Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readWeb Platform

Intercept SPA routes with the Navigation API

Use one navigate handler for link clicks and Back while preserving direct loads and normal navigation outside your routes.

Your order list updates after a link click, but Back changes the URL and leaves the detail screen on the page. A click handler with pushState only covers the click. With the Navigation API, you can send both the intercepted click and the history traversal through the same renderer.

Intercept routes your page can render

Keep regular links. Listen for navigate and call intercept when the browser allows it and your renderer knows the destination. Let the browser handle the rest.

Serve this HTML at both /orders and /orders/42. The script renders from the initial URL on a direct visit, then intercepts navigation between the two routes.

<nav>
  <a href="/orders">Orders</a>
  <a href="/orders/42">Order #42</a>
</nav>
<main><h1 id="view"></h1></main>
<script>
  const views = new Map([
    ['/orders', 'Orders'],
    ['/orders/42', 'Order #42'],
  ])
  const heading = document.querySelector('#view')
  function render(path) {
    const title = views.get(path)
    heading.textContent = title
    document.title = title
  }

  render(location.pathname)
  window.navigation?.addEventListener('navigate', (event) => {
    if (!event.canIntercept || event.hashChange ||
        event.downloadRequest !== null || event.formData ||
        event.navigationType === 'reload') return

    const { pathname, search } = new URL(event.destination.url)
    if (search || !views.has(pathname)) return

    event.intercept({ handler: () => render(pathname) })
  })
</script>

Clicking Order #42 changes the URL and heading without another document request, and Back takes both values back to Orders.

diagram

Two paths from the navigate event

The route check sends known order pages to the handler and leaves other destinations to the browser.

The HTML navigation model commits the destination before the handler runs. That means the handler can read the new URL, and it needs no extra history.pushState call. Use the destination from the event to decide whether to intercept in the first place. At that point the URL can still show the previous route.

Keep the browser's normal paths open

The handler skips fragment-only changes, downloads, reloads and POST submissions. It also lets the browser load URLs with query strings, which this renderer ignores. canIntercept rules out cross-origin links and other navigations the browser needs to handle.

If the browser has no window.navigation, the listener is absent and the regular links request full documents. Test the detail URL by opening it in a fresh tab and by reloading it. If either returns 404, make your server serve that route before shipping the intercepted version.

If you later fetch data in the handler, pass event.signal to the fetch so a new navigation can cancel the old request. Check that a slow response cannot paint the order after the user returns to the list.