Skip to content
FrontDepth, Home

Architecture & Patterns

Client-side routing

How single-page apps navigate without loading documents — the History API and link interception, server fallbacks for deep links, route matching and nesting, then data loading, code splitting, guards, scroll and focus after navigation.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

MPA and SPA navigation

In a multi-page app (MPA) every link click is a document navigation. The browser requests the new URL, the server returns a complete HTML document, the old page is unloaded, and the new one is parsed, styled and rendered from scratch. Along the way the browser does a lot for free: it updates the address bar and the session history, makes Back and Forward work, restores the scroll position, shows a loading indicator, resets focus to the top of the new document, and screen readers announce the new page's title.

A single-page app (SPA) loads one HTML document and then handles navigation in JavaScript. It intercepts the click, changes the URL with the History API without loading a document, and renders the new screen from components and data, usually fetched as JSON. That is client-side routing.

Text
MPA: click → GET /products/42 → HTML → unload old page → parse, CSS, JS → render
SPA: click → preventDefault() → history.pushState(…, "/products/42") → load data → render route

Why do it

  • State survives navigation. An audio player keeps playing, a half-written comment stays in its box, a sidebar keeps its scroll position.
  • Only what changed re-renders. The header, navigation and layout stay mounted; only the content area is replaced.
  • Navigations can be instant. When the route's code and data are already loaded or prefetched, there is no network round trip at all.

What it costs

The router takes over every job the browser used to do, and users notice each one it forgets: Back does nothing, a shared link shows a 404, the page opens scrolled halfway down, a screen reader stays silent after a click. The first visit also gets slower: without server rendering, the JavaScript bundle must download and run before anything appears, which delays and .

Where things stand

The line between the two models has blurred. Next.js, React Router in framework mode, Nuxt and SvelteKit render the first page on the server, attach event handlers with , and switch to client-side navigation after that. Browsers keep improving plain document navigations too: the back/forward cache restores whole pages instantly, and prefetching or prerendering the next page (the Speculation Rules API; MDN lists it as limited availability, supported mainly in Chromium-based browsers) hides network time.

So the real question is not "SPA or MPA" but which navigations in your product benefit from client-side routing, and whether you are ready to rebuild what the browser did for them. The rest of this topic is that list.

JuniorWeb platform

The History API: pushState, replaceState, popstate

Client-side routing rests on three pieces of the History API:

JavaScript
history.pushState({ page: 2 }, "", "/products?page=2");
history.replaceState({ page: 3 }, "", "/products?page=3");

window.addEventListener("popstate", (event) => {
  render(location.pathname, event.state);
});
  • pushState(state, unused, url) adds a new entry to the session history and changes the address bar. The browser does not load the URL and fires no event. The URL must have the same origin as the current one, otherwise a SecurityError is thrown. state is stored with the entry as a structured clone (no functions or DOM nodes; those throw a DataCloneError) and comes back as history.state and event.state. The second argument exists for historical reasons; pass "".
  • replaceState() changes the current entry instead of adding one. Use it for redirects, for normalizing a URL (/Products/ → /products), and for state that changes continuously, like the text of a search box, where one entry per keystroke would make Back useless.
  • popstate fires when the active entry changes through traversal: the Back and Forward buttons, history.back(), history.forward(), history.go(-2). Calling pushState() or replaceState() never fires it.

Two consequences shape every router:

  1. After pushState() the router must render by itself. Nothing will tell it that the URL changed.
  2. history.back() is asynchronous. On the next line location and history.state still show the old entry; the change arrives later with popstate. Code that calls back() and immediately reads the URL is reading the past.

Hash routing

Before the History API, SPAs kept the route in the fragment: /#/products/42. Changing location.hash does not load a document; it adds a history entry and fires hashchange (and popstate before it). The fragment is never sent to the server, so every route is served by the same / and deep links work on any static host.

The price: URLs that look odd, the fragment cannot also be used for in-page anchors, a server can never render the route because it never sees it, and the two mechanisms do not mix: pushState() never fires hashchange, even when only the hash changes. Hash routing is still a fair choice for widgets embedded in someone else's page, for apps opened from file://, or for hosts where you cannot configure rewrites.

Where state lives

history.state is good for things that belong to one entry and should not be in the URL, such as the scroll position of a list or which accordion was open. Some browsers persist state to disk and limit its size, so keep it small; anything a user should be able to share or bookmark belongs in the URL itself.

MiddleExample

A router: intercepting links, rendering, Back and Forward

A minimal history router has four parts: intercept link clicks, push the URL, render the matching route, and render again on popstate.

JavaScript
function shouldIntercept(event, link) {
  return (
    !event.defaultPrevented &&
    event.button === 0 &&
    !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey &&
    (!link.target || link.target === "_self") &&
    !link.hasAttribute("download") &&
    link.origin === location.origin
  );
}

document.addEventListener("click", (event) => {
  const link = event.target.closest("a[href]");
  if (!link || !shouldIntercept(event, link)) return;
  event.preventDefault();
  navigate(link.pathname + link.search + link.hash);
});

function navigate(to, { replace = false } = {}) {
  if (replace) history.replaceState(null, "", to);
  else history.pushState(null, "", to);
  render();
}

window.addEventListener("popstate", render);

function render() {
  const match = matchRoute(routes, location.pathname);
  app.replaceChildren(match ? match.route.view(match.params) : notFoundView());
}

render();

Why each check is there

  • Modifier keys and other buttons. Ctrl/⌘+click opens a new tab, Shift+click a new window. If the router swallows these clicks, power users lose basic browser features.
  • target="_blank" and download. The user asked for a new tab or a file, not an in-app navigation.
  • Other origins. A link to another site (or mailto:, whose origin is not yours) must leave the app. pushState() would throw for another origin anyway.
  • defaultPrevented. Some other handler already took care of this click.

One more case worth handling: a link that changes only the #hash on the current page. Letting the browser handle it keeps its native scroll to the anchor.

Use real <a href> elements for navigation. They work before JavaScript loads, show the URL on hover, support "Open in new tab" and "Copy link", are followed by crawlers, and are announced as links. <div onClick={() => navigate("/settings")}> has none of that. React Router's <Link> renders an <a> and applies the same filter: only a primary-button click with no modifier keys and no target other than _self.

The Mini Router build project on this platform builds exactly this loop, then adds matching and ranking, nested routes, guards and loaders. It uses a memory history with the same API (as React Router's createMemoryRouter does), because pushState() throws a SecurityError in the lab's sandboxed iframe.

The Navigation API

The Navigation API replaces the click listener and popstate with one navigate event that fires for the navigations a router cares about: link clicks, form submissions, location assignments, and Back and Forward between the app's own entries.

JavaScript
navigation.addEventListener("navigate", (event) => {
  if (!event.canIntercept || event.hashChange || event.downloadRequest !== null) return;
  const url = new URL(event.destination.url);
  event.intercept({
    async handler() {
      await renderRoute(url);
    },
  });
});

It is Baseline 2026 (newly available since January 2026), so it is usable today with a History API fallback for older browsers. intercept() also brings default focus and scroll handling after the handler finishes (focusReset, scroll).

MiddleWeb platform

Deep links and the server fallback

With history routing, /products/42 exists only inside the client router. Clicking there from inside the app works. Reloading the page, opening a bookmark or following a shared link does not go through the router: the browser asks the server for /products/42, and a static host that only has index.html answers 404.

The fix is a fallback (a rewrite): every URL that is not a real file is answered with the app's HTML, and files such as JavaScript, CSS and images are served as they are.

Text
# nginx
location / {
  try_files $uri $uri/ /index.html;
}

# Netlify, in _redirects
/*  /index.html  200

The development server usually does this for you, which is why "it works locally" and breaks after the first deploy.

Details that bite

  • Relative asset URLs. <script type="module" src="assets/app.js"> loaded from /products/42 resolves to /products/assets/app.js. That file does not exist, the fallback answers with index.html, and the browser refuses to run HTML as a module script: a blank page, but only on deep links. Use root-relative URLs (/assets/app.js) or configure the bundler's base path.
  • The status code. The fallback answers 200 for every URL, including /no-such-page. Users see your client-side "Not found" view, while crawlers see a successful page, a "soft 404". With server rendering, return a real 404. On a purely static host, Google's guidance for SPAs is to redirect to a URL that does return 404, or to add <meta name="robots" content="noindex"> to the not-found view.
  • APIs behind the same host. If /api/* falls through to index.html, a typo in an endpoint returns HTML with status 200, and the client fails on JSON.parse of <!doctype html>. Exclude API paths from the fallback.
  • A base path. When the app lives under /admin/, both the server rule and the router need it (React Router's basename, and the bundler's base path, such as Vite's base).
  • Caching. index.html must not be cached for long, or users keep an old HTML file that points to deleted, content-hashed bundles. Cache the hashed assets for a long time and revalidate the HTML.

Hash routing as the escape hatch

With /#/products/42 the server only ever sees /, so none of this applies. That is why hash routing survives in embedded widgets and on hosts without rewrite rules. You give up clean URLs, crawlable routes (Google advises against loading different content by fragment) and any chance of server rendering the route.

With server rendering

Frameworks that render on the server (Next.js, React Router's framework mode, Nuxt, SvelteKit) have no fallback problem: every route has a real server handler that renders HTML, returns the right status code and can redirect. Client-side routing takes over only after the first page has been hydrated.

MiddleConcept

Route matching, ranking, params and nested routes

A route pattern is a path made of static segments (users), dynamic segments (:id) and possibly a splat, or catch-all (*). Matching splits the pathname at / and compares segment by segment; dynamic segments capture params.

Ranking

Several patterns often match the same URL: /users/new matches both /users/new and /users/:id. Picking the first one in declaration order is fragile, because moving one line changes behaviour. Modern routers rank patterns by specificity instead: static beats dynamic, dynamic beats splat. React Router computes a score per route: each static segment adds 10, each dynamic segment 3, and a splat route gets a penalty.

Text
/users/new      static + static       wins for /users/new
/users/:id      static + dynamic      /users/42
/users/:id/*    + splat               /users/42/posts/7
/*              splat only            everything else (the 404 view)

So /users/new is never captured as a user with the id "new", wherever the routes are declared.

Details that cause bugs:

  • Params are strings. /users/42 gives "42", and /users/abc matches too. Convert and validate, and show "not found" for invalid ids.
  • Params are percent-decoded. /tags/c%23 gives "c#"; build URLs with encodeURIComponent().
  • Query and hash are not part of the match. /products?page=2 matches /products; read the query separately.
  • Trailing slashes and case. Decide once whether /About/ equals /about and redirect to one canonical form.

Nested routes and layouts

URLs are hierarchical and so are interfaces: /settings/profile shows the app shell, inside it the settings layout with its sidebar, inside that the profile form. Nested routes describe this tree, and a match is a list of routes from the root to the leaf. Each one renders its own part and an outlet where the child goes:

JSX
const router = createBrowserRouter([
  {
    path: "/",
    element: <AppShell />,
    children: [
      { index: true, element: <Home /> },
      {
        path: "settings",
        element: <SettingsLayout />,
        children: [
          { path: "profile", element: <Profile /> },
          { path: "billing", element: <Billing /> },
        ],
      },
      { path: "*", element: <NotFound /> },
    ],
  },
]);

Going from /settings/profile to /settings/billing keeps AppShell and SettingsLayout mounted, with their state and scroll position, and replaces only the leaf. The match list is also what lets a router load data for every level at once and show an error for one level while keeping the layouts around it. Next.js expresses the same tree with folders and layout.js files.

URLPattern

The platform now has its own matcher: new URLPattern({ pathname: "/users/:id" }).exec(url)?.pathname.groups.id. It is Baseline 2025 (newly available since September 2025) and exists in Node too. It matches one pattern at a time and does not rank, so the order is still up to you.

MiddleExample

The URL as state, guards and redirects

If a piece of state should survive a reload, be shareable, or be undone with Back, it belongs in the URL: filters, sort order, the search query, the page number, the selected tab, the open item. Component state alone loses all three.

JavaScript
function readFilters(search) {
  const params = new URLSearchParams(search);
  return {
    q: params.get("q") ?? "",
    tags: params.getAll("tag"),
    page: Math.max(1, Number.parseInt(params.get("page") ?? "1", 10) || 1),
  };
}

function filtersToSearch({ q, tags, page }) {
  const params = new URLSearchParams();
  if (q) params.set("q", q);
  for (const tag of tags) params.append("tag", tag);
  if (page > 1) params.set("page", String(page));
  const search = params.toString();
  return search ? `?${search}` : "";
}

Rules that keep this sane:

  • The URL is the source of truth. Read the filters from it on every render and derive the UI; do not keep a second copy in state that can drift.
  • Push or replace on purpose. Discrete choices that Back should undo (apply a filter, go to page 3) use push. Continuous input (each keystroke in a search box) uses replace, otherwise Back walks through every letter.
  • Keep defaults out. ?page=1&sort=relevance adds noise to every shared link; omit values that equal the default.
  • Validate. People edit URLs by hand: ?page=-1, ?page=abc, unknown tags. Parse defensively, as readFilters does.
  • Know the encoding. URLSearchParams serializes spaces as + and repeats keys for lists (?tag=a&tag=b); read lists with getAll().

React Router (useSearchParams) and Next.js (useSearchParams, router.replace) give you the same model.

Guards and redirects

A guard decides before rendering whether a navigation may go ahead: a signed-out user opening /settings goes to /login?next=/settings; a form with unsaved changes asks for confirmation.

  1. Redirect with replace. If /settings pushes /login, Back from the login page returns to /settings, which redirects again: the user is stuck. Replace the entry instead, and after signing in replace /login with the next path.
  2. Validate next. Accept only same-origin paths (starting with a single /), otherwise ?next=https://evil.example turns your login page into an open redirect.
  3. Client guards are UX, not security. Anyone can change client code or call the API directly, so the server must authorize every request. The React Router docs say the same about loaders: matched loaders run in parallel, so a parent loader cannot protect its children, and each loader must check access itself (or middleware must).
  4. Unsaved changes. beforeunload covers reloads and closing the tab; in-app navigations need the router's blocker (useBlocker in React Router) or the Navigation API's navigate event, which can be cancelled for same-document navigations.
SeniorFramework

Data loading and code splitting per route

The naive SPA fetches inside components, in effects. /projects/7/tasks renders ProjectLayout, whose effect fetches the project; when it arrives, TaskList renders and its effect fetches the tasks; then each task row fetches its assignee. Every request starts only after the previous component has rendered: a waterfall. With a lazily loaded route it gets worse, because the code has to arrive before the first fetch can even start.

Text
effects:  [route JS] → [project] → [tasks] → [assignees] → done
loaders:  [route JS]
          [project]
          [tasks]   → render once, done

Route loaders

The router knows from the URL alone which routes match, before anything renders. So it can start the data requests of every matched route in parallel at navigation time, or even earlier when a link is hovered:

JavaScript
const router = createBrowserRouter([
  {
    path: "/projects/:projectId",
    element: <ProjectLayout />,
    loader: async ({ params, request }) => {
      const res = await fetch(`/api/projects/${params.projectId}`, { signal: request.signal });
      if (!res.ok) throw new Response("Not found", { status: res.status });
      return res.json();
    },
    errorElement: <ProjectError />,
    children: [
      {
        path: "tasks",
        lazy: () => import("./routes/tasks.jsx"),
      },
    ],
  },
]);

What a good loader setup gives you:

  • Parallel requests. The parent's and the child's data load at the same time; the screen renders once with everything it needs.
  • Cancellation. When the user navigates again, the previous navigation's request.signal is aborted. Without this, a slow response for /projects/1 can arrive after the fast one for /projects/2 and overwrite the newer screen. Whatever the router, the rule is "the latest navigation wins".
  • Pending UI. Keep the old screen with a progress indicator (useNavigation().state === "loading") instead of flashing an empty page, or show a skeleton for slow data.
  • Errors per segment. A failed loader renders the nearest errorElement; the layouts above it stay on screen.

Loaders do not replace a data cache. TanStack Query, SWR or the framework's cache still deduplicate and revalidate; loaders decide when loading starts.

Code splitting per route

Routes are natural split points: someone on /settings does not need the chart library of /reports. React.lazy() with <Suspense> splits a component, but the import starts only when it renders, after its parent. A router-level lazy (above) loads the route module during navigation, in parallel with the parent's data. Prefetching hides the rest of the latency: Next.js's <Link> prefetches routes in production when the link scrolls into view, and many routers prefetch on hover or focus.

The trade-off to name in interviews: every prefetch costs bandwidth and server work, so prefetch likely next steps (visible links, hover intent), not the whole app.

SeniorPitfalls

After navigation: scroll, focus and announcing the page

Three things the browser does on every document navigation are now the router's job.

Scroll

Users expect a new page to start at the top (or at its #fragment) and Back to return to where they were. The browser's own restoration (history.scrollRestoration = "auto", Baseline widely available since January 2020) runs when the entry is traversed, which in an SPA is often too early: the previous page's data is still loading, the document is too short, and the position is lost. Routers therefore switch to "manual", save the scroll position per history entry (often in sessionStorage, keyed by the entry), and restore it after the route has rendered its content. React Router's <ScrollRestoration /> does this and sets scrollRestoration to "manual". Next.js's <Link> keeps the scroll position when the new page is already visible and otherwise scrolls to the top of the new page segment. Scrollable panels inside the page need the same treatment, or a long sidebar list jumps back to the top.

Focus

After a click on a link, focus is on that link. Then the router replaces the content:

  • if the link was inside the replaced content, it is removed and focus falls back to <body>;
  • if it was in a persistent navigation, focus stays there, and keyboard users must tab through the whole menu again to reach the new content;
  • either way, a screen reader is told nothing about the new page.

The common fix is to move focus to the new page's main heading, which makes the screen reader read it and puts the next Tab into the content:

JavaScript
function afterNavigation(title) {
  document.title = `${title} · Shop`;
  const heading = document.querySelector("main h1");
  if (heading) {
    heading.setAttribute("tabindex", "-1");
    heading.focus({ preventScroll: true });
  }
}

preventScroll: true leaves scrolling to the scroll logic above. Alternatives are focusing a wrapper or a skip link at the top of the page, which mimics a fresh page load. Do not move focus for changes that are not page changes: typing in a search box that updates ?q=, switching tabs that update the hash, opening a modal route. Focus jumping away while someone types is worse than no focus management.

The Navigation API has a default for this: after an intercepted navigation's handler finishes, focusReset: "after-transition" focuses the first element with autofocus, or <body>. Pass focusReset: "manual" to use your own logic.

Announcing the page

Update document.title on every route: it is what the browser shows in tabs and history, and what screen readers announce on a real page load. For client-side navigation, add an announcement in a polite live region ("Order history"), or rely on the framework: Next.js's built-in route announcer reads document.title, then the first <h1>, then the pathname. Mark the current navigation link with aria-current="page".

For slow navigations, also tell users something is happening: a visible progress indicator, and for long waits a polite status message. The ARIA, accessible names and focus management topic covers live regions in detail.

SeniorInterview tips

Interview tips

A 30-second answer. "A client-side router intercepts same-origin link clicks, updates the URL with history.pushState() without loading a document, matches the path against a ranked route table and renders the matched routes, nested from layout to page. On popstate it renders again for Back and Forward. Because the browser no longer navigates, the router takes over its jobs: the server needs a fallback for deep links, and the router handles data loading, scroll, focus and the page title."

Questions you are likely to get

  • Implement a tiny router. pushState, a popstate listener, a matcher with params. Say out loud that pushState() does not fire popstate, and list the clicks you must not intercept.
  • Hash or history routing? Server configuration, server rendering, crawlability, clean URLs, and where hash routing still makes sense.
  • Refreshing /dashboard/settings gives a 404 in production but not locally. Why? The dev server has a fallback, the production host does not; also relative asset paths and the 200-for-everything soft 404.
  • How does the router choose between /users/new and /users/:id? Ranking by specificity, not declaration order.
  • The page feels slow on navigation. What do you look at? Waterfalls of effect-based fetches, loaders in parallel, route-level code splitting, prefetching, pending UI instead of blank screens.
  • Two quick clicks show the wrong page. Why? A race: abort the previous navigation's requests, or ignore results that are not from the latest navigation.
  • Is client-side navigation accessible? Focus, title, announcements, scroll restoration.
  • Where should filter state live? In the URL; push for discrete choices, replace for typing.

Mistakes that cost points

  • Navigating with onClick on a div or a button instead of a real <a href>.
  • Expecting popstate after pushState(), or reading location right after history.back().
  • Treating a client-side guard as access control.
  • Forgetting the server fallback, the 404 status, or relative asset URLs.
  • One history entry per keystroke.

Senior signal

Discuss trade-offs instead of tools. When is an MPA with server rendering the better product? What does adopting the Navigation API (Baseline 2026) buy you, and what fallback does it still need? What does prefetching cost in bandwidth and server load? Treat URLs as a public API: stable, shareable, with redirects when they change. And measure navigations, not just the first load: route transitions are interactions, so watch INP and your own timing marks for click → content.

JuniorReview checklist

What to check when reviewing client-side routing

Use this list for routing code you did not write: a teammate's, a library's or an AI assistant's. Each check is a job the browser does on a document navigation; skip one and Back breaks, shared links show a 404, or screen readers stay silent.

  • Is every navigation a real <a href>, and are the clicks the router must not take left alone? A div with onClick loses "Open in new tab" and crawlers. Ctrl/⌘+click, Shift+click, target="_blank", download and links to other origins must reach the browser untouched.
  • Does the code render right after pushState(), and again on popstate? pushState() fires no event. Click a link, then press Back and Forward: the screen must follow the URL.
  • Does a deep link work in the production build? Reload /products/42 on the deployed build, not the dev server. The host needs a fallback to index.html that skips real files and /api/*; in the Network panel, scripts must load from root-relative URLs, not come back as HTML.
  • Do guards redirect with replace and validate next? A pushed redirect sends Back into a redirect loop. Accept only a next that starts with a single / and no \ after it: //evil.example and /\evil.example are another site. Client guards are UX: the API must check access too.
  • Is URL state pushed or replaced on purpose, and validated? Typing in a search box should replace, or Back walks through every letter. Params are strings: try ?page=abc and /users/abc, and expect a default or "not found", not a crash.
  • After a navigation, are the title, focus and scroll handled? document.title changes, focus moves to the main heading (tabindex="-1"), new pages start at the top, and Back restores the old position. The next Tab should land in the new content.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    5 questions

Hands-on work that uses this topic.