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.