Skip to content

Redirects and Errors

An old bookmark should reach the replacement page without rendering the abandoned screen. A redirect route retargets an intercepted navigation before the URL commits. It is not an HTTP redirect response and does not run on the first document load.

Start with a route table and a host that handles direct requests. If users can arrive at an old URL from outside your app, configure the corresponding server redirect too; otherwise the initial redirect-route component renders nothing.

With your existing LessonPage component, register the replacement route and then the alias:

import { createRouter } from '@studiolambda/router/react'
const matcher = createRouter((route) => {
route('/lessons/:slug').render(LessonPage)
route('/learn/:slug').redirect(({ params, url }) => {
return `/lessons/${params.slug}${url.search}${url.hash}`
})
})

An eligible cancelable push/replace to /learn/routing?view=notes#summary becomes /lessons/routing?view=notes#summary. The target receives its own matched params and full URL. Query and hash are only preserved because the callback includes them.

Use root-relative absolute paths. Group prefixes affect the source registration, not the redirect target. For example, a /legacy group containing old('/lesson').redirect('/lessons') still targets /lessons, not /legacy/lessons.

Only construct destinations from trusted application routes and validated user input. An active-link match or a pathname capture is not proof that a redirect destination is safe. Do not turn an arbitrary returnTo query value into an open redirect.

The source route’s guards run first, then its inherited/local prefetch callbacks, then its configured redirect. An earlier prefetch redirect stops later callbacks in the abandoned chain, including the configured redirect if it has not run yet.

After a successful redirect, Router rematches the new destination and awaits its guards, then its prefetch. This repeats until a destination completes without redirecting. A denial at any target stops the navigation. No source page is rendered along the way.

Redirect handlers inherit guards and prefetch, but not middleware, scroll, focus-reset, or form-handler configuration. Scroll/focus interception options remain those of the first matched handler, because native interception options are fixed during event dispatch; they are not recalculated from a later target.

Exact static-string cycles such as /a → /b → /a throw while createRouter builds the table. Callback targets are checked at runtime. Repeating a full URL, including query/hash, or exceeding 20 redirects rejects navigation. An unmatched final target renders Router’s notFound component.

Native precommit redirects require a cancelable push/replace navigation. Traverse and reload redirects reject, even if the event is cancelable. Noncancelable events have already committed their URL; their controller throws InvalidStateError for redirect() and addHandler().

Router does not repair these cases by starting another navigation. Prefer host redirects for URL migrations that must work for direct loads and reloads, and do not depend on a redirect route for an unconditional history-traversal policy.

A speculative preload receives a no-op controller: it neither navigates nor recursively preloads the target. Initial rendering does not execute redirect prefetch at all. These limits are why redirect routes are not a substitute for mandatory guards.

Different phases have different recovery owners:

FailureWhat happensHandle it with
Duplicate/conflicting pattern, missing path, consumed builder, static cycleRoute-table construction throwsFix startup configuration
Initial synchronous guard denialRouter initialization throws before contentAncestor client error boundary or SSR host
Initial asynchronous guard denialSuspended check rejects before contentAncestor client error boundary or SSR host
Route/middleware render or lazy import failureReact render failsReact error boundary
Intercepted guard/prefetch/action rejectionNative navigation fails; no automatic error-page replacementonNavigateError and initiating result promises
No complete pattern matchnotFound rendersA useful missing-page component

Use the quickstart’s error boundary above Router. A Suspense fallback is waiting UI, not error recovery. Keep detailed errors out of public production fallbacks: an error message can contain request, session, or application details. Send diagnostics to your application-owned reporting system instead.

For native failures, pass onNavigateError to Router and observe both promises from any useNavigate, history, or search-parameter call you initiate. These are complementary responsibilities: a lifecycle observer does not turn the caller’s rejecting promises into successful promises.

On a precommit check failure, Router does not update the rendered match. On a postcommit failure, it also keeps the old rendered route, but cannot roll back the already committed browser URL. The application must decide whether to show a notification, offer a deliberate navigation to a safe page, or let the user retry. Avoid automatic retry loops in a global error callback.

An action failure does not undo a server mutation that already succeeded. Native event cancellation can stop cooperating requests, but does not create a transaction. If repeating a submission would be harmful, implement idempotency and transactional rules at the server boundary.

For custom POST actions that redirect during precommit, Router discards action dispatch and renders the checked target. It never forwards the original submitted body to the target’s action. See forms before combining redirects with mutations.