Skip to content

Route Guards

A private screen must not briefly render before your application checks access. A guard is a mandatory check that finishes before the matched page’s middleware/content, and before prefetch or a custom form action during intercepted navigation.

Guards are UI and dispatch gates, not server authorization. A user can call your endpoint without visiting the route. Authenticate and authorize every server request independently, including native forms and speculative reads.

Start with an existing AccountPage component. This application-owned factory accepts a permission-checking dependency so the router does not prescribe session storage or an authentication service:

import { createRouter } from '@studiolambda/router/react'
import AccountPage from './AccountPage'
export function createAccountRoutes(canRead: (path: string) => Promise<boolean>) {
return createRouter((route) => {
route('/account')
.guard(async ({ url }) => {
if (!(await canRead(url.pathname))) throw new Error('access denied')
})
.render(AccountPage)
})
}

Supply your actual session/permission function and pass the returned matcher to Router. A guard receives { params, url }: the matched encoded parameter record and full destination URL. Treat both as read-only. Returning normally or resolving allows the operation; throwing or rejecting denies it. Returning false is not a denial protocol.

Guards have no redirect controller. Throw to deny, then let your application choose how to report or recover from that failure. For an initial server request, the host can respond with a login redirect or error status before sending protected HTML; the router does not generate that response for you.

With application-owned requireSession and requireEditor checks plus existing page components, build a hierarchy:

const matcher = createRouter((route) => {
const account = route('/account').guard(requireSession).group()
account('/').render(AccountPage)
account('/edit').guard(requireEditor).render(AccountEditor)
})

At /account/edit, requireSession runs first, then requireEditor. If either fails, later checks, prefetch, and the action/content do not run. All guards finish before all prefetch callbacks. Sibling pages do not inherit a guard attached only to /edit.

Keep checks idempotent: they can read permissions, but should not perform a mutation such as recording a payment or consuming a one-time token. Remounts, React StrictMode, server rendering, and hydration can repeat them. For SSR, close over request-scoped session data rather than sharing one user’s session promise through a process-global matcher.

SituationGuard behavior
Initial client renderRuns before middleware/content
Initial server renderRuns before protected HTML is rendered
Cancelable intercepted navigationRuns before prefetch and URL commit
Noncancelable intercepted navigationRuns after URL commit, before prefetch/UI update
Opted-in custom form actionRuns before prefetch and action dispatch
Hover/viewport/manual speculative prefetchDoes not run
Native POST without a formHandlerDoes not run; the server owns submission

This is why a check belongs in .guard(), not .prefetch() or a render wrapper. Prefetch does not run initially and can run speculatively without guards. Middleware runs only when React renders and cannot gate actions. See prefetching and form ownership before combining them with private routes.

An asynchronous initial guard suspends before rendering any route middleware or content. Router’s fallback can show Checking access… while it waits. A single synchronous guard can throw during Router initialization; multiple composed guards form an asynchronous chain even if each callback is synchronous.

Place an error boundary above Router, as in the quickstart, for initial client denial. A boundary inside middleware is too late for a synchronous initializer failure and is not mounted while the initial guard is pending. Suspense handles waiting, not rejection.

Streaming server rendering can await asynchronous checks. renderToString instead emits the Suspense fallback for pending checks; do not mistake that output for completed authorization. The host owns HTTP status, redirects, and server-side error reporting. See server rendering.

A failed intercepted check rejects the native navigation and is reported through onNavigateError plus the native result promises. It does not automatically replace the current page with an error component. For a noncancelable event, the URL may already be committed; rejecting the guard keeps old React content but cannot restore that URL.

Provide deliberate application-level failure UI or recovery rather than assuming a denied navigation always leaves the address bar untouched. Redirects and Errors maps each failure path to the owner that can handle it.