History API & Client-Side Routing
History API & Client-Side Routing in Modern JavaScript
Single Page Applications (SPAs) like React, Vue, and Next.js do not reload the entire HTML page when navigating between views. Instead, they intercept navigation and manipulate the browser's session history using the HTML5 History API (pushState, replaceState, and popstate), creating seamless transitions while preserving bookmarkable URLs.
1. The History API Methods
The window.history object exposes three primary routing primitives:
- 1
history.pushState(state, title, url): Pushes a new entry onto the browser's history stack and updates the URL bar without triggering a page reload. - 2
history.replaceState(state, title, url): Overwrites the current history entry (ideal for query parameter updates or redirects). - 3
window.onpopstate: Fires when the user clicks the browser's Back or Forward navigation buttons.
2. Building a Lightweight Client-Side Router
Route Table & Usage:
3. Server Configuration: The "SPA Fallback" Rewrite
A critical production gotcha: If a user refreshes the page while at https://mysite.com/settings, the browser sends an HTTP GET request to the web server for /settings.
If the server is not configured to rewrite all routes to index.html, it will return a 404 Not Found!
Production Server Rule (Nginx / Cloudflare / Netlify):
All non-file requests must rewrite to index.html:
Practice Quiz
Geolocation, Clipboard & Device APIs
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Advanced Pattern Matching & Replacement | Geolocation, Clipboard & Device APIs |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.