TanStackT
TanStack2y ago
1 reply
moderate-tomato

[SOLVED] Not found being presented for working route

I am following the Authenticated Routes docs. I've set up a redirect to occur when the user is not logged in. I apply a redirect search param just like the docs do.

But I am experiencing weird behavior where I can reach a protected route through normal navigation. But refreshing the page (triggering auth again) sends me to the not found component.

I don't perform any other redirect other than what the docs have provided. Why would this happen and how can I fix it?

The protected route:
export const Route = createFileRoute('/_auth-layout/my/protected/route')({
  component: MyProtectedRoute,
  beforeLoad: ({ context }) => {
    if (!context.auth.isAuthenticated) {
      toast.info('Please login to continue', {
        id: 'login-to-continue',
      })
      throw redirect({
        to: '/login',
        search: {
          redirect: location.href,
        },
      })
    }
  },
})


The login route redirecting back to the page when auth is found.
export const Route = createFileRoute('/_auth-layout/login')({
  component: Login,
  validateSearch: z.object({
    redirect: z.string().optional(),
  }),
  beforeLoad: ({ context, search }) => {
    // If user is already authenticated, redirect to the appropriate page
    if (context.auth.user) {
      if (search.redirect) {
        window.location.href = search.redirect
      } else {
        throw redirect({
          to: '/another/page',
        })
      }
    }
  },
})
Was this page helpful?