If you’ve ever built your own client-side navigation that properly respects updating URLs, you’ve probably used history.pushState() a bunch, and it’s a bunch of work getting it robust and right. I think Jay Rungta does a good job of showcasing the newly-baseline Navigation API and why it’s better.
Sorry for the huge blockquote, but it’s worth it:
Building a router with the History API felt like assembling a puzzle, since you had to:
- Listen for clicks on
<a>tags globally.- Call
preventDefault()on them.- Manually call
history.pushState().- Manually update your DOM.
- Separately listen for the
popstateevent to handle the back/forward buttons.If you forgot to handle one edge case, users might accidentally end up at the wrong view, highlighting its fragility.
The Navigation API radically simplifies this. It gives you a single, centralized NavigateEvent for every navigation—whether it’s a user clicking a link, submitting a form, hitting the back button, or your code calling
navigation.navigate().The
event.intercept()function does a lot of the heavy lifting for you:
- Automatic URL updates: Handles updating the address bar and the history stack, without the need to call
pushState.- Automatic accessibility: Handles accessibility primitives like focus management (restoring focus after navigation) automatically.
- Centralized logic: Handles the back button and click events in the exact same function.
