Navigation API Baseline

Chris Coyier Chris Coyier on

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:

  1. Listen for clicks on <a> tags globally.
  2. Call preventDefault() on them.
  3. Manually call history.pushState().
  4. Manually update your DOM.
  5. Separately listen for the popstate event 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.

It's time to take your JavaScript to the next level

Leave a Reply

Your email address will not be published. Required fields are marked *

$966,000

Frontend Masters donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.