Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 50 ยท Getting Started

How Routing Works Under the Hood

See how React Router really works: the History API, pushState, popstate, the location object, the server fallback to index.html and hash routing.

React Router feels like magic the first time: you click a link, the page changes, the address bar updates, and nothing reloads. Underneath there is no magic, only three browser features and a bit of bookkeeping. If you know what they are, a surprising number of routing problems (a 404 on reload, a back button that does nothing, a link that refreshes the page) become easy to diagnose.

In this lesson you will learn what the History API does, what the location object contains, why your server must serve index.html for every path, and how hash routing avoids that requirement. You will also build a tiny history store that behaves like React Router's in-memory router. The browser-only parts are shown as read-only snippets, because our sandbox blocks the History API, and the runnable parts simulate it.

The browser keeps a stack of entries

Every tab has a session history: an ordered list of entries, plus a pointer to the current one. Normal navigation (clicking a link to another document) adds an entry after the current one and moves the pointer. The back and forward buttons only move the pointer. If you go back two steps and then navigate somewhere new, the entries ahead of you are discarded, just like undo history after a new edit.

JavaScript can work with this list through the history object:

JavaScript
// Browser History API (read-only: the sandbox blocks it)
history.pushState({ from: 'menu' }, '', '/products/7'); // add an entry and change the URL
history.replaceState(null, '', '/products/8');          // change the current entry in place
history.back();                                         // move the pointer one step back
history.go(-2);                                         // or any number of steps
console.log(history.state, location.pathname);

pushState(state, unused, url) does two things at once: it adds an entry and it changes the URL shown in the address bar to url (which must be on the same origin). It does not load anything and it does not fire an event. That is exactly what a router needs: change the address, then render something else yourself. replaceState has the same signature but overwrites the current entry, which is what a redirect should do so that the back button does not bounce the user into the redirect again.

The second argument is a legacy parameter that browsers ignore; pass an empty string.

Listening for back and forward

When the user presses back or forward (or code calls history.back() or history.go()), the browser moves the pointer and fires a popstate event on window. The event does not tell you the new URL, but by then location already has it. A minimal history router is just this:

JavaScript
// A minimal History-API router loop (read-only)
function navigate(path) {
  history.pushState(null, '', path);
  render(location.pathname);        // pushState fires no event, so we call render ourselves
}

window.addEventListener('popstate', () => {
  render(location.pathname);        // back and forward do fire an event
});

document.addEventListener('click', (event) => {
  const link = event.target.closest('a[data-link]');
  if (link) {
    event.preventDefault();         // stop the browser from loading a new document
    navigate(link.getAttribute('href'));
  }
});

React Router does this and more. Its Link component renders a real <a href> and intercepts normal clicks; its router listens to popstate; it stores the navigation state you pass and a unique key inside history.state; and it publishes every change through React so components re-render.

sequenceDiagram
  participant U as User
  participant L as Link
  participant R as Router
  participant H as History API
  participant C as Components
  U->>L: click "Products"
  L->>R: navigate("/products")
  R->>H: pushState(state, "", "/products")
  R->>C: new location, re-render
  U->>H: press the Back button
  H-->>R: popstate event
  R->>C: previous location, re-render

A click goes through the router into pushState, but the Back button reaches the router through the popstate event.

What the location object contains

The browser's window.location splits the URL into parts. React Router exposes a very similar object through the useLocation hook:

Field Example Meaning
pathname /products/7 The path. Routes are matched against this part only.
search ?sort=price&tag=a The query string, including the leading ?.
hash #reviews The fragment, including the leading #.
state { from: 'menu' } Data attached to this history entry. React Router only.
key a1b2c3 A unique id per entry. The first entry has the key default.

Matching ignores the query string and the hash on purpose: /products/7?sort=price#reviews and /products/7 show the same route. The query string is read with URLSearchParams, which you meet again in Search Params and useSearchParams, and the extra navigation state is the topic of useLocation and Navigation State.

Try it: this stand-in parses whatever URL you pick with the browser's URL class, which is the same machinery you would use on location.

Splitting a URL into pathname, search and hash

Click "Example 4": the path segments are still percent-encoded in pathname, so a router has to decode each param itself. That is why useParams() returns decoded strings, and why a stand-in must call decodeURIComponent.

A history stack you can poke

React Router has a router for situations without an address bar (tests, React Native, embedded widgets) called MemoryRouter, and in data mode createMemoryRouter. It keeps the same list-and-pointer model as the browser, but in a plain JavaScript array. This runnable store does the same thing, so you can watch pushes, replaces and back/forward moves on a visible stack.

A mini in-memory history stack

Do this experiment: press push three times, press back twice, then press push once more. The entries that were ahead of you disappear, because a new navigation from the middle of the stack discards the future. Then press replace and notice that the stack does not grow: only the current entry changes. Real Navigate, redirect and navigate(..., { replace: true }) use exactly this.

Why the server must serve index.html

With history routing the address bar shows /products/7, but your server only has one real document: index.html. Clicking a link never asks the server for anything, because the router handles it. The trouble starts when the browser does ask the server: when the user reloads the page, opens a bookmark, or pastes the URL into a new tab. The browser then requests /products/7, and a plain static server answers 404, because no file has that name.

flowchart TD
  Q["Browser requests<br/>/products/7"] --> F{"Does a file with<br/>that name exist?"}
  F -->|"yes (an asset, e.g. /assets/app.js)"| A["Send the file"]
  F -->|"no, and no fallback"| E["404 Not Found"]
  F -->|"no, with fallback rule"| I["Send index.html"]
  I --> J["JavaScript starts,<br/>router reads the URL"]
  J --> P["Product page appears"]

A fallback rule sends index.html for unknown paths so the router can take over in the browser.

The cure is a fallback rule ("SPA fallback"): serve the real file if one exists, otherwise serve index.html with status 200. Every static host has a way to do it:

NGINX
# nginx (read-only)
location / {
  try_files $uri /index.html;
}
TEXT
# Netlify: a file called _redirects in the published folder (read-only)
/*  /index.html  200

Vite's dev server and vite preview already include a fallback, which is why it works locally and often breaks on the first deployment. Remember this one when a teammate says "it works on my machine but reloading shows a 404". Framework mode avoids the problem differently: its server renders the right HTML for each URL. See SSR, Streaming and Deployment.

Hash routing: the no-server-needed option

A URL such as https://example.com/app#/products/7 has a hash. Browsers never send the hash to the server, so the server only ever sees /app, and no fallback rule is needed. Changing only the hash adds a history entry and fires a hashchange event (and also a popstate). This is why static file hosting, local file:// pages and our sandboxed examples can use it.

React Router offers it as HashRouter (declarative) and createHashRouter (data). Use it only when you cannot configure the server, because the URLs look worse, the hash can no longer be used for in-page anchors, and search engines handle them poorly. Everything else you learn in this course works the same in both styles: only the two functions "read the location" and "change the location" differ.

History routing Hash routing
URL /products/7 /#/products/7
Real router BrowserRouter, createBrowserRouter HashRouter, createHashRouter
Server fallback needed Yes No
Works in this course's live editor No Yes (used by every stand-in)

For a longer treatment of building such a router from scratch, see Client-Side Routing in the React tutorial.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does history.pushState do?

    pushState updates the session history and the displayed URL, but the browser neither loads anything nor fires an event. The router must render the new location itself.
  2. 2. When does the browser fire a popstate event?

    popstate signals traversal of existing history entries. Calls to pushState and replaceState do not fire it, which is why routers render after calling them.
  3. 3. A deployed single-page app works when you click links but shows 404 after reloading /products/7. What is missing?

    On reload the browser asks the server for /products/7. Without a fallback rule, a static server has no such file and returns 404. Serving index.html lets the router handle the URL.
  4. 4. After you push three entries, go back twice and then push again, what happens to the entries ahead of the pointer?

    A new navigation from the middle of the history discards the entries that were ahead, exactly like undo history after a new edit. The memory history in this lesson shows it.
  5. 5. Why does hash routing need no server configuration?

    The fragment stays in the browser, so the server only ever sees the same path (for example /app) and always returns the same document.

Summary

  • The browser keeps a stack of history entries and a pointer; pushState adds an entry, replaceState overwrites the current one, and back or forward only move the pointer.
  • pushState fires no event, while Back and Forward fire popstate, so a router has to listen to popstate and render after its own pushes.
  • The location is made of pathname, search, hash, plus React Router's state and key; routes are matched against pathname only.
  • With history routing the server must return index.html for unknown paths, otherwise a reload or a shared link ends in a 404.
  • Hash routing avoids the server rule by keeping the route after #, which is why the live stand-ins use it.
  • MemoryRouter and createMemoryRouter use the same stack model in plain JavaScript, for tests and non-browser hosts.

Next: Choosing Between Declarative, Data and Framework Mode