Web / TanStack Interview Questions
How do you implement protected routes and auth redirects in TanStack Router?
Use beforeLoad with throw redirect(). This halts the route loading process before the component ever mounts — no flash of protected content.
import { createRoute, redirect } from "@tanstack/vue-router" import { getAuthToken } from "../auth" async function requireAuth({ location }:any){ if(!getAuthToken()) throw redirect({ to:"/login", search:{ redirect:location.href } }) } export const dashboardRoute=createRoute({ getParentRoute: ()=>rootRoute, path: "/dashboard", component: DashboardPage, beforeLoad: requireAuth, }) export const loginRoute=createRoute({ getParentRoute: ()=>rootRoute, path: "/login", component: LoginPage, beforeLoad: ({ search })=>{ if(getAuthToken()) throw redirect({ to:(search as any).redirect??"/dashboard", replace:true }) }, }) // In LoginPage.vue import { useSearch, useNavigate } from "@tanstack/vue-router" const search=useSearch({ from:"/login" }) const nav=useNavigate() async function handleLogin(creds){ await login(creds) nav({ to:(search as any).redirect??"/dashboard", replace:true }) }
More Related questions...