Frontend System Design: The History API
pushState, replaceState and popstate explained by building a tiny router from scratch
Click a link on a classic website and the whole page goes blank for a moment while a new one loads. Click a link in Gmail, YouTube or almost any React app and the URL changes, the content changes, but the page never reloads. The Back button still works too.
That trick is the History API. Every router you've used (React Router, Next.js, Vue Router, Angular Router) is built on top of it. Once you understand it, routing stops being magic, and a whole class of bugs ("Back closes my app", "refresh gives a 404", "scroll jumps to the top") becomes easy to fix.
In this post we'll learn it the best way: by building a tiny router from scratch.
How to read this post
| Marker | Who it's for | What you get |
|---|---|---|
| ๐ข Beginner | New to web development | The idea, in plain words |
| ๐ต Junior | Building your first real projects | Code you can copy |
| ๐ก Mid | Shipping production code | UX patterns and common bugs |
| ๐ด Senior | Designing systems, interviewing | Edge cases, the Navigation API |
Browser history is a stack of cards ๐
๐ข Beginner: every tab keeps its own list of pages you've visited, called the session history. Think of it as a row of cards with a marker on the one you're looking at:
You visit /home, then /products, then /products/42:
[ /home ] [ /products ] [ /products/42 ]
โฒ you are here
Press Back:
[ /home ] [ /products ] [ /products/42 ]
โฒ you are here (the "forward" card is still there)
Now click a link to /cart:
[ /home ] [ /products ] [ /cart ]
โฒ you are here (the old forward card is thrown away)
Normally, every new card means a full page load from the server. The History API lets your JavaScript add and change cards itself, without loading anything. Your code then swaps the content on screen to match.
The whole API in one table
| Method / event | What it does | Reloads the page? |
|---|---|---|
history.pushState(state, '', url) |
Adds a new card and moves to it | No |
history.replaceState(state, '', url) |
Replaces the current card | No |
history.back() |
Same as pressing Back | Not by itself* |
history.forward() |
Same as pressing Forward | Not by itself* |
history.go(n) |
Jump n cards (-2 = back twice) |
Not by itself* |
history.state |
The data attached to the current card | n/a |
history.length |
How many cards this tab has | n/a |
popstate event |
Fires when the user moves between cards (Back/Forward) | n/a |
* If the card you move to was created with pushState/replaceState, there's no reload: the browser fires popstate and your code must update the page. If it's a card from a real page load, the browser loads that page as usual.
The second argument ('') is an old, unused "title" parameter. Always pass an empty string.
pushState vs replaceState
๐ข Beginner:
Start: [ /products ]
โฒ
pushState('/products?page=2'):
[ /products ] [ /products?page=2 ]
โฒ Back goes to /products
replaceState('/products?page=2') instead:
[ /products?page=2 ]
โฒ Back leaves the page entirely
The rule: use pushState when the user would expect Back to undo the change. Use replaceState when they wouldn't.
| Change | Push or replace? | Why |
|---|---|---|
| Navigating to another page or screen | Push | Back should return to the previous page |
| Going to page 2 of results | Push | People expect Back to return to page 1 |
Typing in a search box that updates ?q= |
Replace | Back shouldn't undo one letter at a time |
| Adjusting a map's zoom or a slider | Replace | Dozens of tiny changes; Back should leave the map |
Fixing a URL format (adding a default ?tab=overview) |
Replace | It's a correction, not a new step |
| Opening a full-screen modal or photo viewer on mobile | Push | Users press Back to close it (more on this below) |
๐ก Mid: the worst History API bug is trapping the user: pushing a new entry on every keystroke or slider movement. Then someone presses Back twenty times and is still on your page. If they rage-quit by closing the tab, that's on you.
๐ต Junior: build a tiny router
Here's a complete single-page router in plain JavaScript. It does what React Router does at its core.
<nav>
<a href="/" data-link>Home</a>
<a href="/about" data-link>About</a>
<a href="/products/42" data-link>Product 42</a>
</nav>
<main id="app"></main>
const routes = {
'/': () => '<h1>Home</h1>',
'/about': () => '<h1>About us</h1>',
};
function render() {
const path = location.pathname;
const product = path.match(/^\/products\/(\d+)$/); // a route with a parameter
const html = product
? `<h1>Product #${product[1]}</h1>`
: routes[path]?.() ?? '<h1>404: Not found</h1>';
document.querySelector('#app').innerHTML = html;
}
// 1. Intercept clicks on our links
document.addEventListener('click', (e) => {
const link = e.target.closest('a[data-link]');
if (!link) return;
e.preventDefault(); // stop the normal full-page load
history.pushState({}, '', link.href); // add a history card, change the URL
render(); // show the new "page"
});
// 2. Handle Back and Forward
window.addEventListener('popstate', render);
// 3. Render whatever URL we started on
render();
Three steps, and you have a router:
Click a link โโโถ preventDefault โโโถ pushState (URL changes) โโโถ render()
Press Back โโโถ browser moves the marker โโโถ popstate fires โโโถ render()
First load โโโถ render() reads location.pathname
๐ต Junior: popstate does NOT fire on pushState. It only fires when the user (or history.back() / go()) moves between cards. That's why the click handler calls render() itself.
The "refresh gives a 404" bug ๐ก
Your router works perfectly until someone refreshes on /about. The browser asks the server for /about, and the server has no file called about, so it returns a 404.
The fix is on the server: for any path that isn't a real file, return index.html and let the router take over. Every host has a setting for this ("SPA fallback", "rewrite all routes to index.html"). Frameworks like Next.js handle it for you because they generate a page for each route.
Don't break normal link behavior ๐ก
Users expect Ctrl/Cmd+click and middle-click to open a link in a new tab. A naive router steals those clicks too. Only intercept plain left-clicks on links to your own site:
document.addEventListener('click', (e) => {
const link = e.target.closest('a[href]');
if (!link) return;
if (e.defaultPrevented || e.button !== 0) return; // not a left click
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; // new tab / window
if (link.target && link.target !== '_self') return; // target="_blank"
if (link.hasAttribute('download')) return;
if (link.origin !== location.origin) return; // external link
e.preventDefault();
history.pushState({}, '', link.href);
render();
});
This is exactly the kind of detail real router libraries handle for you, and a good reason to use one.
The state object ๐ฆ
The first argument to pushState/replaceState attaches data to the history card. You get it back in popstate (and from history.state at any time):
history.pushState({ productId: 42, from: 'search' }, '', '/products/42');
window.addEventListener('popstate', (event) => {
console.log(event.state); // { productId: 42, from: 'search' } when you return to that card
});
๐ก Mid: what to put in it. The state is copied (with the structured clone algorithm, like postMessage), so it can hold objects, arrays, dates and maps, but not functions or DOM elements. Browsers also cap its size, so keep it small: IDs and small UI details, never whole API responses.
๐ก Mid: state vs URL. Anything a user might share or bookmark belongs in the URL (/products?sort=price), because state isn't part of the link. History state is for things that should survive Back/Forward but not a shared link, such as "which tab was open" or "where the user had scrolled to".
Scroll restoration ๐
On a normal website, when you press Back the browser restores where you had scrolled. In a single-page app, the browser often can't, because the content is re-rendered by JavaScript and may not exist yet when the browser tries to scroll.
๐ด Senior: take control by saving the position in history state:
history.scrollRestoration = 'manual'; // "I'll handle it myself"
// Before leaving a card, remember the scroll position on it
function navigate(url) {
history.replaceState({ ...history.state, scrollY: window.scrollY }, '');
history.pushState({ scrollY: 0 }, '', url);
render();
window.scrollTo(0, 0); // new page: start at the top
}
// When coming back, restore it (after the content has rendered)
window.addEventListener('popstate', (event) => {
render();
requestAnimationFrame(() => window.scrollTo(0, event.state?.scrollY ?? 0));
});
Routers like React Router (<ScrollRestoration />) and Next.js do this for you, but it's a common interview follow-up: "Why does the list jump to the top when I press Back?"
๐ก Mid: Back closes the modal
On phones, people press Back (or swipe back) to close full-screen things: image viewers, menus, dialogs. If your modal ignores Back, the whole page goes back instead, and the user loses their place.
The pattern: push a history entry when the modal opens, and close the modal on popstate.
function openPhoto(id) {
history.pushState({ modal: 'photo', id }, '', `?photo=${id}`);
showPhotoModal(id);
}
function closePhoto() {
history.back(); // removes the modal's entry; popstate closes it
}
window.addEventListener('popstate', (event) => {
if (event.state?.modal === 'photo') showPhotoModal(event.state.id);
else hidePhotoModal();
});
A bonus of putting ?photo=42 in the URL: the link is shareable, and refreshing reopens the same photo. This is how many photo-sharing sites behave.
Hash routing: the old way #๏ธโฃ
Before the History API existed, single-page apps used the part of the URL after #:
https://example.com/#/products/42
Changing the hash never reloads the page and never hits the server, and it fires a hashchange event. It still works and needs no server setup, which is why you'll see it in old apps and some static hosting setups. The downsides: uglier URLs, and the server never sees the route (the fragment isn't sent), which is bad for server rendering and SEO. For new apps, use the History API.
๐ด Senior: security, limits and the future
You can't fake the domain. pushState only accepts URLs on the same origin. Trying history.pushState({}, '', 'https://bank.com/login') throws a SecurityError, so a page can't make the address bar lie about which site you're on.
history.length is not your app's history. It counts every entry in the tab, including other sites the user visited before yours, and you can't read their URLs (that would be a privacy leak). Don't use it to decide "is there somewhere to go back to?"
Programmatic back can leave your site. If someone opened your app from a link, history.back() may take them to Google. For an in-app "Back" button, track your own navigation, or link to a sensible parent page instead.
The Navigation API. The History API is old and a bit awkward: popstate doesn't fire for your own pushState calls, you have to intercept link clicks yourself, and you can't easily list the entries. The newer Navigation API (window.navigation) fixes this with a single navigate event for every navigation in your page:
navigation.addEventListener('navigate', (event) => {
if (!event.canIntercept) return; // e.g. cross-origin: let the browser handle it
const url = new URL(event.destination.url);
event.intercept({
async handler() {
await renderRoute(url.pathname); // link clicks, Back, Forward: all land here
},
});
});
Chromium browsers have supported it for years, and other engines have been adding it. Check current support on caniuse.com before relying on it without a fallback.
Common bugs and their fixes ๐
| Bug | Cause | Fix |
|---|---|---|
| Refresh on a route gives 404 | The server doesn't know your client-side routes | Serve index.html for unknown paths (SPA fallback) |
| Back goes back one letter at a time | pushState on every keystroke |
replaceState for live-updating inputs |
| Page doesn't update on Back | No popstate listener (or not re-rendering) |
Re-render from location on popstate |
| Ctrl+click opens in the same tab | Router intercepts every click | Skip modified clicks, target="_blank" and external links |
| List jumps to top after Back | Scroll isn't restored after re-render | Save scrollY in history state, restore on popstate |
| Back closes the app instead of the modal | Modal has no history entry | pushState on open, close on popstate |
| "Back" button leaves the site | history.back() with no in-app history |
Track in-app navigation or link to a parent page |
Interview cheat sheet ๐ค
- "How does client-side routing work?" Intercept link clicks,
preventDefault,pushStateto change the URL, render the new view; listen topopstatefor Back/Forward; render fromlocationon first load. The server must fall back toindex.html. - "pushState vs replaceState?" Push adds an entry (Back undoes it); replace overwrites the current one (Back skips it). Push for navigation, replace for live-updating state like search inputs.
- "Does pushState fire popstate?" No. Only moving between entries does.
- "Where do you keep UI state: URL or history state?" URL if it should be shareable or bookmarkable; history state if it should only survive Back/Forward.
- "Hash routing vs History API?" Hash needs no server config but gives worse URLs and invisible routes for the server; the History API gives clean URLs but needs an SPA fallback.
Wrapping up
The History API is small: two methods to change history (pushState, replaceState), a few to move through it (back, forward, go), and one event to react to (popstate). Everything else, from routers to modals that close on Back, is built from those pieces.
Next time you use <Link> in React Router or Next.js, you'll know what's happening underneath: a preventDefault, a pushState, and a re-render.
Keep learning
- MDN: History API: developer.mozilla.org/en-US/docs/Web/API/History_API
- MDN: Working with the History API: developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API
- MDN: Navigation API: developer.mozilla.org/en-US/docs/Web/API/Navigation_API
- HTML spec, session history: html.spec.whatwg.org/multipage/nav-history-apis.html
- My earlier posts: How a Browser Loads a Website (the back/forward cache), and my Web Storages post (using the URL as storage)
If this helped, share it with someone whose app closes when they press Back. ๐
About the author
Push karo khush raho ;)
Comments
Join the discussionNo comments yet. Be the first to comment.