Full answer
In a normal site, each link triggers a request for a new HTML page. In a single-page application (SPA), JavaScript handles navigation. The History API makes that possible:
history.pushState(state, '', url)adds an entry and changes the URL without loading anything.history.replaceState(state, '', url)changes the current entry (for redirects and cleaning query strings).- The
popstateevent fires onwindowwhen the user moves through history with back or forward. It does not fire forpushStatecalls, so the router renders after its own calls. history.back(),forward(), andgo(n)move through the entries.history.stateholds the state object of the current entry.
A minimal router does four things:
- Route table: patterns such as
/users/:idconverted to regular expressions, with named parameters. - Navigation:
navigate(path)callspushStateand then renders. Arender()function readslocation.pathname, finds the match, and calls its handler with the parameters. - Link interception: listen for clicks on the document. For an
aelement on the same origin, with no modifier keys, notarget, and a left click, callpreventDefaultandnavigate. Let the browser handle everything else, such as ctrl-click to open a new tab. - Back and forward: on
popstate, callrender()again.
Server side: a visit to /users/7 sends a request to the server, which must return the app shell (the same HTML file) for unknown paths, or the page shows a 404. Also handle scroll restoration, focus management and the page title for accessibility, a not found route, and the base path if the app is not served from the root.
The older alternative is hash routing (#/users/7), which needs no server configuration. The newer Navigation API (navigation.navigate, navigate event) is a more complete replacement for the History API in current browsers, and the View Transitions API can animate page changes.
class Router {
constructor(routes, outlet) {
this.outlet = outlet;
this.routes = routes.map(([pattern, handler]) => {
const names = [];
const regex = new RegExp('^' + pattern.replace(/:(\w+)/g, (_, name) => (names.push(name), '([^/]+)')) + '/?$');
return { regex, names, handler };
});
window.addEventListener('popstate', () => this.render());
document.addEventListener('click', (event) => {
const link = event.target.closest('a[href]');
const plain = event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
if (link && plain && !link.target && link.origin === location.origin) {
event.preventDefault();
this.navigate(link.pathname + link.search);
}
});
}
navigate(path, { replace = false } = {}) {
history[replace ? 'replaceState' : 'pushState']({ path }, '', path);
this.render();
}
render() {
for (const { regex, names, handler } of this.routes) {
const match = regex.exec(location.pathname);
if (match) {
const params = Object.fromEntries(names.map((name, i) => [name, decodeURIComponent(match[i + 1])]));
this.outlet.textContent = handler(params, new URLSearchParams(location.search));
return;
}
}
this.outlet.textContent = 'Not found: ' + location.pathname;
}
}
document.body.innerHTML = `
<nav>
<a id="home" href="/">Home</a>
<a id="user" href="/users/7?tab=posts">User 7</a>
<a id="external" href="https://other.example.org/page">External</a>
</nav>
<main id="outlet"></main>`;
const router = new Router(
[
['/', () => 'Home page'],
['/users/:id', (params, query) => `User ${params.id}, tab ${query.get('tab') ?? 'none'}`],
],
document.getElementById('outlet'),
);
const show = (label) => console.log(label.padEnd(18), location.pathname + location.search, '|', document.getElementById('outlet').textContent, '| entries:', history.length);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
router.render();
show('first render');
document.getElementById('user').click();
show('click user link');
router.navigate('/users/42');
show('navigate in code');
router.navigate('/missing');
show('unknown route');
router.navigate('/', { replace: true });
show('replace with home');
history.back();
await wait(50);
show('after back');
history.forward();
await wait(50);
show('after forward');
const external = document.getElementById('external');
console.log('same origin as the page (router would intercept):', document.getElementById('user').origin === location.origin, external.origin === location.origin);
}
main();Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: first render / | Home page | entries: 1 click user link /users/7?tab=posts | User 7, tab posts | entries: 2 navigate in code /users/42 | User 42, tab none | entries: 3 unknown route /missing | Not found: /missing | entries: 4 replace with home / | Home page | entries: 4 after back /users/42 | User 42, tab none | entries: 4 after forward / | Home page | entries: 4 same origin as the page (router would intercept): true false
Key points
- pushState and replaceState change the URL without loading; popstate fires on back and forward only.
- A router has a route table with params, a render function, link interception, and popstate handling.
- Intercept only plain same-origin left clicks; let other clicks use the browser default.
- The server must return the app shell for deep URLs.
- Handle scroll, focus, title, and not found; hash routing and the Navigation API are alternatives.
Common mistakes
- Expecting popstate to fire after pushState.
- Intercepting every click, including ctrl-click, external links, and downloads.
- Forgetting the server fallback, so refreshing a deep URL gives a 404.
- Not updating the page title and focus after a route change, which hurts accessibility.
Follow-ups
- What are the trade-offs between hash routing and History API routing?
- How would you restore scroll position on back navigation?
- What does the Navigation API improve over the History API?
Tips
- Say that pushState does not fire events, so the router must render itself.
- List which clicks to intercept and which to leave alone.
- Mention the server fallback and accessibility.