How does the window.history API work?
JavaScriptThe short answer
The window.history API lets you manipulate the browser's session history — the list of pages the user has visited in the current tab. You can go back, go forward, and add or replace entries without a page reload. This is the API that React Router and other client-side routers use to handle navigation in SPAs.
Basic navigation
history.back(); // same as clicking the back buttonhistory.forward(); // same as clicking the forward buttonhistory.go(-2); // go back 2 pageshistory.go(1); // go forward 1 pagepushState — add a new history entry
history.pushState( { page: 'about' }, // state object (any serializable data) '', // title (ignored by most browsers) '/about' // new URL);This does three things:
- Changes the URL in the address bar to
/about - Adds a new entry to the history stack
- Does NOT reload the page or make a network request
The user can now hit the back button to go to the previous URL.
replaceState — replace the current entry
history.replaceState({ page: 'home' }, '', '/home');Same as pushState, but it replaces the current history entry instead of adding a new one. The user cannot go back to the previous URL because it was replaced.
The popstate event
When the user clicks back or forward, the popstate event fires:
window.addEventListener('popstate', (event) => { console.log('Navigation happened'); console.log(event.state); // the state object from pushState // Update the UI based on the new URL renderPage(window.location.pathname);});This is how SPAs handle browser navigation. When the user clicks back, the SPA listens for popstate, reads the new URL, and renders the appropriate page without a full reload.
How React Router uses it
React Router uses pushState when you navigate and popstate to detect back/forward clicks:
// When you click a Link, React Router calls:history.pushState(null, '', '/dashboard');// Then renders the Dashboard component// When user clicks back, React Router listens for popstate// and renders the previous route's componentInterview Tip
Explain pushState (adds entry, changes URL, no reload) and popstate (fires on back/forward). Connecting it to how React Router works shows you understand the internals of client-side routing, not just the API surface.
Why interviewers ask this
The History API is the foundation of client-side routing. Interviewers ask about it to see if you understand how SPAs handle navigation. If you have ever wondered how React Router changes the URL without a page reload, this is the answer.