Course contentsShow
← Web Development
Lesson 977 of 2,98217. URL and History ManagementFree lesson

History API Routing Pattern

Implement routing using pushState and replaceState for clean URLs without hash fragments.

History API Routing Pattern

You'll learn how to implement clean, bookmark-friendly client-side routing using pushState and replaceState instead of hash fragments.

The Core Idea

Traditional hash-based routing uses URLs like example.com/#/about, where the hash fragment (#/about) triggers navigation without reloading the page. The History API pattern replaces this with clean URLs like example.com/about that look identical to traditional server URLs, but still work entirely on the client side.

This approach uses history.pushState() to add new "virtual pages" to the browser's history stack and updates the visible URL without triggering a full page reload.

How It Works

When a user clicks a link or triggers navigation:

// Instead of changing window.location.hash
// Use pushState to navigate cleanly
function navigateTo(path) {
  history.pushState(null, '', path);
  renderPage(path); // Your function to display the right content
}

// Listen for link clicks
document.addEventListener('click', (e) => {
  if (e.target.matches('a[data-route]')) {
    e.preventDefault();
    navigateTo(e.target.pathname);
  }
});

// Handle back/forward buttons
window.addEventListener('popstate', () => {
  renderPage(window.location.pathname);
});

When the user clicks a routed link, you prevent the default behavior, call pushState with the new path, and render the appropriate content. The popstate event handles browser back/forward navigation.

Use replaceState() when you want to update the current URL without adding a history entry—useful for redirects or updating query parameters.

Key Takeaway: History API routing creates clean, professional URLs without hash fragments by using pushState and replaceState to manage navigation state, making your single-page app feel like a traditional multi-page site while maintaining speed and control.