chapter eleven

11 Building a Router

 

This chapter covers

  • Creating a client-side router.
  • Rendering matched routes through an outlet.
  • Updating metadata after route changes.
  • Applying View Transitions as progressive enhancement.

Chapter 10 introduced client-side routing from the platform side: real URLs, real links, server support, navigation interception, and route matching. This chapter continues from the point where a route has already been matched. We will render the route, update the browser cues around it, and then combine the pieces into a small router.

11.1 Rendering routes

After a route has been matched, the router has to do the visible part of the job: render the view that belongs to that route. This is the part most developers imagine first, but it should not be the first thing designed. Rendering is easier when the previous decisions are already clear:

  • What URL represents this view?
  • Which route pattern matched?
  • Which parameters and query values does the view need?
  • Which element in the document will receive the new content?
  • Which browser cues need to be updated after the render?

For a small router, the render contract can be simple: a route handler returns a title and a DOM node. The router then replaces the current view, updates the document metadata, marks active links, restores focus, and optionally handles scroll.

11.1.1 Outlet and master pages

11.1.2 Using DOM APIs

11.1.3 Title and metadata

11.1.4 Active navigation and focus

11.1.5 Scroll restoration

11.1.6 Using web components

11.1.7 Route guards

11.1.8 Not found and route errors

11.2 Navigating to new routes

11.3 View transitions for route change

11.3.1 View Transitions API

11.3.2 Cross-document view transitions

11.3.3 Motion and accessibility

11.4 Building a tiny Vanilla router

11.4.1 First pass: a function-based router

11.4.2 Second pass: a class-based router