Skip to content

setGuard

setGuard(newGuard): RouteGuard

Defined in: route.ts:159

Register a navigation guard, or unregister it by passing null. At most one guard can be registered at a time; the previously registered guard (or null) is returned, so a temporary guard can be chained or restored later.

The guard is consulted before any navigation is applied — any change of history entry, meaning go / push, back / up, and the browser’s own back/forward buttons (popstate) — as well as before in-place changes to path or search through the current proxy. Same-page tweaks — mutating current.state (like persistScroll saving scroll positions) or current.hash, and the browser jumping to a #fragment — are applied without consulting the guard.

When the guard returns (a promise of) false:

  • a go()/back()/up() call does nothing, and reports false;
  • a browser back/forward is undone, by travelling the exact number of history entries back to where we were — the depth delta is known, so even a multi-entry jump (a long-press on the back button) restores correctly;
  • a direct route.current mutation is reverted in place. With an async guard the proxy is reverted while the verdict is pending and re-applied if it passes — prefer go() for changes a guard may need to think about.

While a verdict is pending, other attempted route changes are refused. A browser navigation arriving in the meantime supersedes the change the guard was being asked about — that change is dropped (reporting false) and, once the verdict settles, the guard is consulted about wherever the browser has ended up instead.

The guard is invoked outside of any reactive scope (reading proxied state in it doesn’t subscribe anything), and receives plain copies of the routes, so mutating them has no effect. A guard that throws counts as a veto. A guard may itself navigate, enabling the redirect pattern:

route.setGuard(to => {
if (to.path.startsWith('/admin') && !user.isAdmin) {
route.go('/login'); // recursively consults (and passes) the guard
return false;
}
return true;
});

RouteGuard

RouteGuard