Route Guards
Route guards run in the browser on SPA navigation. They improve UX (redirects, spinners) but are not a security boundary — they never see a first load, curl, or a crawler. For real auth on pages, API routes, and loader data, use Middleware (app/_middleware.js) on the server and compose a client guard for the SPA feel.
Add app/routeGuard.js and it is discovered automatically. It runs before each client navigation and can be async.
export default async function routeGuard(to, { next, redirect }) { if (to.pathname.startsWith("/admin") && !(await isLoggedIn())) { return redirect("/login"); } return next(); }
| Argument | Description |
|---|---|
to | The target route: pathname, fullPath (pathname + query + hash), params, and query. |
next() | Allow the navigation. |
redirect(path) | Cancel and navigate elsewhere. |
replace(path) | Redirect without adding a history entry. |
to.fullPath is handy for redirect-then-return flows — e.g. redirect("/login?next=" + encodeURIComponent(to.fullPath)).
Return one of next, redirect, or replace from every path so navigation never stalls.
Mirror the same rules in app/_middleware.js so direct URL hits and SSR are guarded before HTML is sent. See Middleware.