Chapter 11: Building a router
The chapter previews building a client-side router from matched routes, including rendering, browser-cue updates, and view transitions.
After this chapter you will be able to
- Rendering prerequisites. Explain why rendering follows route matching and which decisions should be clear before it begins: the view’s URL, matched pattern, needed parameters and query values, destination element, and browser cues to update.
- Small router render contract. Describe the simple render contract: a route handler returns a title and DOM node, and the router replaces the current view and updates associated browser cues.
- Stable shell and route outlet. Explain what an outlet and an app shell are, and why the router replaces the outlet rather than the whole document. Describe how the same arrangement can be owned by a Web Component.
- Route content replacement. Explain how a route can render by creating the next view and replacing the outlet’s old content with replaceChildren().
- Replacement versus hidden views. Distinguish when showing and hiding prebuilt views is appropriate from when replacing route content is preferred, and explain the drawbacks of hidden route trees.
- Same-document route details. Explain why rendering a new view is not enough during same-document navigation, and describe the title, canonical URL, and active navigation state the router may need to update.
- Active navigation link cues. Explain how to mark an active navigation link and choose a matching rule that fits the menu.
- Post-navigation focus placement. Explain why a client-side router should move focus after navigation and how it can focus a heading or main region without changing the normal Tab order.
- Scroll behavior by navigation type. Distinguish the expected scroll behavior for a new route, Back or Forward navigation, and a URL with a hash fragment.
- Browser and router restoration strategies. Explain why automatic restoration can be unreliable in a same-document SPA and describe the two strategies given for controlling it.
- Router and component responsibilities. Explain how a router uses Web Components as route views while keeping navigation concerns separate from component internals.
- Route guard purpose. Explain what a route guard checks, when it runs, and why a route might require one.
- Guard placement by navigation API. Describe where guards run with the Navigation API and the History API fallback, and how navigation proceeds only when the destination is allowed.
- Unknown routes versus route errors. Distinguish a URL that matches no route from a matched route whose data loading or rendering fails, and explain the different responses each calls for.
- Programmatic route navigation flow. Explain when code may need to initiate navigation and how navigation.navigate() can use the router’s existing navigate event handler instead of a separate rendering path.
- History fallback rendering. Describe why a History API fallback must render explicitly after pushState() or replaceState(), unlike a helper that delegates to an intercepted Navigation API flow.
- Push versus replace choices. Explain when to push a new history entry and when to replace the current one during programmatic navigation.
- History entry state boundaries. Describe what belongs in history entry state versus the URL, and how the Navigation API and History API store, read, or update entry state.
- Optional route change animation. Explain why View Transitions can improve route changes without becoming part of routing itself.
- Same-document transition sequence. Trace how a router uses document.startViewTransition() to animate a route update: it passes a DOM-updating callback, and the browser captures the old and new views before animating between them.
- Browser-coordinated document transitions. Explain how a cross-document view transition differs from a same-document transition: two separate pages opt in with CSS, and the browser animates an eligible navigation rather than the app calling document.startViewTransition().
- Eligible navigation conditions. State the conditions for a cross-document transition: both documents must opt in, navigation must remain on the same origin, and a cross-origin redirect breaks the transition.
- Accessible route motion. Explain why route transitions must accommodate user comfort and remain optional to the route’s meaning and function.
- Reduced-motion transition controls. Distinguish what the CSS reduced-motion rules do for same-document and cross-document View Transitions, and when the JavaScript router should also skip starting a transition.
- Minimal function-based router. Describe the pieces needed for this first router: an existing matcher, an outlet, a render function, and one event listener for back-and-forward navigation. Explain that popstate makes back-and-forward traversal work.
- Router contract and rendering flow. Trace how a route handler’s title and Node view move through the class-based router: #getCurrentPath selects a path, #resolve matches it, and #render updates the page.
- URL-backed tab selection. Explain why each tab is a route and why the selected tab is represented by the URL rather than hidden in component state.
- Simple tab route mapping. Describe the small setup for routing a tab view and distinguish its navigation behavior from its visual styling.
- Three routing responsibility layers. Describe the roles of the app shell, router module, and page components, and explain why matching and navigation logic can be kept separate from presentation.
What it builds on
- Route matching (chapter 10) · A route has already been matched before its view is rendered.
- Client-side router (chapter 10) · The idea of a client-side router changing the displayed route.
- The server (chapter 10) · The server’s role in serving navigation requests.
- The Navigation API (chapter 10) · Navigation API interception provides the event used for the recommended strategy.
- Cancellation with event.signal (chapter 10) · The navigation cancellation signal supplied through event.signal.
- History API fallback (chapter 10) · History API fallback navigation
- Route state (chapter 10) · The idea of route state.
- Navigation interception (chapter 10) · Navigation interception supplies the context for the handler and hash check.
Section by section
Introduction
The chapter previews building a client-side router from matched routes, including rendering, browser-cue updates, and view transitions.
11.1 Rendering routes
This section explains what must be decided before a matched route is rendered and sketches a simple contract for rendering it.
- Rendering prerequisites: Explain why rendering follows route matching and which decisions should be clear before it begins: the view’s URL, matched pattern, needed parameters and query values, destination element, and browser cues to update.
Why it matters: These decisions give the rendering step a clear view to show and a clear place to show it. - Small router render contract: Describe the simple render contract: a route handler returns a title and DOM node, and the router replaces the current view and updates associated browser cues.
Why it matters: The contract separates what a route supplies from what the router does when displaying it.
Key terms: route, route pattern, parameters, query values, render contract, route handler, title, DOM node, document metadata, active links
11.1.1 Outlet and master pages
Explains how a router renders changing route content inside a replaceable outlet while keeping the surrounding app shell in place.
- Stable shell and route outlet: Explain what an outlet and an app shell are, and why the router replaces the outlet rather than the whole document. Describe how the same arrangement can be owned by a Web Component.
Why it matters: This separation lets route content change without rebuilding UI that should stay on screen.
Key terms: outlet, app shell, master page, #route-outlet
11.1.2 Using DOM APIs
This section compares replacing an outlet’s DOM content with showing and hiding prebuilt views, and recommends replacement for application routes.
- Route content replacement: Explain how a route can render by creating the next view and replacing the outlet’s old content with replaceChildren().
Why it matters: This gives the reader a simple default for updating the view when a route changes. - Replacement versus hidden views: Distinguish when showing and hiding prebuilt views is appropriate from when replacing route content is preferred, and explain the drawbacks of hidden route trees.
Why it matters: Choosing between these approaches helps avoid unwanted leftover content and behavior across application routes.
Key terms: replaceChildren(), outlet, DOM replacement, show/hide, route-level rendering, hidden route trees
11.1.3 Title and metadata
Explains which document details a router must update after rendering a route and why public-facing metadata also needs a server-provided source.
- Same-document route details: Explain why rendering a new view is not enough during same-document navigation, and describe the title, canonical URL, and active navigation state the router may need to update.
Why it matters: A route change should update the browser’s description of the view and help users tell where they are. - Public metadata delivery: Distinguish useful client-side metadata updates from the server-provided metadata needed for public content and social sharing.
Why it matters: Metadata changed in one browser session may not be what a social app or other visitor receives on a fresh request.
Key terms: same-document navigation, document.title, canonical URL, active navigation state, social sharing metadata, server-rendered, statically generated metadata, discoverability
11.1.4 Active navigation and focus
Explains how a client-side router restores navigation cues by marking the active link and moving focus after a route change.
- Active navigation link cues: Explain how to mark an active navigation link and choose a matching rule that fits the menu.
Why it matters: The active-link cue helps users tell where they are after navigation. - Post-navigation focus placement: Explain why a client-side router should move focus after navigation and how it can focus a heading or main region without changing the normal Tab order.
Why it matters: Moving focus restores a cue that users would otherwise lose when the router changes views without loading a new document. - Temporary tabindex cleanup: Describe when a router needs to remove the tabindex used for post-navigation focus.
Why it matters: Cleanup depends on whether the focused element survives the route change, rather than being a requirement for every view.
Key terms: aria-current="page", aria-current="true", exact-match comparison, path prefix, same-document navigation, focus, heading, <main>, tabindex="-1", tabindex
11.1.5 Scroll restoration
Explains the scroll behavior users expect from a router and how to restore the right position at the right time.
- Scroll behavior by navigation type: Distinguish the expected scroll behavior for a new route, Back or Forward navigation, and a URL with a hash fragment.
Why it matters: The right scroll destination depends on how the user navigated. - Browser and router restoration strategies: Explain why automatic restoration can be unreliable in a same-document SPA and describe the two strategies given for controlling it.
Why it matters: Choosing who controls restoration prevents an SPA from scrolling against content that has not been rendered yet. - Restoration timing with delayed content: Explain when to restore scroll after rendering and why asynchronously loaded route content may require waiting or reserving space.
Why it matters: Restoring too early can put the user at the bottom of an incomplete page instead of where they left off.
Key terms: new route, Back or Forward, hash fragment, scroll position, history.scrollRestoration, auto, manual, Navigation API, event.scroll(), history entry state
11.1.6 Using web components
This subsection shows how a router can select Web Component pages, pass them route data and cancellation signals, and leave each component responsible for its own UI.
- Router and component responsibilities: Explain how a router uses Web Components as route views while keeping navigation concerns separate from component internals.
Why it matters: This separation lets page components focus on their screens without making every component depend on the router. - Navigation cancellation signal handoff: Trace how a navigation's AbortSignal reaches a page component and what the component can use it for.
Why it matters: Passing the signal helps a page stop an unfinished fetch when the user navigates away.
Key terms: Web Component, router, app shell, route data, outlet replacement, event.signal, AbortSignal, route handler, page component
11.1.7 Route guards
This section explains how route guards check a destination before rendering and either allow, cancel, or redirect navigation.
- Route guard purpose: Explain what a route guard checks, when it runs, and why a route might require one.
Why it matters: A guard keeps a restricted route from rendering when its condition is not met. - Guard placement by navigation API: Describe where guards run with the Navigation API and the History API fallback, and how navigation proceeds only when the destination is allowed.
Why it matters: The check must happen at the right point so a disallowed destination does not render. - Route metadata guards: Explain how route metadata can let a router apply an authentication guard centrally.
Why it matters: Route metadata keeps the access rule attached to the route without repeating checks across handlers.
Key terms: route guard, authentication, navigate listener, event.preventDefault(), pushState, popstate, meta property, requiresAuth
11.1.8 Not found and route errors
Distinguishes an unknown route from a failure in a matched route and explains why each needs different handling.
- Unknown routes versus route errors: Distinguish a URL that matches no route from a matched route whose data loading or rendering fails, and explain the different responses each calls for.
Why it matters: Handling these cases separately keeps missing URLs from looking like crashes and prevents real failures from being hidden as 404s.
Key terms: Unknown route, Route error, not-found view, server 404
11.2 Navigating to new routes
Explains how to start route changes from JavaScript, choose history behavior, and store small amounts of route-local state without replacing shareable URL state.
- Programmatic route navigation flow: Explain when code may need to initiate navigation and how navigation.navigate() can use the router’s existing navigate event handler instead of a separate rendering path.
Why it matters: A single route-handling flow keeps programmatic and link-driven navigation consistent. - Navigation completion promises: Distinguish the committed and finished promises returned by navigation.navigate(), and explain why a routing helper usually awaits finished.
Why it matters: A caller may need to wait for the route to render, not merely for the address to change. - History fallback rendering: Describe why a History API fallback must render explicitly after pushState() or replaceState(), unlike a helper that delegates to an intercepted Navigation API flow.
Why it matters: Without an explicit render, a fallback can change the address while leaving the old view on screen. - Push versus replace choices: Explain when to push a new history entry and when to replace the current one during programmatic navigation.
Why it matters: The choice determines whether Back returns to the prior route or skips a location that has been corrected or superseded. - History entry state boundaries: Describe what belongs in history entry state versus the URL, and how the Navigation API and History API store, read, or update entry state.
Why it matters: Keeping shareable state in the URL preserves meaningful addresses while entry state restores local view details.
Key terms: real links, navigation.navigate(), navigate event, event.intercept(), committed, finished, History API, pushState(), replaceState(), popstate
11.3 View transitions for route change
Introduces View Transitions as an optional way to smooth route changes and distinguishes transitions within a document from those between documents.
- Optional route change animation: Explain why View Transitions can improve route changes without becoming part of routing itself.
Why it matters: You can add smoother navigation without making animation necessary for navigation to work. - Two transition contexts: Distinguish same-document transitions from cross-document transitions by what changes and where each is useful.
Why it matters: The distinction tells you whether the animated change stays within one document or moves between documents.
Key terms: View Transitions, routing, same-document view transitions, cross-document view transitions, SPA, MPAs, hybrid apps, same-origin
11.3.1 View Transitions API
This section explains how to animate a same-document route update with the View Transitions API while keeping animation optional.
- Same-document transition sequence: Trace how a router uses document.startViewTransition() to animate a route update: it passes a DOM-updating callback, and the browser captures the old and new views before animating between them.
Why it matters: It lets the router change views without implementing the animation between them itself. - Transition CSS targets: Describe how CSS can customize a view transition, including the default whole-document root transition, its outgoing and incoming pseudo-elements, and the option to name specific elements.
Why it matters: These CSS targets let you adjust the animation without changing how the router updates the DOM. - Optional restrained animation: Justify treating view transitions as a progressive enhancement and describe the section’s advice to start with short, simple opacity changes rather than relying on elaborate motion.
Why it matters: The route remains usable even when no transition plays, and restrained motion avoids making navigation feel overdesigned.
Key terms: View Transitions API, document.startViewTransition(), callback, same-document transitions, root transition, ::view-transition-old(root), ::view-transition-new(root), view-transition-name, progressive enhancement, opacity
11.3.2 Cross-document view transitions
This section explains how browsers can animate eligible same-origin navigations between separate documents while preserving normal document navigation.
- Browser-coordinated document transitions: Explain how a cross-document view transition differs from a same-document transition: two separate pages opt in with CSS, and the browser animates an eligible navigation rather than the app calling document.startViewTransition().
Why it matters: MPAs and hybrid apps can gain smoother transitions without becoming same-document SPAs. - Eligible navigation conditions: State the conditions for a cross-document transition: both documents must opt in, navigation must remain on the same origin, and a cross-origin redirect breaks the transition.
Why it matters: These conditions determine whether the browser can provide the transition. - Progressive enhancement fallback: Explain why cross-document view transitions can be treated as a progressive enhancement, and why production use still calls for checking current browser support.
Why it matters: The site can retain working navigation even where the animation is unavailable.
Key terms: cross-document view transitions, same-origin navigation, document.startViewTransition(), opt in, same origin, cross-origin redirects, Baseline status, progressive enhancement, normal document navigation
11.3.3 Motion and accessibility
This section explains how to keep route transitions accessible, especially for users who prefer reduced motion.
- Accessible route motion: Explain why route transitions must accommodate user comfort and remain optional to the route’s meaning and function.
Why it matters: Navigation should remain comfortable and usable whether or not a transition plays. - Reduced-motion transition controls: Distinguish what the CSS reduced-motion rules do for same-document and cross-document View Transitions, and when the JavaScript router should also skip starting a transition.
Why it matters: Removing an animation is different from avoiding the transition work altogether.
Key terms: reduced motion, route transitions, prefers-reduced-motion, View Transitions, ::view-transition-group(*), document.startViewTransition()
11.4 Building a tiny Vanilla router
Introduces a two-pass plan for building a small Vanilla router, starting with a function and later refactoring it into a class.
11.4.1 First pass: a function-based router
Introduces a minimal function-based router for back-and-forward navigation and explains when its limitations justify a class.
- Minimal function-based router: Describe the pieces needed for this first router: an existing matcher, an outlet, a render function, and one event listener for back-and-forward navigation. Explain that popstate makes back-and-forward traversal work.
Why it matters: This identifies the smallest routing arrangement the section says is sufficient for history traversal. - First-pass limits and refactor: Distinguish what this first pass handles from what it does not, and explain why adding those responsibilities motivates a class.
Why it matters: It clarifies both the first pass’s boundaries and the reason for the next refactor.
Key terms: matcher, outlet, render function, popstate, link clicks, Navigation API, focus, scroll, transitions, class
11.4.2 Second pass: a class-based router
This section outlines a small class-based router’s contract and rendering flow, then explains two interception details and why the router remains deliberately limited.
- Router contract and rendering flow: Trace how a route handler’s title and Node view move through the class-based router: #getCurrentPath selects a path, #resolve matches it, and #render updates the page.
Why it matters: These distinct responsibilities make the router’s rendering flow easier to follow. - Navigation enhancement choices: Describe the small router’s stated navigation choices: it declares routes with addRoute, uses Navigation or a History API fallback, matches with URLPattern or regex, and can animate same-document updates when View Transitions are available.
Why it matters: The class can use newer browser features without making them prerequisites for routing. - Interception edge cases: Explain why the interception code checks hashes and uses an arrow function for its handler.
Why it matters: These details prevent ordinary anchor navigation and private-method calls from breaking during interception. - Deliberately limited router scope: Justify why nested routes, prefetching, data loaders, and extensive route guards are left out of this small router.
Why it matters: Keeping the initial router small avoids adding features without a project requirement.
Key terms: handler, title, view, Node, #getCurrentPath(url?), #resolve(path), addRoute(path, handler), Navigation, History API, URLPattern
11.4.3 Using the router for a tab view
This section uses a tab view to show how a small router can map real links and URLs to views.
- URL-backed tab selection: Explain why each tab is a route and why the selected tab is represented by the URL rather than hidden in component state.
Why it matters: A tab selection can behave like ordinary web navigation instead of disappearing when the page reloads. - Simple tab route mapping: Describe the small setup for routing a tab view and distinguish its navigation behavior from its visual styling.
Why it matters: Keeping links, route matching, and styling in their respective roles makes the tab router easier to build.
Key terms: route, URL, Back and Forward, real links, route matching, CSS, route handlers
11.5 Building a web component-based router
This section explains how an existing routing approach fits into a web component architecture by assigning responsibilities to an app shell, router, and page components.
- Three routing responsibility layers: Describe the roles of the app shell, router module, and page components, and explain why matching and navigation logic can be kept separate from presentation.
Why it matters: This division lets routing fit into a component tree without making page components responsible for navigation. - Unchanged routing foundations: Explain that using web components changes where routing responsibilities live, not the underlying routing approach.
Why it matters: You can apply the routing pieces already introduced without inventing a new routing model for web components.
Key terms: app shell, outlet, router module, page components, real links, route matching, metadata updates, focus management, cancellation
11.6 Summary
Where this is used later
- Screens and app architecture (chapter 15) · The earlier model of rendering routes.
- The document metadata (chapter 15) · Route rendering can update page titles and metadata.
- Routing and navigation (chapter 15) · Rendering routes using web components
Concepts explained in this chapter
- Navigation APIA browser API for observing and controlling navigation, including intercepting navigations.
- history entry stateHistory entry state is serializable transient data associated with an individual browser session-history entry.
- navigationMovement among locations or views in a web application.
- routingComparing a navigation destination with route definitions to select a view or handler.
- popstate eventA browser event dispatched when the active session-history entry changes through history traversal.
- History APIThe History API is a browser API for manipulating session history entries and navigating between document URLs without necessarily loading new documents.
- application shellAn application shell is the persistent structure and shared interface of an application around content that changes or loads separately.
- route handlerA route handler is a function or component associated with a route that produces the content or response for that destination.
- history.pushState()history.pushState() adds a session-history entry with optional state and URL without loading a new document.
- history.replaceState()A History API method that replaces the current session-history entry and can change the displayed URL without loading a new document.
- navigate eventA Navigation API event dispatched when a navigation is initiated.
- progressive enhancementProgressive enhancement is an approach that starts with broadly compatible baseline functionality and adds capabilities when supported by the user's device and browser.
- metadataMetadata is information that defines settings and descriptive properties for a website or web application without changing the document contents displayed in the viewport.
- renderingRendering is the process of producing visible interface content from application data, state, or route information.
- Web ComponentsA reusable custom HTML element built using browser standards such as custom elements, shadow DOM, and HTML templates.
- canonical URLA canonical URL is the preferred URL designated as the authoritative address for a page or resource among equivalent URL variants.
- fallbackAn alternative implementation or behavior used when a preferred feature or supplied content is unavailable.
- event.intercept()event.intercept() is a navigation-event method that prevents a supported navigation from proceeding natively and assigns application handling to it.
- promiseA JavaScript promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
