🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

The History API: pushState Routing and popstate

Web FoundationsBrowser APIsđŸŸĸ Free Lesson

The History API: pushState Routing and popstate

A single-page application renders every view from one HTML document, which creates a problem the multi-page web never had: the URL stops changing, so bookmarks break, the back button does nothing useful, and there is nothing to share in a chat message. The History API exists to reconcile SPA rendering with the URL contract the browser already gives users for free. pushState adds an entry, replaceState rewrites the current one without adding an entry, and the popstate event tells you when the user walks through the entries you created.

The API is small and the discipline around it is not. This lesson covers the mechanics, a working router, the server-side rewrite that deep links require, and the scroll and state details that separate a URL-accurate app from one that merely changes the address bar.

The Three Pieces

javascript
history.pushState({ view: 'settings', tab: 'profile' }, '', '/settings?tab=profile');
history.replaceState({ view: 'settings', tab: 'security' }, '', '/settings?tab=security');

window.addEventListener('popstate', (event) => {
  if (event.state) {
    render(event.state);
  } else {
    renderFromLocation();
  }
});

The first argument is a state object the browser stores with the entry and hands back on popstate — structured-cloned on storage, so keep it small and serializable. The second is a legacy title argument, effectively ignored. The third is the URL, which may be same-origin only; pushing a cross-origin URL throws a SecurityError. Crucially, pushState does not load anything and does not fire popstate — you are responsible for rendering the new view at the moment you push.

The state object is the right place to stash what the renderer needs, not the whole application store. Its size limits vary by browser, and a giant state blob makes history navigation mysteriously expensive. Treat the URL as the source of truth and state as a cache of derived data.

A Router That Respects the Back Button

The pattern that works: intercept internal link clicks, prevent the default navigation, push, and render; let popstate drive rendering for back and forward:

javascript
const routes = [
  { pattern: /^\/$/, view: () => renderHome() },
  { pattern: /^\/articles\/([^/]+)$/, view: (params) => renderArticle(params[0]) },
  { pattern: /^\/search$/, view: () => renderSearch(new URLSearchParams(location.search)) }
];

function resolve(pathname) {
  for (const route of routes) {
    const match = pathname.match(route.pattern);
    if (match) return () => route.view(match.slice(1));
  }
  return () => renderNotFound();
}

function navigate(path, { replace = false } = {}) {
  const url = new URL(path, location.origin);
  if (url.origin !== location.origin) {
    location.href = path;
    return;
  }
  const state = { path: url.pathname + url.search };
  if (replace) history.replaceState(state, '', url.pathname + url.search);
  else history.pushState(state, '', url.pathname + url.search);
  resolve(url.pathname)();
}

document.addEventListener('click', (event) => {
  const anchor = event.target.closest('a');
  if (!anchor) return;
  if (event.defaultPrevented || event.button !== 0) return;
  if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
  if (anchor.target && anchor.target !== '_self') return;
  if (anchor.hasAttribute('download') || anchor.getAttribute('rel') === 'external') return;
  const url = new URL(anchor.href, location.origin);
  if (url.origin !== location.origin) return;
  event.preventDefault();
  navigate(url.pathname + url.search);
});

window.addEventListener('popstate', (event) => {
  const path = event.state?.path || location.pathname + location.search;
  resolve(new URL(path, location.origin).pathname)();
});

resolve(location.pathname)();

The click handler's exclusion list is not paranoia: modified clicks open tabs, download anchors must download, and external links must navigate for real. Forgetting any one of those produces an app that eats middle-clicks, which power users notice immediately. The final resolve call on load is the deep-link path: a fresh document load must render whatever URL the user arrived on.

Hash Routing Versus Path Routing

CriterionPath routing with pushStateHash routing
Server configurationMust rewrite all app routes to index.htmlNo server changes needed
Clean URLsYesHash visible in the address bar
Initial loadOne extra round trip riskStatic file serves everything
Crawler understandingModern crawlers execute JSFragment not sent to servers
Works on static hostingOnly with a rewrite ruleEverywhere, immediately

Hash routing — listening to hashchange and treating the fragment as the path — remains the right answer for apps you cannot configure a server for and for progressive enhancement of multi-page sites. Path routing is the better product when you control the server, because the URLs read like the site they identify. Pick one per application; mixing them produces link forms that half the router does not recognize.

Scroll Restoration: The Detail Everyone Forgets

Browsers restore scroll position on history navigation for regular documents. SPAs lose that unless they participate. The history.scrollRestoration property, set to auto or manual, controls the built-in behavior; manual mode tells the browser to stay out so you can save scroll offsets per history entry and reapply them on popstate:

javascript
if ('scrollRestoration' in history) {
  history.scrollRestoration = 'manual';
}

const scrollPositions = new Map();

window.addEventListener('beforeunload', () => {
  scrollPositions.set(location.href, window.scrollY);
});

window.addEventListener('popstate', async () => {
  await renderRoute();
  const saved = scrollPositions.get(location.href);
  window.scrollTo(0, typeof saved === 'number' ? saved : 0);
});

A cheap version stores one offset per entry key; a better version keys on the history state and debounces writes during scroll. Whatever the strategy, scroll to the top on forward navigation to a new view and restore only on back — the asymmetry matches what users expect from the multi-page web.

The Server Half: Rewrites and Deep Links

Every path route you push must also be a path the server will serve, because the first visit to /articles/42 is an ordinary document request. Configure the host to rewrite unknown paths to the application shell — a catch-all rule in nginx, a routes array entry in Next.js, a _redirects file on static hosts. Without it, sharing a deep link yields a 404 and the back button's first press after a refresh does the same.

Pair the rewrite with an actual 404 view for paths your route table does not recognize, and consider server-rendering the shell with the correct title for the initial path so the first paint is not a blank document with a generic title.

Duplicate Entries, Double Listeners, and Title Hygiene

Two classic bugs come from listening carelessly. Registering popstate twice — once in a router module and once in a page component — renders every history step twice, which shows up as flicker or doubled analytics events. And pushing on every filter keystroke fills the history stack with entries, so the user's back button walks through thirty near-identical search states; debounce rapid updates with replaceState and reserve pushState for transitions a user would consciously navigate back to. Finally, call document.title after every navigation. The title is what the back-button menu shows, and a menu of identical titles makes history useless for anything beyond the last two steps.

The Navigation API: The Modern Complement

Browsers now ship a Navigation API that covers the same ground with a more coherent surface — navigation.navigate for programmatic moves, navigation.currentEntry for inspection, and interceptable navigate events that unify link clicks, back button, and pushes into one handler. It complements rather than replaces the History API: the classic pushState and popstate functions still work and still power most existing routers, while the Navigation API removes the need for the click-interception dance and the manual popstate bookkeeping when you target modern browsers only.

A pragmatic migration path is to keep the router's public interface — navigate(path) and a render callback — and swap the underlying mechanism when analytics show your browser support matrix allows it. Design your router so the URL parsing and view rendering never depend on which history mechanism feeds them; that separation is what makes the upgrade a one-file change instead of a rewrite.

Testing History Behavior Without a User

Back and forward behavior is hard to test by hand and easy to test in automation. Drive the page with pushState calls and synthetic popstate events in unit tests to verify that render is invoked exactly once per transition, and use end-to-end browser tests for the real back button, including the refresh-on-a-deep-link case. The bug that manual testing always misses is the one where the first load renders the wrong view for the current URL — automated navigation to an inner path on a cold start catches it in one line.

Common Mistakes

Calling pushState without rendering the new view

Fix: Render immediately after pushing — popstate only fires on actual back and forward navigation.

Filling the history stack with one entry per keystroke

Fix: Use replaceState for rapid intermediate updates and push only for meaningful transitions.

Forgetting the server rewrite for path routes

Fix: Configure a catch-all rewrite to the app shell so deep links and refreshes work.

Breaking middle-click and modifier-click on internal links

Fix: Let modified clicks and download or external links fall through to default browser behavior.

Leaving scroll restoration to the browser in an SPA

Fix: Set scrollRestoration to manual, save offsets per entry, and restore on popstate.

Best Practices

  • Keep the URL the source of truth; store only small derived caches in the history state object.
  • Set document.title on every navigation so the history menu stays useful.
  • Centralize routing in one module and register popstate exactly once.
  • Support both a not-found route and correct titles for server-rendered deep links.

Key Takeaways

  • pushState adds an entry without navigating; replaceState rewrites the current entry; neither fires popstate.
  • The state object travels with the entry and returns on popstate — keep it small and serializable.
  • Intercept link clicks with a careful exclusion list, and render on popstate to honor back and forward.
  • Path routing needs a server rewrite; hash routing needs nothing but shows fragments in the URL.
  • Save and restore scroll positions manually or users lose their place in long articles.
  • Debounce rapid URL updates with replaceState so the back button stays one step per intent.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement