TanStackT
TanStack11mo ago
64 replies
awake-maroon

Can I redirect from the index route?

In nextjs, I can do this to not allow the user to load the index route.

import { redirect } from 'next/navigation';

export default function HomePage() {
  redirect('/dashboard');
}


This causes my auth context provider to fire which force-redirects the user back to dashboard or login screen.

Perhaps there is a better way? The use case I'm trying to solve...

User comes to site for the first time -
localhost:3000/ gets presented the 'sales' page.

User logs in, gets routed to /dashboard
User logs out, gets routed to /login

At any point, if the user is logged in, and tries to hit localhost:3000/ I want the user redirected to /dashboard.

I'm trying to do this, but it doesn't seem to be redirecting me.

export const Route = createFileRoute("/")({
    beforeLoad: ({ context }) => {
        // Log for debugging
        console.log("Auth check with context:", context);
        // Check if user is authenticated
        if (context.auth.user) {
            console.log("User authenticated, proceeding...");
            throw redirect({
                to: "/dashboard",
                search: {
                    redirect: location.href,
                },
            });
        }
    },
    component: HomeComponent,
});
Was this page helpful?