In JavaScript, history.pushState(state, unused, url) updates the browser’s address bar URL and adds a new entry to the session history stack without triggering a full page reload or network request. Pair it with a popstate event listener on window so browser Back and Forward buttons respond cleanly to state changes.
1. Basic history.pushState() Usage
Call history.pushState() with a serializable state object, a string/empty value for the second parameter, and a relative or same-origin url:
// Update the browser URL without reloading the page
function navigateWithoutReload(nextUrl, stateData = {}) {
if (typeof window === "undefined" || !window.history) {
return;
}
window.history.pushState(stateData, "", nextUrl);
console.log("Updated URL:", window.location.pathname + window.location.search);
}
// Example: update query string or path while keeping current DOM state
navigateWithoutReload("/products?category=laptops&sort=price", {
category: "laptops",
sort: "price"
});
- First argument (
state): Stores structured data (like filter parameters or tab IDs) associated with that history entry and exposed viaevent.stateonpopstate. - Second argument (
title): Historically ignored by modern browsers; pass""for clarity and consistency. - Third argument (
url): Updates the displayed URL path, query string, or hash without reloading the document.
2. Handling Browser Back/Forward with popstate
pushState() adds a history entry, but clicking Back or Forward fires the window "popstate" event rather than reloading the page—listen to it to sync your UI:
// Sync application UI when the user clicks Back or Forward
window.addEventListener("popstate", (event) => {
const restoredState = event.state;
const currentUrl = new URL(window.location.href);
console.log("Navigated via Back/Forward to:", currentUrl.pathname + currentUrl.search);
console.log("Restored state:", restoredState);
});
event.state: Contains the state object passed topushState()for the entry being restored (ornullfor entries not created with state).history.replaceState()alternative: UsereplaceState()instead ofpushState()when you want to update the URL in place without adding a new Back-button step.
3. Common Traps to Avoid
Using pushState() looks simple, but a few browser rules and routing details cause common issues:
- Cross-origin URLs throw a
SecurityError:pushState()only allows URLs with the same origin (protocol, domain, and port) as the current document. - Direct page refresh or deep links on nested paths: Pushing
/dashboard/settingschanges the client URL, so your server or static host must also route/dashboard/settingstoindex.htmlif a user refreshes directly on that URL. - Forgetting to update UI state: Calling
pushState()changes the URL bar only—your JavaScript still needs to update visible content or fetch data for the new route/query.
TL;DR: Use history.pushState(state, "", nextUrl) to change the browser URL without reloading, and listen to window "popstate" to handle
