Before Using JavaScript URLPattern for Routing, Test Encoded Paths and Query Strings

Test JavaScript URLPattern routing with encoded paths, optional segments, and query strings, plus a limited fallback for unsupported browsers.

Published
Reading time
6 min read
Before Using JavaScript URLPattern for Routing, Test Encoded Paths and Query Strings
On this page

JavaScript URLPattern routing examples can look straightforward until an encoded slash, optional path segment, or repeated query parameter changes what your application receives. The important distinction is that a browser first parses and normalizes a URL; URLPattern then matches components of that parsed URL.

This tutorial builds a small test page for a /products/:id? route. It also shows a limited fallback for browsers without URLPattern and keeps query-string policy separate from pathname matching.

Key Takeaways

  • A pathname match does not automatically constrain the query string. Inspect query parameters separately when they affect route selection.
  • A captured path segment can contain encoded characters such as %2F. Decoding it may produce a slash even though the original pathname had only one segment at that position.
  • URL parsing can normalize a path before matching. Inspect the parsed pathname as well as the match result.
  • Feature-detect URLPattern and provide an intentional fallback. Neither a match nor client-side routing authorizes access to data.

What this example matches

The pattern /products/:id? describes a pathname with an optional id segment. The example treats /products and /products/42 as pathname matches. It then applies a separate application rule: the query string must contain exactly one view parameter, whose value is full.

The distinction matters for a URL such as /products/42?view=compact: the pathname can match while the application's additional query rule rejects the route. Similarly, tag parameters can be read without being part of the pathname pattern.

This is a routing demonstration, not an authorization check or a complete router. The code has not been executed for this article; use the page below to verify behavior in your target browsers.

Advertisement

Create a reproducible test page

Save the following as urlpattern-test.html. From its directory, run python3 -m http.server 8000, then open http://localhost:8000/urlpattern-test.html. Python's standard library supplies the local server; no JavaScript dependencies are needed.

Enter a URL or path in the form. The page displays the parsed URL, pathname match, captured ID, decoded ID, query values, and the result of the additional query rule. It restricts input to the page's origin so this example remains focused on local routes.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>URLPattern route experiment</title>
</head>
<body>
  <h1>Route experiment</h1>
  <form id="route-form">
    <label for="url-input">URL or path</label>
    <input id="url-input" size="80"
      value="/products/a%2Fb?view=full&amp;tag=red+blue&amp;tag=green%2Bwhite">
    <button type="submit">Inspect</button>
  </form>
  <pre id="result" aria-live="polite"></pre>

  <script>
    const form = document.getElementById('route-form');
    const input = document.getElementById('url-input');
    const result = document.getElementById('result');

    let pattern = null;
    if (typeof URLPattern === 'function') {
      try {
        pattern = new URLPattern({ pathname: '/products/:id?' });
      } catch (error) {
        // Use the narrowly scoped fallback if pattern construction fails.
      }
    }

    // This fallback implements only the route used by this page.
    const fallback = new RegExp('^/products(?:/([^/]+))?$');

    function inspect() {
      try {
        const url = new URL(input.value, window.location.href);
        if (!['http:', 'https:'].includes(url.protocol) ||
            url.origin !== window.location.origin) {
          throw new Error('Enter an HTTP(S) URL on this page’s origin.');
        }

        let matched = false;
        let rawId = null;
        if (pattern) {
          const match = pattern.exec(url.href);
          matched = match !== null;
          if (match) rawId = match.pathname.groups.id ?? null;
        } else {
          const match = fallback.exec(url.pathname);
          matched = match !== null;
          if (match) rawId = match[1] ?? null;
        }

        let decodedId = null;
        let decodeError = null;
        if (rawId !== null) {
          try {
            decodedId = decodeURIComponent(rawId);
          } catch (error) {
            decodeError = 'The captured ID is not valid percent-encoded UTF-8.';
          }
        }

        const views = url.searchParams.getAll('view');
        const queryRulePasses = views.length === 1 && views[0] === 'full';

        result.textContent = JSON.stringify({
          matcher: pattern ? 'URLPattern' : 'limited fallback',
          parsedHref: url.href,
          parsedPathname: url.pathname,
          parsedSearch: url.search,
          pathnameMatched: matched,
          rawId,
          decodedId,
          decodeError,
          views,
          tags: url.searchParams.getAll('tag'),
          queryRulePasses,
          routeSelected: matched && decodeError === null && queryRulePasses
        }, null, 2);
      } catch (error) {
        result.textContent = `Cannot inspect URL: ${error.message}`;
      }
    }

    form.addEventListener('submit', (event) => {
      event.preventDefault();
      inspect();
    });
    inspect();
  </script>
</body>
</html>

The fallback deliberately covers only this ASCII route shape. It is not a general URLPattern polyfill, and you should not assume it reproduces every URLPattern behavior. If your application has more patterns, test the fallback against the same route cases or use a compatibility solution appropriate to your supported browsers.

Try encoded paths and query strings

Run each of these through the page and compare parsedPathname, pathnameMatched, and routeSelected:

  • /products?view=full: tests the optional segment when no ID is present.
  • /products/42?view=compact: tests a pathname match that fails the separate query rule.
  • /products/a%2Fb?view=full: tests an encoded slash. Compare rawId with decodedId; do not assume the decoded value is still a single safe path segment.
  • /products/%2e%2e/admin?view=full: tests an encoded dot segment. URL parsing can resolve the dot segment before matching, so inspect the parsed pathname rather than judging the input text alone.
  • /products/42?view=full&view=full: tests duplicate query parameters. This page rejects them because its rule requires exactly one value.
  • /products/42?view=full&tag=red+blue&tag=green%2Bwhite: tests query decoding. URLSearchParams interprets + as a space in query values, while %2B represents a literal plus.
  • /products/%ZZ?view=full: tests error handling when a captured ID cannot be decoded with decodeURIComponent.

The query rule is intentionally strict for demonstration. An application could instead allow an absent view, choose a default, or reject unknown parameters. Decide explicitly what duplicate and empty values mean; getAll() makes duplicates visible.

Advertisement

Browser support and router integration

URLPattern support depends on the browser and version. Current MDN documentation and browser compatibility data were not available for review here, so this article cannot verify support at publication time. Before deployment, check MDN's URLPattern documentation and compatibility table for your target browsers, then run this page in those environments. The feature detection in the example selects a fallback when URLPattern is unavailable or the pattern cannot be constructed; it does not establish complete compatibility.

URLPattern can be one piece of a client-side router: it can identify a pathname and extract parameters. An application router may also need to handle navigation history, links, nested layouts, rendering, loading, errors, and server configuration for direct visits. Replacing a router with a pattern matcher does not provide those behaviors automatically.

A client-side match also does not grant access to a product or any other resource. The server must authenticate and authorize each protected request. Validate identifiers at the relevant boundary, and avoid decoding a value and blindly inserting it into another URL or filesystem path.

Common Mistakes

  • Matching the visible input instead of the parsed URL. Dot segments and other parsing behavior can change what is matched. Inspect url.pathname when debugging.
  • Treating query parameters as path parameters. This example's pathname pattern does not require view=full; JavaScript checks that separately.
  • Decoding without an error path. Malformed percent escapes can make decodeURIComponent throw. Decoding can also introduce characters your application does not permit in an identifier.
  • Assuming the fallback is a full polyfill. The regular expression is only for this one route and must be checked against your application's cases.
  • Using client-side routing as a security control. Users can bypass client-side checks; protected operations need server-side enforcement.

Best Practices

Keep a small test matrix for every route: missing and present optional segments, trailing slashes, encoded separators, malformed escapes, duplicate parameters, and direct navigation. Run it in the browsers you support and against any fallback implementation.

Define whether captured values are decoded, what characters are valid after decoding, and how repeated query parameters are handled. Keep those rules consistent with the server and any downstream services that consume the values.

Conclusion

Use URLPattern to match URL components, but test the parsed path and query policy separately. A small browser test page can expose assumptions before they become routing bugs—and server-side authorization remains necessary regardless of the match result.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.