Skip to content
jshacks.dev
Browser

How to Build a Tiny Client-Side Router

Build a tiny client-side router with the History API: route patterns with params, link interception, popstate, not-found handling, guards and lazy loaded views.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Postman and NGINX logos.

Routers look like framework magic until you write one. At heart a router does three things: it matches the current URL against a list of patterns, runs the code for the match and keeps the address bar and the history in step when the user clicks links or presses Back. That is less than a hundred lines of JavaScript, and building it once explains what every routing library does and when a small hand-written one is enough, for example in a widget, a prototype or a site that sprinkles interactivity over server-rendered pages. This guide shows how to build a tiny client-side router: the route table, turning a pattern with :params into a regular expression, matching and extracting parameters, navigating with the History API, intercepting links, handling Back and Forward, a not-found route, query strings, guards and redirects, lazy loaded views, scroll and focus handling, and what to leave to a library. It builds on the History API documented on MDN.

The route table

Start by describing what you want: a list of paths, each with a function that renders a view into the page.

routes.jsJavaScript
const routes = [
  { path: "/", view: () => "<h1>Home</h1>" },
  { path: "/products", view: () => "<h1>Products</h1>" },
  { path: "/products/:id", view: ({ id }) => `<h1>Product ${id}</h1>` },
  { path: "/users/:userId/posts/:postId", view: (p) => `<h1>${p.userId} / ${p.postId}</h1>` },
];
Text
(four routes; two of them have named parameters)

A path segment beginning with a colon is a parameter that matches any text up to the next slash, and its name becomes a key in the object passed to the view.

Turn a pattern into a matcher

Convert each pattern to a regular expression once, with a named capture group per parameter, and keep the names so you can build the params object. Escape the literal parts so that characters such as a dot in a path are matched literally.

compile.jsJavaScript
function compile(path) {
  const names = [];
  const source = path
    .split("/")
    .map((segment) => {
      if (segment.startsWith(":")) {
        names.push(segment.slice(1));
        return "([^/]+)";
      }
      return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    })
    .join("/");

  return { regex: new RegExp(`^${source}/?$`), names };
}

function match(routes, pathname) {
  for (const route of routes) {
    const { regex, names } = route.compiled ?? (route.compiled = compile(route.path));
    const result = regex.exec(pathname);
    if (!result) continue;

    const params = {};
    names.forEach((name, i) => {
      params[name] = decodeURIComponent(result[i + 1]);
    });
    return { route, params };
  }
  return null;
}

console.log(match(routes, "/products/42")?.params);
console.log(match(routes, "/users/ada/posts/7")?.params);
console.log(match(routes, "/nothing"));
Text
{ id: '42' }
{ userId: 'ada', postId: '7' }
null

The matcher tries routes in order and returns the first hit, so put specific patterns before general ones. The optional trailing slash makes /products/ equivalent to /products. Decoding each captured value turns %20 back into a space, which is the form users and links expect. A malformed escape in the address makes decodeURIComponent throw, so wrap it in a try in real code and treat the failure as not found.

Render the match

The router needs somewhere to put the result and a function that connects the location to a view.

render.jsJavaScript
const outlet = document.querySelector("#app");

function render() {
  const found = match(routes, location.pathname);

  if (!found) {
    outlet.innerHTML = "<h1>Page not found</h1>";
    document.title = "Not found";
    return;
  }

  outlet.innerHTML = found.route.view(found.params);
  document.title = found.route.title ?? document.title;
}
Text
(the matching view replaces the contents of #app)

Setting innerHTML from a view that includes route parameters is a cross-site scripting hole, as /products/<img src=x onerror=...> shows. Either have views return DOM nodes, build them with textContent, or escape every value. The next sections assume views return nodes for that reason.

nodes.jsJavaScript
const routes = [
  {
    path: "/products/:id",
    view: ({ id }) => {
      const h1 = document.createElement("h1");
      h1.textContent = `Product ${id}`;
      return h1;
    },
  },
];

function render() {
  const found = match(routes, location.pathname);
  const node = found ? found.route.view(found.params) : notFoundView();
  outlet.replaceChildren(node);
}
Text
(parameters are inserted as text, never parsed as HTML)

A function that changes the address and renders, using pushState for new navigation, gives the rest of your code one entry point.

navigate.jsJavaScript
function navigate(to, { replace = false } = {}) {
  const url = new URL(to, location.origin);
  if (url.origin !== location.origin) {
    location.assign(url);
    return;
  }

  const same = url.pathname + url.search + url.hash === location.pathname + location.search + location.hash;
  if (!same) history[replace ? "replaceState" : "pushState"](null, "", url);

  render();
  window.scrollTo(0, 0);
}

navigate("/products/42");
console.log(location.pathname);
Text
/products/42

External addresses leave to the browser, and navigating to the page you are already on does not add a duplicate history entry. Scrolling to the top mimics what a page load does, and you can skip it for replace navigations that only change a query.

Use event delegation so every link, including ones added later, goes through the router, but let the browser keep its own behaviors for modified clicks and for links that are not for the router.

links.jsJavaScript
document.addEventListener("click", (event) => {
  if (event.defaultPrevented || event.button !== 0) return;
  if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;

  const link = event.target.closest("a[href]");
  if (!link || link.target === "_blank" || link.hasAttribute("download")) return;

  const url = new URL(link.href, location.origin);
  if (url.origin !== location.origin) return;

  event.preventDefault();
  navigate(url.pathname + url.search + url.hash);
});
Text
(internal links navigate in place; external links, new tab clicks and downloads behave normally)

Because the links are ordinary anchors, they work without JavaScript, can be opened in a new tab and are visible to search engines, as long as the server also serves the pages.

Back, Forward and the first load

popstate fires when the user moves through history, and the first render must happen on load. Both call the same function.

start.jsJavaScript
window.addEventListener("popstate", render);
render();
Text
(Back and Forward re-render the view for the restored address; a reload renders the current route)

That completes the core: a route table, a matcher, a render function, a navigate function, link interception and popstate. The rest are the features that make it practical.

Query strings

The query string is not part of the path matching, so a view reads it through URLSearchParams. Pass it to the view along with the params.

query.jsJavaScript
function render() {
  const found = match(routes, location.pathname);
  const query = new URLSearchParams(location.search);
  const node = found
    ? found.route.view({ ...found.params }, query)
    : notFoundView();
  outlet.replaceChildren(node);
}

const searchRoute = {
  path: "/search",
  view: (params, query) => {
    const p = document.createElement("p");
    p.textContent = `Searching for ${query.get("q") ?? "nothing"}`;
    return p;
  },
};
Text
(the /search?q=router view shows: Searching for router)

Guards and redirects

Some routes need a condition, such as a signed-in user. Add an optional guard that returns true to continue, or a path to redirect to.

guard.jsJavaScript
const routes = [
  { path: "/login", view: loginView },
  {
    path: "/account",
    guard: () => (isSignedIn() ? true : "/login"),
    view: accountView,
  },
  { path: "/old-pricing", redirect: "/pricing" },
  { path: "/pricing", view: pricingView },
];

function render(depth = 0) {
  const found = match(routes, location.pathname);
  if (!found || depth > 5) return outlet.replaceChildren(notFoundView());

  const { route, params } = found;
  const target = route.redirect ?? (route.guard ? route.guard() : true);

  if (typeof target === "string") {
    history.replaceState(null, "", target);
    return render(depth + 1);
  }

  outlet.replaceChildren(route.view(params));
}
Text
(visiting /account while signed out replaces the address with /login and shows the login view)

Redirects use replaceState so the redirecting address does not stay in the history, where Back would bounce the user straight forward again. The depth limit prevents a redirect loop from hanging the page. Remember that client-side guards only hide views; the server must enforce access to the data.

Lazy loaded views

A router that imports every view up front loses the benefit of splitting code. Let a route provide a loader that uses dynamic import(), and show a loading state until it resolves.

lazy.jsJavaScript
const routes = [
  { path: "/", load: () => import("./views/home.js") },
  { path: "/reports", load: () => import("./views/reports.js") },
];

let renderId = 0;

async function render() {
  const id = ++renderId;
  const found = match(routes, location.pathname);
  if (!found) return outlet.replaceChildren(notFoundView());

  outlet.setAttribute("aria-busy", "true");
  const module = await found.route.load();
  if (id !== renderId) return;

  outlet.replaceChildren(module.default(found.params));
  outlet.removeAttribute("aria-busy");
}
Text
(each view is downloaded the first time its route is visited)

The counter discards a stale result: if the user clicks another link while a module is still loading, the earlier render must not overwrite the later one.

Accessibility after navigation

A page load announces itself to assistive technology and resets focus. A client-side navigation does neither, so the router must do it. After rendering, update document.title, move focus to the new heading or the main region and announce the change in a live region.

focus.jsJavaScript
function afterRender() {
  const heading = outlet.querySelector("h1");
  if (heading) {
    heading.tabIndex = -1;
    heading.focus({ preventScroll: true });
  }
}
Text
(a screen reader reads the new page heading after each navigation)

What to leave to a library

A tiny router covers static and parameterized routes, links, history, guards and lazy loading. It does not cover nested layouts with their own data loading, route transitions, scroll restoration for every case, search parameter typing, preloading on hover, server rendering or file-based routes. When an application needs several of these, adopt the router of your framework, or a small standalone library, and keep the hand-written one for pages where a hundred lines is the better trade.

Testing the router

A router is easy to test because its core is pure: compile() and match() take strings and return data. Write table-driven tests that list patterns, paths and the expected parameters, including awkward cases such as a trailing slash, an encoded space, a literal dot in a pattern and two routes that could both match. For the browser parts, run the page in a headless browser, click a link and assert the new address, the visible heading and the focused element, then press Back and assert that the previous view returns. Check the first load of a deep link, since that exercises the server fallback as well. A few dozen such cases give confidence, and they are the same checks that a larger library would have in its own suite.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.