Building a Client-Side Router with History API
You'll learn how to create a simple routing system that updates the page content based on URL changes without full page reloads.
Now that you understand the individual History API methods, it's time to put them together into a working client-side router—a system that intercepts link clicks, updates the URL, and renders different content for different routes.
The Core Idea
Think of a router as a dispatcher at a hotel. When guests arrive at different floors (URLs), the dispatcher (router) knows which room (view) to send them to. Instead of rebuilding the entire hotel for each guest, you just change which room they see.
A basic router needs three parts:
- Route definitions: A map of URLs to functions that render content
- Link interception: Catch clicks on internal links to prevent full page loads
- State synchronization: Listen for back/forward button presses and render accordingly
How It Works
When a user clicks a link, your router:
- Prevents the default navigation
- Uses
history.pushState()to update the URL - Looks up which view matches the new URL
- Renders that view into the page
When the user presses back/forward:
- The
popstateevent fires - Your router reads the current URL
- Renders the matching view
This creates a seamless single-page experience where URLs still work correctly for bookmarking and sharing, but navigation feels instant because you're only swapping content, not reloading the entire page.
Key Takeaway: A client-side router combines link interception, pushState() for programmatic navigation, and popstate listeners to create a navigation system that updates both the URL and page content without full reloads.