What you'll learn: By the end of this lesson you will be able to explain what a client-side router does, describe what the History API gives it and what it does not (pushing and replacing are silent), model a route table with layout, index, parameter and catch-all routes, explain how the most specific route wins, build a link that keeps new-tab and crawler behaviour, connect a router to React with a subscribe-and-snapshot store, and test routing without a browser.
Think of a hotel with a front desk. A guest gives a room number (the URL). The desk looks it up in a plan of the building (the route table) and sends the guest down a corridor, past the lobby, to the room. The guest never leaves the building. For a room that does not exist the desk has a procedure, and the corridor behind the guest is remembered, so "go back" is always available.
A client-side router is that front desk for a web app. It watches the address, matches it against a plan, and decides which parts of the screen to show, without asking the server for a new document. The running example is the ShopStream storefront: a shell with navigation, a products section (list and detail) and settings.
The core idea
- The URL is the address of a screen, and the router is the only code that turns an address into screens. React Router's overview puts it this way: client-side routing lets your app update the URL from a link click without requesting another document from the server, and render new UI immediately.
- The browser gives the router a stack, and stays silent about two of its operations.
pushStateandreplaceStatechange the address without a signal;popstatefires only when the user moves between entries. So the router must announce its own navigations. - A route table is architecture. Nested routes couple URL segments to a component hierarchy, so the shape of the table is the shape of your layouts.
Three illustrations run through the lesson: a minimal example (matching paths against a small table), a realistic example (the storefront's history stack and what listeners hear) and a failure example (a layout that forgets where its children go).
Three layers
Figure 1. From the address bar to the screen
How to read this: only the first box touches the browser. The matcher is a pure function, and the React binding only reads snapshots, so each can be tested without the others.
The browser's part: the History API
MDN describes the History API as access to the browser's session history and the ability to manipulate the history stack. Four facts matter for a router.
pushState(state, unused, url)adds an entry andreplaceStatemodifies the current one. The new URL must be of the same origin, and the browser does not load it. Theunusedargument cannot be omitted; an empty string is safe.- Neither one fires
popstate. MDN's popstate page says that just callingpushStateorreplaceStatewill not trigger it.popstatefires when the active entry changes while the user navigates the session history, for example through the back button orhistory.back(). - The
stateobject travels with the entry. It is serialised, some browsers limit its size, andpopstatedelivers a copy of it. - A hash change is a different event.
hashchangefires when the fragment changes, andpushStatenever fires it. Google's JavaScript SEO guidance tells single-page apps to use the History API for routing and not fragments.
Because of the second fact, a router wraps the browser. The lab's adapter performs the change, then tells its own listeners:
push(to, state = null) {
win.history.pushState({ key: `k${counter++}`, usr: state } satisfies Stored, "", to);
notify("PUSH");
},
For back, it does the opposite: it calls win.history.go(delta) and waits for popstate, which then notifies with POP. The lab also has an in-memory history with the same interface, used in tests so a route test needs no window.
Route tables
A route table is a tree. React Router's documentation describes the pieces the lab models.
| Piece | Meaning | Example |
|---|---|---|
| Nested route | The parent's path is included in the child's | products then :id gives /products/:id |
| Layout route | A route without a path: new nesting, no URL segment | the shell with navigation |
| Index route | Renders into the parent's outlet at the parent's URL | the product list at /products |
| Dynamic segment | A segment starting with :, parsed into params |
:id |
| Splat | A pattern ending in /* matches the rest, including slashes |
files/* |
Child routes render through <Outlet /> in the parent. The lab's matcher returns the whole chain from the layout down to the leaf, so each level can render its own part.
Illustration 1: the minimal example
The storefront table is a shell with a home index, a products route (list, :id, new), files/* and settings. In the output captured below, /products/42 renders shell > products > product-detail with id 42, /products/new renders the static product-new route, and /products/42/reviews has no match, so the caller renders a not-found page.
Figure 2. The storefront route table as a tree
How to read this: a path walks from the shell down to one leaf. The chain it walks is the list of components that render, each inside its parent's outlet.
Which route wins
/products/new matches both new and :id (here new could be the id). React Router's overview says it ranks routes by the number of segments, static segments, dynamic segments and splats, picks the most specific match, and says ranking means you do not have to worry about route order.
The lab implements its own small version, and says so in its source: it is a model, not React Router's algorithm. Its rules: compare one segment at a time from the left, static beats param beats splat; for the same pattern the deeper branch wins, so an index route beats its parent; a remaining tie goes to the route declared first. Tests check that a static segment beats a param even when the param route is declared first, and that the result does not depend on declaration order.
Connecting the router to React
A router is a store with a changing value (the location and the match chain). React's useSyncExternalStore is built for that: you give it a subscribe function and a getSnapshot function, and repeated calls to getSnapshot must return the same value while the store has not changed, or React will loop. The lab's router returns a cached state object until the location changes:
getState() {
if (history.location.key !== state.location.key) state = compute(); // read before anyone subscribed
return state;
},
The provider reads it with useSyncExternalStore(router.subscribe, router.getState, router.getState). The third argument is the server snapshot, which React uses during server rendering and hydration; this matters if the same routes are rendered on the server (see rendering strategies).
Figure 3. A click, from link to screen
How to read this: pushState is silent, so the notification in the middle comes from the adapter. Remove that step and the URL changes but the screen does not.
Links stay real links
The lab's Link renders a real <a href> and only turns a plain primary-button click into a client-side navigation:
const onClick = (event: MouseEvent<HTMLAnchorElement>) => {
if (event.defaultPrevented) return;
if (event.button !== 0) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
React Router's reference describes its Link as a progressively enhanced <a href> wrapper for client-side routing, with reloadDocument available when you want the browser to handle the transition. The reason to keep the anchor: Google can only discover links that are <a> elements with an href, and a middle-click, a copied link or a new tab should still work. React Router's guidance is to prefer Link and NavLink for ordinary navigation and to reserve useNavigate for cases where the user is not interacting, such as after a timeout.
Trade-offs
| Choice | What it buys | What it costs |
|---|---|---|
History API URLs (/products/42) |
Clean URLs that crawlers can use | The server must answer these URLs on a direct load |
Hash URLs (/#/products/42) |
Works with any static host | Google advises against fragments for routing |
| One central route table | The whole structure in one place | A shared file everyone edits |
push |
Back returns to the previous screen | A longer stack |
replace |
No back-button clutter (a redirect, a tab switch) | Back skips the replaced entry |
Build it: the router in a model, tested without a browser
Goal. Run the 38 tests (matcher, history, router, React binding, and the browser adapter over jsdom's window.history) and read the demo's three sections.
Setup. The lab is in the course's example workspace (Node 26, pnpm). jsdom is a JavaScript model of the DOM: it has no real back button, tabs, scroll restoration, layout or painting.
cd examples/frontend
pnpm install
cd labs/client-side-routing
pnpm test # 38 tests in 4 files
node src/demo.ts
Steps.
- In
test/matcher.test.tsread the ranking tests. Intest/browserHistory.test.tssee thatpushStateandreplaceStatefire nopopstate, while going back does, with the state of the entry returned to. - Run the demo. Section 1 lists the branches most specific first, section 2 matches ten paths, and section 3 walks a history stack through push, replace, back and a forward with nothing ahead.
- In section 3, notice that
backleaves the later entry in the stack (it is still there to go forward to), and that in the lab's model pushing after going back drops it.
Expected output, captured from a real run (Node 26.12.1, 2026-11-08):
=== 1. branches in match order (most specific first)
1. /products/new -> shell > products > product-new
2. /settings/profile -> shell > settings > settings-profile
3. /products/:id -> shell > products > product-detail
4. /files/* -> shell > files
5. /products -> shell > products > product-list
6. /settings -> shell > settings > settings-home
7. /products -> shell > products
8. /settings -> shell > settings
9. / -> shell > home
=== 2. matching
/ shell > home params={}
/products shell > products > product-list params={}
/products/new shell > products > product-new params={}
/products/42 shell > products > product-detail params={"id":"42"}
/products/a%20b shell > products > product-detail params={"id":"a b"}
/files/a/b/c shell > files params={"*":"a/b/c"}
/settings/profile shell > settings > settings-profile params={}
/settings/ shell > settings > settings-home params={}
/nope no match (render the not-found page)
/products/42/reviews no match (render the not-found page)
=== 3. a history stack and what listeners hear
start stack: [/] | renders: home
listener: PUSH now at /products
push /products stack: / [/products] | renders: product-list
listener: PUSH now at /products/42
push /products/42 stack: / /products [/products/42] | renders: product-detail
listener: REPLACE now at /products/42?tab=reviews
replace with ?tab=reviews stack: / /products [/products/42?tab=reviews] | renders: product-detail
listener: POP now at /products
back stack: / [/products] /products/42?tab=reviews | renders: product-list
listener: POP now at /
back stack: [/] /products /products/42?tab=reviews | renders: home
listener: PUSH now at /settings
push /settings stack: / [/settings] | renders: settings-home
forward (nothing ahead) stack: / [/settings] | renders: settings-home
What the lab does not show. No real browser: the real back button, tabs, scroll restoration and focus handling are outside it. The matcher is the lab's own model and not React Router's algorithm, and there is no server, prerendering or data loading.
Break it. (1) In src/matcher.ts, change segment.startsWith(":") ? 1 : 2 to segment.startsWith(":") ? 2 : 1, so a param outranks a static segment. (2) In src/react.tsx, delete the line that returns on metaKey, ctrlKey, shiftKey or altKey. With both changes applied together, 7 of the 38 tests failed: three ranking tests, and the ctrl, meta, shift and alt link tests. Revert both and run the tests again: all 38 pass.
Stretch. Add an optional segment (:lang?) to the matcher and decide where it ranks, with tests for each case.
In practice: shared links to a storefront that 404
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The ShopStream storefront moves from server-rendered pages to a single-page app with a client-side router. In testing, everything works: clicking from the list to a product shows the detail. After release, customers who open a shared link such as /products/42 in a new tab get an error page (illustrative).
Starting architecture
Figure 4. Starting point: the host only knows one file
How to read this: in-app clicks never ask the host anything, so they work. A direct load asks the host for a path it has no file for.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Rewrite app routes to the shell document | Direct loads reach the router | Host configuration and a list of valid paths | An unknown URL gets the shell with a 200 status (a soft 404) |
| Prerender each route to its own HTML file | Real documents per URL, usable by crawlers | A build step and a list of paths | Stale pages until rebuilt |
| Switch to hash URLs | No server change | Less readable URLs | Google advises against fragments for routing |
The decision
| Field | Decision record |
|---|---|
| Context | Direct loads of client-side routes fail; unknown URLs must still look like errors. |
| Decision | Prerender the known routes, route the rest to a not-found document that the host serves with a 404 status, and keep the router's own not-found page for in-app navigation. |
| Consequences, good | Shared links work; unknown URLs return 404 instead of an empty shell. |
| Consequences, bad | The route list is now needed at build time and must stay in step with the table. |
| Revisit when | Routes depend on data that changes often. Consider server rendering for those. |
Rollout and verification
- Generate the list of paths from the route table instead of keeping a second list.
- Check every known path returns its own document, and a made-up path returns a 404 status.
- Test in-app navigation and direct load of the same route and compare what renders.
- Watch error and 404 rates after release.
The 2 a.m. failure
A merchant team adds /products/new-arrivals as a static route. A cached older shell, still served to some browsers, has no such route: its router treats new-arrivals as an :id and asks the catalogue for a product that does not exist (illustrative). First three checks: (1) compare the route table in the served bundle with the deployed one; (2) look at the request for the id new-arrivals in the network panel or logs; (3) check cache headers on the shell document. Mitigation: make the product page render the not-found state when the catalogue says the id does not exist, and serve the shell with revalidation. Follow-up: a test that every static route outranks :id, and a test for the not-found state of the detail page.
Architect's notes
- Make the URL the source of truth for "where". Whatever must survive a reload or a shared link belongs in the URL, not in component state.
- Keep the matcher pure and the history adapter thin, so routing is tested without a browser.
- Generate anything that lists routes (sitemap, prerender list) from the route table.
- Decide push or replace deliberately. A redirect should replace; a new screen should push.
- Handle the unknown URL twice: a not-found screen in the app and a real 404 status from the host.
Common mistakes
- Using
<div onClick>or a barenavigatecall instead of a link. New tabs, copied links and crawlers stop working. - Intercepting every click, including modified ones.
- A layout route that forgets
<Outlet />, so its children never render (the lab's test shows it). - Returning a new object from
getSnapshotevery call, which makes React loop. - Serving the app shell with a 200 status for every unknown URL. Search engines see soft 404s.
- Assuming
pushStatefires an event. It does not, so something must notify the router.
Key takeaways
- A client-side router turns an address into a chain of routes without requesting a new document.
pushStateandreplaceStateare silent; only history traversal firespopstate, so the router notifies its own listeners.- A route table is a tree; layout routes add nesting without a URL segment, index routes fill the parent's outlet.
- The most specific route wins, which makes route order irrelevant.
- Connect the router to React with subscribe and a cached snapshot.
- Keep links as real
<a href>elements and intercept only plain clicks. - Direct loads and unknown URLs need a host strategy: rewrite, prerender and a real 404.
Practice exercises
Exercise 1 — Starter (45 min): Write the route table for a site you know as a tree: layouts, index routes, one parameter and one catch-all. Predict which route wins for five paths, then check with the lab's matcher.
Exercise 2 — Intermediate (2 hours): Add a NavLink to the lab that reports whether its target is the current location, with a test for exact and prefix matching.
Exercise 3 — Advanced (half day): Extend the history adapter to block a navigation (an unsaved-changes prompt), decide what back should do when it is blocked, test it with jsdom and list what you cannot verify without a real browser.
Related reading
In this course:
- Feature-Based and Modular Folder Structure, where route modules and feature folders meet.
- Code Splitting, Lazy Loading and Tree Shaking, loading a route's code on demand.
- Rendering Strategies, how routes are rendered on the server or at build time.
- SEO Architecture, crawlable URLs, links and status codes.
- Component-Based Architecture, the components a route chain renders.
Official documentation
- MDN: History API, pushState, replaceState and the popstate event.
- React Router: Routing, nested, layout, index, dynamic and splat routes, and Navigating and Link.
- React Router 6.30 overview, client-side routing, nested routing and route ranking.
- React: useSyncExternalStore, subscribing to an external store.
- Google Search Central: JavaScript SEO basics, History API routing, links and soft 404s.