liveBook · Manning

URLPattern

As explained in Vanilla Web

URLPattern is a web-platform API for matching URLs against structured patterns and extracting their components or parameters.

A client-side router needs to turn a URL into a route and its parameters. URLPattern provides native matching for structured URL patterns. For routing, matching the pathname is usually enough: a pattern such as /products/:id accepts a product path and captures the dynamic segment as id. Matching selects a handler; navigation interception, data loading, and rendering remain separate responsibilities. section 10.4 section 10.4.2 section 10.0

Extract a path parameter

Create a pattern with new URLPattern({ pathname: "/products/:id" }), then call exec({ pathname: "/products/espresso-maker" }). The result’s pathname.groups.id is "espresso-maker". A nonmatching path returns null. URLPattern can also match components such as the hostname, search string, and hash, but query parameters are usually parsed separately with URLSearchParams. section 10.4.2

Keep the route matcher small and explicit:

  • Compile each route pattern once. Test the current pathname against routes in order, returning the first matching route and its extracted parameters. section 10.4.2
  • Put specific routes before generic ones: /products/new must precede /products/:id if “new” is not an ID. Return a not-found route when nothing matches. section 10.4.2
  • For older browsers, a regular-expression fallback can support literal segments and plain :name parameters. Do not assume it supports URLPattern modifiers or inline regular expressions; restrict shared route syntax or implement a fuller fallback. section 10.4.2
Listing 10.3 Matching routes with URLPattern and a regex fallback
function safeDecode(value) {
  try {
    return decodeURIComponent(value);
  } catch {
    return value;
  }
}

function compileRoute(path) {
  if ("URLPattern" in globalThis) {
    const pattern = new URLPattern({ pathname: path });

    return (pathname) => {
      const result = pattern.exec({ pathname });
      if (!result) return null;

      return Object.fromEntries(
        Object.entries(result.pathname.groups).map(([key, value]) => [
          key,
          safeDecode(value)
        ])
      );
    };
  }

  const keys = [];
  // Static segments may legally contain regex metacharacters
  // such as `.`, `+`, or parentheses, as in `/cards/v1.0`
  const escapeRegex = (segment) =>
    segment.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");

  const source = path
    .split("/")
    .map((segment) => {
      if (segment.startsWith(":")) {
        keys.push(segment.slice(1));
        return "([^/]+)";
      }
      return escapeRegex(segment);
    })
    .join("\\/");

  const regex = new RegExp(`^${source}$`);

  return (pathname) => {
    const match = pathname.match(regex);
    if (!match) return null;

    return Object.fromEntries(
      keys.map((key, index) => [
        key,
        safeDecode(match[index + 1])
      ])
    );
  };
}

The matcher implementation shows feature detection, parameter extraction, safe decoding, and the narrower regular-expression fallback. section 10.4.2

Use URLPattern where the browser supports it, but do not mistake route matching for a complete router. Keep real links and server-supported deep links; use the Navigation API or a History API fallback to intercept eligible navigations. The matched route can then supply parameters to the view that renders it. section 10.5 section 15.4

How Vanilla Web covers it

How deep it goes
Works through exec() results and a compiled matcher, including a limited regex fallback; does not implement all URLPattern syntax in fallback mode.
Examples
Demonstrates a product-detail path, a multi-parameter user/post path, and an ordered route table with a not-found result.
What it assumes
Assumes basic familiarity with URLs and client-side navigation while defining named path parameters before using them.
What you can do after
Build it from scratch: compile pathname routes, extract named parameters, provide a limited fallback, and handle unmatched paths.
How it connects
Connects route matching to the Navigation API, History API, URLSearchParams, and server-supported deep links.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.