Route Guards

Route guards run in the browser during initial app mounting and later SPA navigation. They can redirect the UI, but they cannot prevent the server from sending HTML or data to a direct request. For authentication 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. The routes plugin exports it as guard; pass that export to mountApp({ pages, guard, target }), as in the browser entry example. The guard runs before each client navigation and can be async.

JavaScript
export default async function routeGuard(to, { next, redirect }) {
  if (to.pathname.startsWith("/admin") && !(await isLoggedIn())) {
    return redirect("/login");
  }
  return next();
}
ArgumentDescription
toThe target route: pathname, fullPath (pathname + query + hash), params, and query.
next()Allow the navigation.
redirect(path)Cancel and navigate elsewhere, replacing the history entry.
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)).

Always resolve

Return one of next, redirect, or replace from every path so navigation never stalls.

Pair with middleware

Mirror the same rules in app/_middleware.js so direct URL hits and SSR are guarded before HTML is sent. See Middleware.

Last updated on
Edit this page