Server Rendering and Deployment
A reader who opens /lessons/routing directly needs an HTML document before any client navigation can run. Router can match that request URL during React server rendering, but it does not run an HTTP server, choose response statuses, or configure your host’s document fallback.
Use the browser integration only where the native Navigation API is available. For server rendering or fixed-location tests, supply createMemoryNavigation explicitly; it does not add interactive navigation to unsupported browsers.
Render a known request URL
Section titled “Render a known request URL”In a React application with server rendering already configured, a complete src/renderNotebook.tsx module can render a synchronous page:
import { renderToString } from 'react-dom/server'import { createMemoryNavigation, createRouter, Router, useParams,} from '@studiolambda/router/react'
function LessonPage() { const { slug } = useParams() return <h1>Lesson: {slug}</h1>}
const matcher = createRouter((route) => { route('/lessons/:slug').render(LessonPage)})
export function renderNotebook(requestUrl: string) { const navigation = createMemoryNavigation({ url: requestUrl }) return renderToString(<Router matcher={matcher} navigation={navigation} />)}Calling renderNotebook('https://example.com/lessons/routing') returns markup containing Lesson: routing. Supply the absolute incoming request URL, including its query string. The host catches rendering failures, puts the result into its document template, and sends the response. This function is a renderer, not a complete server or hydration setup.
For client hydration, use the same route definitions and initial URL/authorized state so server and client agree. Hydrate with the browser navigation object, not the fixed memory adapter. Router adds no serialization protocol for your data or session state.
Keep access checks request-scoped
Section titled “Keep access checks request-scoped”Server-side guards can prevent protected content from being emitted. If guards depend on a session, create that matcher with dependencies belonging to the incoming request, as in the guard factory example. Do not close over one user’s session in a process-global matcher or cache a private permission result across users.
Initial rendering runs guards, but does not run prefetch. A page’s normal data read must work without a navigation-time warmup. Guards may repeat during server rendering, remounts, StrictMode, and hydration; keep them idempotent and continue to authorize backend requests independently.
A lone synchronous denial can throw during Router initialization. Async guards suspend before middleware/content. Streaming SSR can wait for them; renderToString emits the Suspense fallback for a pending guard instead of awaiting it. Do not send a success/private-content response merely because renderToString returned fallback markup.
For a host already using React’s Web Streams renderer, the essential waiting sequence is:
import { renderToReadableStream } from 'react-dom/server'
const stream = await renderToReadableStream( <Router matcher={matcher} navigation={navigation} fallback={<p>Checking access…</p>} />, { onError: (error) => console.error('server render failed', error) },)await stream.allReadyHere matcher and navigation come from the request’s setup; create the matcher per request when its checks close over a session. Run this fragment in an async handler, or a module that supports top-level await. This is a focused rendering fragment, not an HTTP-response implementation. The host still owns its error flag, status selection, headers, and whether to stream a fallback before all work is ready. A stream becoming ready is not by itself proof that authorization succeeded; inspect the host’s error path before sending a protected response.
Understand the memory adapter
Section titled “Understand the memory adapter”createMemoryNavigation({ url }) retains the URL verbatim and exposes one fixed entry. It implements only the subset used for rendering:
| Member | Behavior |
|---|---|
currentEntry.url | Always the supplied URL |
entries() | A single-entry array |
canGoBack, canGoForward | Always false |
transition | Always null |
navigate, back, forward, traverseTo | Return already-resolved result promises for that same entry |
updateCurrentEntry | No-op |
| Event subscription methods | No-op; no events fire |
It has no real history keys, IDs, entry state, or navigation stack. Other native members can be absent. Calling a missing method can throw, despite the adapter’s Navigation return type. Even back() with canGoBack === false returns the unchanged resolved entry rather than simulating native failure.
Use it to select initial content, not to test clicks, query updates, or transitions. Interactive tests need a native browser or a purpose-built event adapter. See testing.
Serve direct route requests
Section titled “Serve direct route requests”For a client-rendered deployment, configure your host to serve the application document for route GET requests such as /lessons/routing. Preserve the requested URL so Router can match it after startup. A successful internal click does not prove this works: open the URL in a new tab and refresh it after deployment.
Scope the fallback carefully. Keep static asset misses as asset errors, and let API endpoints and POST requests reach their actual backend handlers. Rewriting every method/path to index.html can drop form handling or return HTML where a data request expects JSON.
There is no router basename option. If the app lives under /notebook, include that prefix in your route group and root-relative links, and separately configure your bundler’s asset base and the host’s fallback. URL path prefixing and asset URL generation are different responsibilities.
Own HTTP statuses and redirects
Section titled “Own HTTP statuses and redirects”Rendering a notFound component does not set 404. The host must select its response status. Similarly, .redirect() only runs during intercepted navigation; directly rendering a redirect route produces its null fallback. Configure host redirects for legacy URLs that must work on initial requests and reloads.
For private initial requests, perform the host’s authentication/redirect decision before committing response headers. React error boundaries do not choose HTTP statuses. A router guard does not grant the browser authority to access server resources.
Before release, verify direct deep links, refresh, unmatched URLs, host redirects, unsupported-browser UI, native POST handling, and authorized/denied SSR responses. Those are deployment contracts, not behaviors the memory adapter can prove.