Changing the URL without reloading
The History API lets a single page app update the address bar without fetching a new document.
- pushState adds a new entry to the history stack and changes the URL.
- replaceState changes the current entry without adding to the stack.
- Neither triggers a navigation or page load, so your router renders the matching view in place.
Handling the back button
When the user clicks back or forward, the browser fires a popstate event. Your router listens for it and renders the view for the new URL.
- pushState does not fire popstate, so you render directly after calling it.
- popstate fires only on browser navigation, so you render in its handler.
What a router must do
- Intercept link clicks, call preventDefault, and pushState instead of letting the browser navigate.
- Match the path to a component and render it.
- Handle popstate to support back and forward.
- Make the server return the app shell for any deep linked path so a refresh works.
Key idea
pushState updates the URL without a reload while popstate handles back and forward, and the server must serve the app shell for deep links to refresh correctly.