The problem
In a traditional multi-page app, clicking a link loads a whole new page. The screen flashes white, and everything on the old page is thrown away, including the parts that have nothing to do with the link you clicked. A half-typed search in the header is cleared, a video playing in the sidebar stops, and a menu you’d expanded collapses again. Websites have worked like that for decades, and next to a native app, where moving between screens is instant, it feels clunky. And when there’s a loading spinner on every navigation, the whole app feels slow, even if the content itself loads quickly.
The pattern
With client-side routing, the browser doesn’t load a new page when you move between views. The router intercepts link clicks, calls pushState from the History API to change the URL, and renders the component for the new route in place of the old one. When users press the back or forward button, the browser fires a popstate event, and the router renders the route for that URL.
Problem
Solution
The router only replaces the view for the route, so anything outside that view keeps its state, such as the search in the header or the video in the sidebar. The view users navigate away from is still removed, so a form inside it loses what they typed, the same as it would on a full page load. The scroll position also stays where it was, which is rarely what you want for a new view, so the router has to scroll to the top on each navigation and put the old position back when users go back.
Router libraries such as React Router and Vue Router make the History API calls for you, so all you have to do is map URL patterns to components.
Example
The first example is a small router written without a library, so you can see each step from the Solution. The framework examples then set up the same routes with a router library.
A Minimal Router
This router intercepts clicks on internal links, calls pushState and renders the matching route, and it renders again when the browser fires popstate.
class Router {
constructor(routes) {
this.routes = routes;
document.addEventListener('click', (e) => {
// closest() also catches clicks on elements nested inside the link
const link = e.target.closest('a[href^="/"]');
// Clicks with a modifier key open a new tab, so the browser handles those
if (!link || e.metaKey || e.ctrlKey || e.shiftKey) return;
e.preventDefault();
this.navigate(link.getAttribute('href'));
});
window.addEventListener('popstate', () => this.render(location.pathname));
this.render(location.pathname);
}
navigate(path) {
history.pushState({}, '', path);
this.render(path);
}
render(path) {
const route = this.routes.find(r => r.path === path)
|| this.routes.find(r => r.path === '*');
if (!route) return;
const container = document.querySelector('#app');
container.innerHTML = '';
container.appendChild(new route.component().render());
}
}
const router = new Router([
{ path: '/', component: HomePage },
{ path: '/about', component: AboutPage },
{ path: '*', component: NotFoundPage }
]);
The Same Routes with a Router Library
A router library does the click handling, the History API calls, and the rendering for you. The code in each tab declares the same three routes as the minimal router: a home page, an about page, and a “not found” page for any other URL. React Router and Vue Router take a list of routes, while SvelteKit builds its routes from the files in src/routes. Each library also has a function for navigating from your own code, which is useNavigate in React Router, router.push in Vue Router, and goto in SvelteKit.
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
} <!-- App.vue -->
<template>
<div>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<router-view />
</div>
</template>// main.js: the router is installed on the app, not declared inside a component
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import App from './App.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/:pathMatch(.*)*', component: NotFound }
]
});
createApp(App).use(router).mount('#app'); <!-- src/routes/+layout.svelte -->
<script>
// SvelteKit passes the page matching the URL as the children snippet
let { children } = $props();
</script>
<!-- Plain links work: SvelteKit intercepts same-origin clicks and routes client-side -->
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<!--
src/routes/+page.svelte renders /
src/routes/about/+page.svelte renders /about
src/routes/+error.svelte renders the "not found" page for any other URL
-->
{@render children()} Scroll Position Management
After pushState, the window is still scrolled to wherever it was on the previous view. You can fix that in two places in the minimal router. In navigate, the router saves the current position before leaving and scrolls the new view to the top. In the popstate handler, it restores the position it saved for the view users are going back to.
// The router restores scroll itself, so the browser shouldn't also try
history.scrollRestoration = 'manual';
const scrollPositions = new Map();
class Router {
// Same as before, except that render() also sets this.currentPath = path,
// and the popstate listener calls this.handlePopState()
navigate(path) {
scrollPositions.set(this.currentPath, window.scrollY); // Save before leaving
history.pushState({}, '', path);
this.render(path);
window.scrollTo(0, 0); // A new view starts at the top
}
handlePopState() {
// location has already changed, so currentPath is still the view being left
scrollPositions.set(this.currentPath, window.scrollY);
this.render(location.pathname);
window.scrollTo(0, scrollPositions.get(location.pathname) ?? 0);
}
}
Router libraries manage the scroll position for you. Vue Router has a scrollBehavior option, React Router has a ScrollRestoration component for its data routers, and SvelteKit resets and restores the scroll position by default.
Hash-Based Routing
With History API routes, the server treats /about as the path to a real file. If users reload the page or open a link to it, the browser asks the server for /about, and unless the server is configured to return your app’s HTML for every route, it responds with a 404. Hash-based routing avoids that, because the browser never sends the part of the URL after the # to the server. A URL such as example.com/#/about always requests /, so it works on a static host you can’t configure, and the router listens for hashchange instead of popstate.
// Links are written as <a href="#/about">, so no click handler is needed
function renderCurrentRoute() {
render(location.hash.slice(1) || '/');
}
window.addEventListener('hashchange', renderCurrentRoute);
renderCurrentRoute();
Benefits
- Navigation is faster, because the browser doesn’t reload the whole page on each click.
- Anything outside the swapped content keeps its state, such as a video playing in a sidebar or a half-typed search in the header.
- Animated transitions between views are easier, because the old and new content are on the same page.
- The server does less work, because it only sends data instead of rendering entire HTML pages.
- You can run your own code before each navigation, such as a route guard that sends logged-out users to the login page.
Tradeoffs
- It needs JavaScript, and without it the routing doesn’t work at all, so you should consider server-side fallbacks.
- The server needs configuring so that a direct request for any route’s URL serves your app instead of a 404, unless you use hash-based routing.
- SEO gets more complicated, because some crawlers might not run JavaScript, so you might need Server-Side Rendering (SSR) or prerendering.
- Memory leaks build up, because the page never reloads to free the memory, so listeners and subscriptions need cleaning up when components unmount.
- Scroll and focus need managing, by you or by your router library, because browsers only reset them automatically for full page loads.
- The back button can behave in confusing ways if you use
pushStatewhere you meantreplaceState, or the other way around.
Summary
Client-side routing uses the History API to change the URL and swaps the content in place, so the page never reloads and everything outside the swapped view keeps its state. The back button still works, and each view still has a URL people can share, but the router has to manage the scroll position itself.