Frontend development · Intermediate · 25 min
Build a small client-side router with the History API
By Padding · Updated 18 Nov 2026
Modern browsers · Node.js 26.13.1 LTS · Playwright 1.65.1 (Chromium)
You will build a three-page bookshop app with no library, where links change the URL without a reload, back and forward work, a book page reads its ID from the path, unknown paths show a not-found view, and every page change updates the title, moves focus and is announced.
On this page
A single-page app loads one HTML document and then swaps what is inside it as the reader moves around. A router is the part that keeps that honest: the address bar shows a real URL for every view, back and forward behave as people expect, and a link pasted into a chat opens the right page. Libraries such as React Router, Vue Router and the routers in SvelteKit and Next.js do this for you, which makes it easy to treat routing as magic.
It is not. The browser gives you three things to build on: history.pushState() to change the URL without loading a page, the popstate event for back and forward, and URLPattern to match paths such as /books/:id. In this tutorial you build Kanda Books, a fictional second-hand bookshop with three pages (home, the book list and a page per book) and a not-found view, using only those pieces and about 80 lines of JavaScript. You also do the accessibility work that hand-rolled routers often skip, and you finish with a browser test that proves it all.
A router like this is also small. The whole app here is a few kilobytes, which matters to a reader on a low-end Android phone paying for prepaid data: after the first load, moving between pages costs no extra HTML downloads at all.
Step 1 · Write the app shell and a server that answers every path
Make a demo folder with a public folder inside it for everything the browser loads:
mkdir -p ~/router-demo/public
cd ~/router-demoThe shell is the one HTML page the browser ever loads. It holds what every page shares (the navigation) and an empty <main> that the router fills in:
cat > public/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kanda Books</title>
<link rel="stylesheet" href="/style.css">
<script type="module" src="/app.js"></script>
</head>
<body>
<nav aria-label="Main">
<a href="/">Home</a>
<a href="/books">Books</a>
</nav>
<main id="view"></main>
<p id="route-announcer" class="visually-hidden" aria-live="polite" aria-atomic="true"></p>
</body>
</html>
HTML
cat > public/style.css <<'CSS'
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; color: #1b1f24; background: #f6f7f8; }
nav { display: flex; gap: 1rem; padding: 1rem; background: #ffffff; border-bottom: 1px solid #d5d9df; }
nav a { color: inherit; }
nav a[aria-current="page"] { font-weight: 700; text-decoration-thickness: 3px; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.visually-hidden {
position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
}
CSSTwo details matter later. The stylesheet and script use absolute paths (/style.css, /app.js). On the page /books/2, a relative app.js would ask for /books/app.js, which does not exist. And the empty paragraph with aria-live="polite" is where you will announce page changes in a later step.
Now the server. A plain static server looks up the file named by the path, so /books/2 would be a 404 because no such file exists. A single-page app needs a different rule: a path with no file extension is a page, so send the shell and let the router decide. A path with an extension (/app.js, /style.css) is a real file, and a missing one is a real 404. Without this rule, clicking around works but reloading or opening a shared link to /books/2 fails.
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize, sep } from 'node:path';
const root = join(import.meta.dirname, 'public');
const port = Number(process.env.PORT ?? 8080);
const types = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
};
createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
const headers = { 'cache-control': 'no-store' };
// No extension: a route such as /books/2. Always answer with the app shell.
if (!extname(pathname)) {
const shell = await readFile(join(root, 'index.html'));
res.writeHead(200, { ...headers, 'content-type': types['.html'] }).end(shell);
return;
}
// An extension: a real file inside public/, or a real 404.
const file = normalize(join(root, pathname));
try {
if (!file.startsWith(root + sep)) throw new Error('outside public/');
const body = await readFile(file);
const type = types[extname(file)] ?? 'application/octet-stream';
res.writeHead(200, { ...headers, 'content-type': type }).end(body);
} catch {
res.writeHead(404, { ...headers, 'content-type': 'text/plain' }).end('Not found');
}
}).listen(port, () => console.log(`Kanda Books on http://localhost:${port}`));
JScache-control: no-store stops the browser keeping old copies while you edit, so a reload always shows your latest files. The startsWith check refuses any path that would resolve outside public/.
Open a second terminal, go to the folder and start the server. Leave it running for the rest of the tutorial; it reads files on every request, so you never need to restart it after an edit:
cd ~/router-demo
node server.mjsEvery development server for single-page apps has this rule somewhere. Vite turns it on by default (its appType option is 'spa'), and on Nginx it is one line in the location block: try_files $uri $uri/ /index.html;.
Check it worked
The server terminal prints Kanda Books on http://localhost:8080. Back in your first terminal, ask for a deep link and a missing file:
curl -s -o /dev/null -w '%{http_code} %{content_type}\n' http://localhost:8080/books/2
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/missing.jsThe first line is 200 text/html; charset=utf-8: the shell, even though there is no books/2 file. The second is 404. Open http://localhost:8080/books/2 in your browser: you see the Home and Books links and nothing else yet. The browser console shows a 404 for app.js, which you write next.
Step 2 · Describe the pages and match paths to them
Put the pages and the route table in their own module, routes.js. Each view is a function that returns a title and some HTML. The book page takes the id from the path, and returns null when no book has that ID, so the not-found view can take over.
cat > public/routes.js <<'JS'
const books = [
{ id: '1', title: 'Things Fall Apart', author: 'Chinua Achebe' },
{ id: '2', title: 'The River Between', author: "Ngũgĩ wa Thiong'o" },
{ id: '3', title: 'So Long a Letter', author: 'Mariama Bâ' },
];
// Escape anything that comes from data or the URL before it goes into HTML.
const esc = (value) => String(value).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
const home = () => ({
title: 'Home',
html: `<h1 tabindex="-1">Kanda Books</h1>
<p>Second-hand African fiction, posted from Kisumu. <a href="/books">Browse the books</a>.</p>`,
});
const bookList = () => ({
title: 'Books',
html: `<h1 tabindex="-1">Books</h1>
<ul>${books
.map((b) => `<li><a href="/books/${esc(b.id)}">${esc(b.title)}</a> by ${esc(b.author)}</li>`)
.join('')}</ul>`,
});
const bookPage = ({ id }) => {
const book = books.find((b) => b.id === id);
if (!book) return null;
return {
title: book.title,
html: `<h1 tabindex="-1">${esc(book.title)}</h1>
<p>by ${esc(book.author)}</p>
<p><a href="/books">All books</a></p>`,
};
};
const notFound = (path) => ({
title: 'Page not found',
html: `<h1 tabindex="-1">Page not found</h1>
<p>There is no page at <code>${esc(path)}</code>. <a href="/">Go to the home page</a>.</p>`,
});
const routes = [
{ pattern: '/', view: home },
{ pattern: '/books', view: bookList },
{ pattern: '/books/:id', view: bookPage },
];
// Turn a pattern into a function: path in, params object (or null) out.
function compile(pattern) {
if ('URLPattern' in globalThis) {
const urlPattern = new URLPattern({ pathname: pattern });
return (path) => urlPattern.exec({ pathname: path })?.pathname.groups ?? null;
}
// Fallback for older browsers: /books/:id becomes ^/books/(?<id>[^/]+)$
const regex = new RegExp('^' + pattern.replace(/:(\w+)/g, '(?<$1>[^/]+)') + '$');
return (path) => {
const match = regex.exec(path);
return match ? { ...match.groups } : null;
};
}
const compiled = routes.map((route) => ({ ...route, match: compile(route.pattern) }));
export function matchRoute(path) {
for (const route of compiled) {
const params = route.match(path);
if (params) return route.view(params) ?? notFound(path);
}
return notFound(path);
}
JSURLPattern is the browser's own path matcher. new URLPattern({ pathname: '/books/:id' }) matches /books/2 and gives back { id: '2' } in pathname.groups. It became Baseline in September 2025, so it is in current Chrome, Edge, Firefox and Safari, but phones that no longer get browser updates, which are common in many markets, may not have it. The fallback builds an equivalent regular expression with a named group for each :name. It only handles the simple patterns used here (plain segments and :params), which is all most apps need. Both return {} for a match with no parameters, which is truthy, and null for no match.
Routes are tried in order and the first match wins, which is how most router libraries behave too. The tabindex="-1" on every heading lets script focus it without adding it to the Tab order. You use that in the accessibility step.
Now the smallest possible router: read the current path, find the page, put it in <main>.
cat > public/app.js <<'JS'
import { matchRoute } from './routes.js';
const view = document.querySelector('#view');
function render() {
const page = matchRoute(location.pathname);
view.innerHTML = page.html;
}
render();
JSBook titles and the path are escaped with esc() before they go into innerHTML, so a title or URL containing < shows as text instead of becoming markup.
Check it worked
Reload http://localhost:8080/books/2. The heading reads The River Between with the author below it. Try http://localhost:8080/books (a list of three linked titles), http://localhost:8080/books/99 and http://localhost:8080/shelves: both show Page not found with the path in code type. The author names keep their accents (Ngũgĩ, Bâ), because the shell declares UTF-8 and the server sends it.
Step 3 · Intercept link clicks and push the new URL
Click Books in the navigation now and watch the reload button: the browser makes a full page load, fetches the shell again and runs the script again. Routing is about stopping that. Listen for clicks on the whole document, and when one lands on a link to a page in this app, cancel the browser's navigation, change the URL yourself with history.pushState(), and render.
The guards matter as much as the main path. People Ctrl-click or Cmd-click and middle-click links to open a new tab, use links with target or download, and follow links to other sites. All of those must keep their normal behaviour.
cat >> public/app.js <<'JS'
function navigate(to) {
if (to === location.pathname + location.search) return;
history.pushState(null, '', to);
render();
window.scrollTo(0, 0);
}
document.addEventListener('click', (event) => {
// Leave modified clicks (new tab or window) and non-left clicks to the browser.
if (event.defaultPrevented || event.button !== 0) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const link = event.target.closest('a[href]');
if (!link || link.target || link.hasAttribute('download')) return;
const url = new URL(link.href);
if (url.origin !== location.origin) return; // another site: a normal navigation
event.preventDefault();
navigate(url.pathname + url.search);
});
JShistory.pushState(state, '', url) adds an entry to the tab's history and changes the address bar, and nothing else: no request, no load, no event. The middle argument is unused by browsers and is passed as an empty string. One listener on document covers every link, including ones that render() adds later, because clicks bubble up. Pressing Enter on a focused link also fires a click, so keyboard users get the same behaviour.
navigate returns early when the URL would not change, so clicking Books twice does not add two identical history entries, and it scrolls to the top because a new page should start at the top.
Check it worked
Reload http://localhost:8080/, click Books, then click Things Fall Apart. The address bar changes to /books, then /books/1, and the content changes, without the brief flash or the reload button turning into a stop button. In the browser's developer tools, the Network panel shows no new request for the document when you click. Cmd-click (macOS) or Ctrl-click (Windows, Linux) a book title: it opens in a new tab and shows the right book there, thanks to the server rule.
Step 4 · Handle back and forward with popstate
Press the browser's back button now. The address bar goes back to /books, but the page still shows Things Fall Apart. pushState recorded the URL, but nothing tells your code when the reader moves through history. That is the popstate event: the browser fires it on window when the reader goes back or forward between entries in the same document. It does not fire for your own pushState calls, which is why navigate renders by itself.
cat >> public/app.js <<'JS'
window.addEventListener('popstate', () => render());
JSThe handler does not need to know which way the reader went. The URL is the single source of truth: whatever location.pathname says, render() shows. This is the most important idea in any router, and it is why a reload, a deep link and the back button all end up in the same place.
There is a newer API for all of this. The Navigation API gives you one navigate event on the navigation object that fires for link clicks, form submissions and back and forward alike, and event.intercept() turns a navigation into a same-document one. It replaces the click listener and the popstate listener with one handler. It reached Baseline in January 2026, so it works in current versions of the major browsers, but older phones and browsers that no longer update do not have it. The History API version you are building works everywhere, and once you understand it, the Navigation API is a small step.
Check it worked
From the home page, click Books, then The River Between. Press back: the list returns. Press back again: the home page returns. Press forward twice: you are on The River Between again. Notice that the tab title says Kanda Books on every page. The next step fixes that and some less visible problems.
Step 5 · Make page changes accessible
A full page load does several things for free that a router has to do by hand:
- The title changes. People with many tabs, and screen reader users, rely on the document title to know where they are. WCAG 2.2 success criterion 2.4.2 asks for titles that describe each page.
- Focus resets. After a load, a keyboard user starts at the top of the new page and a screen reader starts reading it. After
innerHTMLreplaces<main>, focus is left on a link that may no longer exist, and the screen reader says nothing. - The change is noticeable. Sighted people see the content change. Others need to be told.
- The current link is marked. Your navigation should say which page is current, with
aria-current="page", so it is announced and can be styled.
Replace app.js with this version. The click handler and navigate are the same as before. render gains an option saying whether to move focus, because on the first load the browser has already put the reader at the top of a new page and moving focus there would be surprising.
cat > public/app.js <<'JS'
import { matchRoute } from './routes.js';
const view = document.querySelector('#view');
const announcer = document.querySelector('#route-announcer');
function render({ moveFocus }) {
const page = matchRoute(location.pathname);
view.innerHTML = page.html;
// 1. A title that names the page.
document.title = `${page.title} · Kanda Books`;
// 2. Mark the current link in the navigation.
for (const link of document.querySelectorAll('nav a')) {
if (link.pathname === location.pathname) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
if (moveFocus) {
// 3. Put focus at the start of the new content.
view.querySelector('h1').focus();
// 4. Announce the new page. Clearing first means a repeat is still announced.
announcer.textContent = '';
setTimeout(() => { announcer.textContent = page.title; }, 100);
}
}
function navigate(to) {
if (to === location.pathname + location.search) return;
history.pushState(null, '', to);
render({ moveFocus: true });
window.scrollTo(0, 0);
}
document.addEventListener('click', (event) => {
if (event.defaultPrevented || event.button !== 0) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const link = event.target.closest('a[href]');
if (!link || link.target || link.hasAttribute('download')) return;
const url = new URL(link.href);
if (url.origin !== location.origin) return;
event.preventDefault();
navigate(url.pathname + url.search);
});
window.addEventListener('popstate', () => render({ moveFocus: true }));
render({ moveFocus: false });
JSFocusing the <h1> is what tabindex="-1" was for: headings are not focusable by default, and -1 allows focus() from script while keeping the heading out of the Tab order. The next Tab press moves to the first link after the heading, as it would on a freshly loaded page.
The live region is a hidden paragraph marked aria-live="polite". When its text changes, screen readers read the new text once they finish what they are saying, without moving focus. This uses the same live-region technique that WCAG 2.2 success criterion 4.1.3 (Status Messages) describes, though whether a route change counts as a status message is debatable. Some screen readers will also read the focused heading, so a reader may hear the page name twice; that is a better failure than hearing nothing. Try it with the screen reader you have (VoiceOver on macOS and iOS, TalkBack on Android, NVDA on Windows) and keep the heading focus even if you drop the announcement. If your app is translated, translate the titles too: they are what gets announced.
Check it worked
Reload http://localhost:8080/ and look at the tab: it reads Home · Kanda Books. Click Books: the tab reads Books · Kanda Books, and the Books link in the navigation is bold with a thick underline. Press Tab once: focus goes to the first book link, not back to the top of the page, because focus was on the Books heading. Click a book, then press back: the title changes back to Books · Kanda Books. With a screen reader running, each click reads out the new page name.
Step 6 · Test the router in a real browser
Clicking through by hand proves it once. A test proves it again after every change. Install Playwright into the demo folder (not into public/, so the server never serves it). --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:
cd ~/router-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThe test runs the same journey twice: once with the browser's URLPattern, and once with URLPattern deleted before the page loads, so the fallback matcher is tested as well. It also leaves a marker on window after the first load. If any click caused a full page load, the marker would be gone.
cd ~/router-demo
cat > test-router.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const base = 'http://localhost:8080';
const browser = await chromium.launch();
async function journey(withURLPattern) {
const page = await browser.newPage();
if (!withURLPattern) await page.addInitScript(() => { delete globalThis.URLPattern; });
const h1 = page.getByRole('heading', { level: 1 });
const nav = page.getByRole('navigation', { name: 'Main' });
const focusedOnHeading = () => h1.evaluate((el) => el === document.activeElement);
const announced = (text) =>
page.waitForFunction((t) => document.querySelector('#route-announcer').textContent === t, text);
await page.goto(base + '/');
assert.equal(await page.evaluate(() => 'URLPattern' in globalThis), withURLPattern);
assert.equal(await h1.textContent(), 'Kanda Books');
assert.equal(await page.title(), 'Home · Kanda Books');
assert.equal(await focusedOnHeading(), false, 'first load leaves focus alone');
await page.evaluate(() => { window.sameDocument = true; });
// Click through: the URL changes, the document does not reload.
await nav.getByRole('link', { name: 'Books', exact: true }).click();
await page.waitForURL(base + '/books');
assert.equal(await h1.textContent(), 'Books');
assert.equal(await nav.getByRole('link', { name: 'Books', exact: true }).getAttribute('aria-current'), 'page');
assert.equal(await nav.getByRole('link', { name: 'Home', exact: true }).getAttribute('aria-current'), null);
await page.getByRole('link', { name: 'The River Between', exact: true }).click();
await page.waitForURL(base + '/books/2');
assert.equal(await h1.textContent(), 'The River Between');
assert.equal(await page.title(), 'The River Between · Kanda Books');
assert.ok(await focusedOnHeading(), 'focus moves to the new heading');
await announced('The River Between');
// Back and forward.
await page.goBack();
await page.waitForURL(base + '/books');
await page.getByRole('heading', { level: 1, name: 'Books', exact: true }).waitFor({ timeout: 5000 });
assert.equal(await page.title(), 'Books · Kanda Books');
await announced('Books');
await page.goForward();
await page.waitForURL(base + '/books/2');
await page.getByRole('heading', { level: 1, name: 'The River Between', exact: true }).waitFor();
// The keyboard: Enter on a focused link routes too.
await nav.getByRole('link', { name: 'Home', exact: true }).focus();
await page.keyboard.press('Enter');
await page.waitForURL(base + '/');
assert.equal(await h1.textContent(), 'Kanda Books');
assert.equal(await page.evaluate(() => window.sameDocument), true, 'no full page load');
// Deep links and not-found, straight from the server.
await page.goto(base + '/books/3');
assert.equal(await h1.textContent(), 'So Long a Letter');
assert.equal(await page.title(), 'So Long a Letter · Kanda Books');
for (const path of ['/books/99', '/shelves']) {
await page.goto(base + path);
assert.equal(await h1.textContent(), 'Page not found');
assert.equal(await page.title(), 'Page not found · Kanda Books');
assert.equal(await page.locator('main code').textContent(), path);
}
await page.close();
console.log(`PASS: router ${withURLPattern ? 'with URLPattern' : 'with the regex fallback'}`);
}
await journey(true);
await journey(false);
await browser.close();
JS
node test-router.mjsThe test finds elements by role and accessible name, the same way a screen reader user finds them, so breaking a heading or the navigation label breaks the test. The not-found check also confirms that the path is shown as text.
Check it worked
The last two lines of output are PASS: router with URLPattern and PASS: router with the regex fallback. To see it catch a real bug, delete the line window.addEventListener('popstate', () => render({ moveFocus: true })); from public/app.js and run node test-router.mjs again: after going back, the URL changes to /books but the heading still says The River Between, so after about five seconds it stops with a TimeoutError from locator.waitFor while waiting for the Books heading. Put the line back and the test passes.
Step 7 · Compare it with a router library, then clean up
You have now built the core of what React Router, Vue Router and the framework routers do:
- A route table of patterns and views, matched in order, with parameters such as
:id. Libraries add nested routes, layouts and optional or wildcard segments. - Link handling that cancels the browser's navigation and calls
pushState. Their<Link>components do the same check for modified clicks and other origins. - History listening with
popstate, and the URL as the single source of truth. - A server fallback, which every single-page app host needs.
What they add on top is mostly work you would grow into: loading data before a page renders, lazy-loading each page's code, handling form submissions, restoring scroll positions per entry, and in some, focus and announcement handling like yours. When you reach for one, you know what it is doing and what to check it still does, such as titles and focus.
Stop the server with Ctrl+C in its terminal, then remove the demo folder. That also removes the local Playwright install; the browser Playwright downloaded stays in its shared cache, and npx playwright uninstall removes it if you no longer need it.
cd ~
rm -rf ~/router-demoCheck it worked
http://localhost:8080/ no longer loads in the browser, and ls ~/router-demo reports that there is no such file or directory.
Next steps
- Keep data such as a basket or the signed-in reader across page changes in manage app state in plain JavaScript with a store.
- See the same ideas with a library in add pages and navigation with React Router.
- Grow the router test into a full suite in write end-to-end browser tests with Playwright.
Related tutorials
- Manage app state in plain JavaScript with a store and eventsYou will build a shopping list app with no framework, where one state object, a small store built on EventTarget and a render function keep the screen and the data in step, with derived counts and a list that survives a reload.
- Add pages and navigation to a React app with React Router 8You will turn a Vite React app into a three-page recipe box with React Router 8.5 in data mode, with a shared layout, URL parameters, loaders, an action, pending UI, error boundaries and a search kept in the URL, then prove the back button and deep links with a Playwright script.
- Handle clicks and key presses with event listeners and delegationYou will build a small to-do list where adding, ticking and deleting tasks work by mouse and keyboard, using one delegated listener on the list, a form submit handler that stops the page reloading, and an AbortController that removes every listener in one call.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials