JavaScript Notes
Master the JavaScript History API for SPA routing. Learn pushState, replaceState, popstate event, and how SPAs manage URL navigation without page reloads. Includes interview Q&A.
The History API gives JavaScript control over the browser's session history — the list of pages the user has visited in the current tab. Its most powerful feature is letting Single Page Applications (SPAs) change the URL without reloading the page, enabling bookmarkable URLs and working Back/Forward buttons.
💡 Key insight: Before the History API (HTML5), SPAs used URL hashes (#page) for navigation.pushStateeliminated that need and allows clean URLs like/products/42even in a fully client-side app.
The History Stack
Basic Navigation Methods
console.log(history.length); // number of entries in history stack
history.back(); // same as clicking the ← Back button
history.forward(); // same as clicking the → Forward button
history.go(-1); // go back 1 (same as back())
history.go(1); // go forward 1 (same as forward())
history.go(-3); // jump back 3 entries
history.go(0); // reload current page4 // back(): navigates to previous URL // forward(): navigates to next URL // go(-3): jumps 3 pages back // go(0): reloads current page
pushState — Add a History Entry Without Reloading
// history.pushState(stateObject, title, url)
history.pushState({ page: "products", id: 42 }, "", "/products/42");
console.log(location.pathname); // URL has changed
console.log(history.state); // state object is stored"/products/42"
{ page: "products", id: 42 }The page did not reload — only the URL bar changed. The browser back button now goes back to the previous URL.
replaceState — Update Current Entry Without Adding One
// Replace the current history entry (no new entry added)
history.replaceState({ page: "products", filter: "red" }, "", "/products?color=red");
console.log(location.pathname); // updated
console.log(location.search); // updated
console.log(history.state);"/products"
"?color=red"
{ page: "products", filter: "red" }replaceState is useful for updating the URL as a user types in a search box — you don't want a history entry for every keystroke.
The popstate Event
popstate fires when the user navigates using the Back/Forward buttons, or when history.go() is called. It does not fire when pushState or replaceState is called.
"Navigated to: /products"
"State: { page: 'products', id: 42 }"
"Rendering: products"Building a Simple SPA Router
"Rendered: /" // on page load "Rendered: /about" // after clicking About link "Rendered: /" // after pressing Back
pushState vs location.href
pushState | location.href | |
|---|---|---|
| Page reload | ❌ No reload | ✅ Full reload |
| Adds history entry | ✅ Yes | ✅ Yes |
| URL change | ✅ Yes | ✅ Yes |
| State object | ✅ Yes | ❌ No |
| Use in SPAs | ✅ Ideal | ❌ Not suitable |
When to Use the History API
- SPA routing — React Router, Vue Router, Angular Router all use
pushStateunder the hood - Search filtering — update URL as filters change so users can share/bookmark results
- Multi-step forms — each step gets a URL so Back goes to the previous step
- Infinite scroll — update URL to reflect the current scroll position
Common Mistakes
- Not handling the initial page load —
popstatedoesn't fire on first load; callrenderRoute(location.pathname)manually. - Using
pushStateevery keystroke — usereplaceStatefor incremental updates (e.g., search boxes). - Forgetting the server — if users bookmark a
pushStateURL and refresh, the server must serve the sameindex.html(configure server-side catch-all). - Not setting the
stateobject —event.statewill benullafter back/forward if no state was provided. - Calling
pushStatewith cross-origin URLs — the new URL must be same-origin; otherwise a security error is thrown.
Interview Questions
Q1. What does history.pushState() do?
It adds a new entry to the browser's session history stack with a given state object, title, and URL, without reloading the page. This is the foundation of SPA client-side routing.
Q2. What is the difference between pushState and replaceState?
Both update the URL and state without a page reload.pushStateadds a *new* entry to the history stack (the user can press Back to return).replaceState*modifies* the current entry — no new entry is added, so Back goes to the page before the previouspushState.
Q3. When does popstate fire?
popstatefires when the user navigates the session history — i.e., pressing Back/Forward, or callinghistory.go(). It does not fire whenpushStateorreplaceStateis called programmatically.
Q4. How does React Router use the History API?
React Router wrapspushState/replaceStatein its ownhistoryobject. Whennavigate("/path")is called, it callshistory.pushStateto update the URL and then re-renders the matched Route components without a page reload.
Q5. What is history.state?
Thestateproperty returns the state object associated with the current history entry — the first argument passed to the most recentpushStateorreplaceStatecall. Returnsnullif no state was set.
Q6. What happens if a user bookmarks a pushState URL and opens it directly?
The browser requests that URL from the server. If the server only serves static files and has no catch-all route, it returns a 404. The fix is to configure the server (e.g., Nginx, Express) to return index.html for all routes so the SPA can handle them client-side.Q7. Can pushState change the origin of the URL?
No.pushStatecan only change the path, query string, and hash of a same-origin URL. Attempting to set a cross-origin URL throws aDOMException: SecurityError.
Key Takeaways
pushStatechanges the URL without a page reload — it's the engine behind every SPA router.replaceStateupdates the current entry;pushStateadds a new one.popstatefires when navigating history (Back/Forward) — use it to sync your UI with the URL.- Always handle the initial page load separately (
popstatedoesn't fire on first visit). - Configure your server to serve
index.htmlfor all SPA routes to avoid 404s on refresh. history.statestores arbitrary data per history entry — use it to pass route metadata.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for History API in JavaScript — SPA Routing & pushState Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, history
Related JavaScript Master Course Topics