History API
The History API lets a page change the URL and session history without a full reload. SPAs use pushState / replaceState and the popstate event to keep the address bar in sync with the view.
Detailed Explanation
history.pushState(state, "", url) adds a history entry and changes the visible URL (same origin). replaceState updates the current entry. The unused title argument is ignored in browsers; pass "". state is a structured-cloneable value you get back on popstate.
The back button fires popstate with event.state. It does not fire on pushState itself. After a pushState, you render because you called it. After back/forward, you listen and render from location + event.state.
location.hash changes (#/users) fire hashchange and do not need the History API. Hash routing works on static hosts that cannot rewrite paths. Path routing (/users/7) needs the server to serve the SPA shell for unknown paths, or a 404 appears on refresh.
history.back(), forward(), go(n) move the stack. length is the session history length, not something you should logic on.
What it costs you: lost state if you put too much in state (size limits, clone rules: no functions). Forgetting the server fallback. Fighting the browser: pushState on every keystroke fills history; debounce or replaceState for query updates (?q=).
Reach for pushState when the view is a new place the user should return to. Reach for replaceState when you are normalising a URL. Reach for a router library when you have many routes, guards, and code-split pages.
Scroll restoration is part of history. The browser may restore scroll on popstate; SPAs that render async often fight it and jump the user to the top. history.scrollRestoration = "manual" plus saving scrollY in state is the usual fix.
pushState does not check that the path exists. You can push /this-is-not-a-route and the address bar will lie until you add a not-found view. Run the same matcher you use for first paint.
Query updates during typing should replaceState so back does not walk through ?q=a, ?q=ab, ?q=abc.
Code Examples
function navigate(path, state = {}) {
history.pushState(state, "", path);
render(path, state);
}
window.addEventListener("popstate", (event) => {
render(location.pathname, event.state ?? {});
});
function render(path, state) {
console.log("view", path, state);
}
navigate("/users/7", { from: "list" });const params = new URLSearchParams(location.search);
params.set("q", "ada");
history.replaceState(null, "", `${location.pathname}?${params}`);Common Gotchas
Cross-origin `pushState` throws
you cannot put `https://other.example` in the URL.
`popstate` does not run on `pushState`
if you only render in `popstate`, the first navigation shows a blank view.
Refresh on `/users/7` needs server rewrite to `index.html`
otherwise the host 404s.
`hashchange` and `popstate` are different events
hash-only apps can ignore History API.