MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
History API & Client-Side Routing0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
15.1History API & Client-Side Routing15.2Geolocation, Clipboard & Device APIs15.3Fullscreen & Screen Orientation APIs15.4Web Audio & MediaStream APIs Basics
HomeTutorialsJavaScript for AdvancedHistory API & Client-Side Routing
Geolocation, Clipboard & Device APIs

History API & Client-Side Routing

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

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. 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. 2
    history.replaceState(state, title, url): Overwrites the current history entry (ideal for query parameter updates or redirects).
  3. 3
    window.onpopstate: Fires when the user clicks the browser's Back or Forward navigation buttons.
1 User clicks navigation link
2 │
3 e.preventDefault()
4 │
5 history.pushState({ view: 'settings' }, '', '/settings')
6 │
7 URL bar updates to /settings (Zero page reload!)
8 │
9 Render Settings View Component into DOM

2. Building a Lightweight Client-Side Router

1class ClientRouter {
2 constructor(routes, outletSelector = '#app-root') {
3 this.routes = routes;
4 this.outlet = document.querySelector(outletSelector);
5 
6 this.init();
7 }
8 
9 init() {
10 // 1. Intercept internal anchor clicks
11 document.addEventListener('click', (e) => {
12 const link = e.target.closest('a[data-link]');
13 if (link) {
14 e.preventDefault(); // Stop default browser page refresh!
15 this.navigate(link.getAttribute('href'));
16 }
17 });
18 
19 // 2. Handle browser Back/Forward navigation
20 window.addEventListener('popstate', (e) => {
21 this.resolveRoute(window.location.pathname, e.state);
22 });
23 
24 // 3. Resolve initial page load
25 this.resolveRoute(window.location.pathname);
26 }
27 
28 navigate(url, state = {}) {
29 // Push state and update browser URL bar
30 history.pushState(state, '', url);
31 this.resolveRoute(url, state);
32 }
33 
34 resolveRoute(path, state = {}) {
35 const routeHandler = this.routes[path] || this.routes['/404'];
36 this.outlet.innerHTML = routeHandler(state);
37 }
38}

Route Table & Usage:

1const routes = {
2 '/': () => '<h1>Home Page</h1><p>Welcome to our SPA!</p>',
3 '/products': () => '<h1>Product Catalog</h1><p>Browse our collection.</p>',
4 '/settings': () => '<h1>User Settings</h1><p>Configure preferences.</p>',
5 '/404': () => '<h1>404 Not Found</h1><p>Page does not exist.</p>'
6};
7 
8// Mount router
9const router = new ClientRouter(routes);

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:

1# Nginx SPA Configuration
2location / {
3 try_files $uri $uri/ /index.html;
4}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does history.pushState(state, title, url) do?
Question 2
When does the window popstate event fire?
Question 3
Why does history.pushState() NOT fire the popstate event?
Question 4
What server-side configuration is mandatory for client-side SPA routing to work on page refresh?
Question 5
How does history.replaceState() differ from history.pushState()?
Next Lesson

Geolocation, Clipboard & Device APIs

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Advanced Pattern Matching & ReplacementGeolocation, Clipboard & Device APIs

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext