A client-side router must render the right route when someone presses Back or Forward. In a History API router, listen for `popstate` on `window` and render from the current location when it fires. The event handles history traversal; it is not a general notification that the URL changed. section 10.3.6 section 11.2
Keep the other navigation paths explicit:
- Render once on startup; a `popstate` listener alone does not perform the initial render. section 11.4.1
- After `pushState()` or `replaceState()`, render manually. Neither call fires `popstate`. section 10.3.6 section 11.2
- Handle eligible internal link clicks separately. Start with real links, and leave modified clicks, external destinations, downloads, and hash jumps to the browser. section 10.3.6
const outlet = document.querySelector("#app");
const routes = [
{ path: "/", handler: () => homePage() },
{ path: "/products", handler: () => productsPage() },
{ path: "/products/:id", handler: ({ id }) => productPage(id) }
];
const matchers = routes.map((route) => ({
...route,
match: compileRoute(route.path)
}));
function getRoute(pathname = location.pathname) {
for (const route of matchers) {
const params = route.match(pathname);
if (params) return { route, params };
}
return null;
}
async function render() {
const result = getRoute();
if (!result) {
outlet.replaceChildren(notFoundPage());
document.title = "Not found";
return;
}
const { title, view } = await result.route.handler(result.params);
outlet.replaceChildren(view);
document.title = title;
}
window.addEventListener("popstate", render);
render();
A small function-based router connects `popstate` to its render function, then calls that function once for the initial route. The example does not yet intercept links or manage focus and scroll. section 11.4.1
This split is the central History API fallback rule: traversal renders through `popstate`, while a router-initiated URL change must trigger its own render. The Navigation API can provide a unified navigation flow instead, but a History API fallback must coordinate these paths itself. section 10.3.6 section 11.2
