How to Switch Pages in React with the Navigation API
ReactflushSync,Navigation API,Playwright,TypeScript
With the Navigation API's navigate event, you can intercept link navigations in JavaScript while keeping ordinary <a href="/items/3"> links. React can switch the view without reloading the whole page. The browser's Back and Forward buttons also fire the same event.
When writing this in React, I found two things to watch. One is wrapping the rendering of the new page in flushSync inside the handler. The other is passing e.signal to the data fetch. Without either, the display actually broke.
The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc and then built them with esbuild. The only browser I tested was Chromium 153 (headless) driven by Playwright 1.63.0. I did not test Firefox, Safari, real smartphones, forms that submit with POST, pages inside an iframe, or combinations with router libraries such as React Router.
Which browsers support it
According to MDN's compatibility data, Navigation is supported in Chrome and Edge from version 102, in Firefox from 147, and in Safari from 26.2.
Older browsers do not have window.navigation. In that case, the code does nothing and links behave as ordinary page navigations. For that reason, the server should return the same HTML for any path that is opened (I check this in a later section).
Catching link navigations with the navigate event
For testing, I built three kinds of pages: a list of articles (/), an article (such as /items/1), and an "About this site" page (/about). Page data is received as JSON from the server at /api/<path>.
// api.ts
export type PageData =
| { kind: 'list'; items: { id: number; title: string }[] }
| { kind: 'item'; id: number; title: string; body: string }
| { kind: 'about' }
| { kind: 'notfound' };
export type Page = { path: string; data: PageData };
export async function loadPage(path: string, signal?: AbortSignal): Promise<Page> {
const res = await fetch(`/api${path}`, { signal });
const data = (await res.json()) as PageData;
return { path, data };
}
This is the finished App. The links are still plain <a href>, with no dedicated Link component. PageView only renders the list, the article, and so on, depending on page.data.kind.
// App.tsx
import { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { loadPage, type Page } from './api';
import { PageView } from './PageView';
export function App() {
const [page, setPage] = useState<Page | null>(null);
const [pending, setPending] = useState(false);
useEffect(() => {
const controller = new AbortController();
// The navigate event does not fire on the first display, so load it here
loadPage(location.pathname, controller.signal).then(setPage, () => {});
// In browsers without the Navigation API, links are ordinary page navigations
if (!window.navigation) return () => controller.abort();
const onNavigate = (e: NavigateEvent) => {
// Leave cross-origin navigations, hash-only navigations, and downloads to the browser
if (!e.canIntercept || e.hashChange || e.downloadRequest !== null) return;
const url = new URL(e.destination.url);
e.intercept({
async handler() {
setPending(true);
const next = await loadPage(url.pathname, e.signal);
// Finish rendering the new page before the handler ends
flushSync(() => setPage(next));
},
});
};
const onDone = () => setPending(false);
navigation.addEventListener('navigate', onNavigate);
navigation.addEventListener('navigatesuccess', onDone);
navigation.addEventListener('navigateerror', onDone);
return () => {
controller.abort();
navigation.removeEventListener('navigate', onNavigate);
navigation.removeEventListener('navigatesuccess', onDone);
navigation.removeEventListener('navigateerror', onDone);
};
}, []);
return (
<>
<nav>
<a href="/">一覧</a> <a href="/about">このサイトについて</a>{' '}
<a href="https://example.com/">外部サイト</a>{' '}
<a href="/files/memo.txt" download>メモをダウンロード</a>{' '}
<a href="#bottom">ページの下へ</a>
</nav>
<p id="status" style={{ position: 'fixed', top: 0, right: 8 }}>{pending ? '読み込み中…' : ''}</p>
<main>{page ? <PageView page={page} /> : <p>読み込み中…</p>}</main>
<p id="bottom">ページの下</p>
</>
);
}
Calling e.intercept() inside the navigate event turns that navigation into one that does not reload the page, and the code in handler runs. In TypeScript 7.0.2, the NavigateEvent and navigation types are included in the DOM type definitions, so tsc passed without me writing any extra type declarations.
I followed the links from the list to article 3 and then to "About this site", and pressed Back and Forward. The view switched each time. During that time, the browser fetched HTML only once, for the initial /. navigation.entries() listed three entries, /, /items/3, and /about, and Back and Forward did not reload the page either.
Excluding navigations that should not be intercepted
You cannot intercept every navigation. The finished code excludes three kinds up front.
When e.canIntercept is false, the navigation cannot be intercepted. According to MDN's description of canIntercept, this includes navigations to a different origin. In my test, the link to https://example.com/ had canIntercept set to false, and the browser opened the external page as usual.
When e.hashChange is true, the navigation stays on the same page, as with the #bottom link. When I let the browser handle the link to the bottom of the page on the list page without intercepting it, it scrolled to the bottom without reloading any data.
To exclude download links, write the condition as e.downloadRequest !== null. According to MDN's description of downloadRequest, downloadRequest is the file name for a download navigation and null otherwise. For a link with a download attribute that has no value, downloadRequest was an empty string in my test. An empty string is falsy in an if condition, so writing if (e.downloadRequest) would fail to exclude that link as a download.
The URL changes before the handler runs

The handler runs after the URL has changed. MDN's description of intercept() also says that handler runs after currentEntry has been updated.
For testing, I made the server delay only the data for article 1 by 1.5 seconds. I clicked the link to article 1 on the list and looked 300 milliseconds later. The URL was already /items/1, but the list was still on screen. For that reason, the first thing the handler does is call setPending(true) to show a loading message ("Loading…"). After the data arrived and article 1 appeared, the loading message was gone.
The loading message is cleared not in the handler but in the navigatesuccess and navigateerror events. As stated in MDN's description of the Navigation API, navigatesuccess fires when the handler's Promise succeeds, and navigateerror fires when it fails. In my test, when I clicked another link while article 1 was still loading, a navigateerror fired for the navigation to article 1. In the finished code, the loading message is placed in the top-right corner of the screen with position: fixed, and the measurements in the next section were taken with that placement.
Using flushSync inside the handler to finish rendering
According to MDN's description of intercept(), when navigating with Back or Forward, the browser waits for the handler's Promise to complete before restoring the scroll position. The newly displayed page starts at the top.
In my test, I scrolled the list down 1,500 pixels, opened article 30, pressed Back, and checked the scroll position 1.2 seconds later. I changed only how setPage was called. In every version, the loading message was placed in the top-right corner with position: fixed, the same as in the finished code.
| How setPage is called inside the handler | Times the list's scroll position was restored (out of attempts) |
|---|---|
setPage(next) called directly |
12 of 20 (in the other 8, the list appeared at the top) |
setPage(next) called 300 ms after the handler finished |
0 of 5 |
flushSync(() => setPage(next)) (finished code) |
10 of 10 |
When setPage was called directly, the screen still showed article 30 every time navigatesuccess fired. React rendered that update only after the handler finished. The position was restored in 12 of 20 attempts, and in the other 8 the list appeared from the top. Delaying the render further restored nothing in 5 attempts.
Wrapping the call in flushSync makes React update the DOM immediately. By the time navigatesuccess fired, the screen already showed the list, and the scroll position returned to 1,500 in all 10 attempts. react.dev says flushSync should be used rarely, but it lists integrating with browser APIs as a case where it is appropriate. Here, I call it once per navigation.
Using e.signal to cancel the fetch when another link is clicked
I tested clicking the link to article 2 while the slow fetch for article 1 was still running. As stated in MDN's description of signal, e.signal is aborted when another navigation starts and the current one is canceled.
When I did not pass e.signal to fetch, article 2 appeared first, and then the late data for article 1 overwrote the screen. The URL was /items/2, but the heading still showed article 1 (the heading text is in Japanese).
In the finished code, which passes e.signal, the fetch for article 1 is aborted as soon as article 2 is clicked. The handler for article 1 ends with an AbortError and never reaches setPage. Even after waiting 2 seconds, the screen still showed article 2.
The canceled navigation to article 1 still remained in the history. navigation.entries() listed three entries: /, /items/1, and /items/2. Pressing Back from article 2 leads to the page for article 1.
The initial display and the HTML the server returns
As stated in MDN's description of the Navigation API, the navigate event does not fire when the page is first loaded. For that reason, the finished code loads the page for location.pathname itself at the start of useEffect.
I also considered opening /items/5 directly by typing it into the address bar. My test server returns the same HTML for any path, except paths beginning with /api/ and files such as JavaScript. Opening /items/5 directly displayed article 5.
To stand in for a browser without the Navigation API, I set window.navigation to undefined and tested again. When I clicked the link to article 3, the browser fetched the HTML for /items/3, and the whole page reloaded. The screen showed article 3, and the link worked without problems.
One more thing: after navigating with intercept(), focus moved to body. When I pressed the link to article 3 while it was focused, focus was on body after article 3 appeared. According to MDN's description of intercept(), with the default focusReset, focus moves to an element with the autofocus attribute if there is one, and otherwise to body.
Posted by 86
Related Posts

How to Show Online or Offline Status on a React Screen
I built a React display that shows "Offl ...

How to Use flushSync in React to Update the Screen Immediately After setState
Right after you update state in React, t ...

Creating a Frosted Glass Background with backdrop-filter in CSS
Combining a semi-transparent background ...

Preloading and Preinitializing Resources in React 19 with preload and preinit
In react-dom, preload only downloads a f ...

How to Pause Polling in React While the Tab Is in the Background
For a screen that asks the server every ...
