日本語

How to Extract Values from a URL with URLPattern in React

​​React​Playwright,TypeScript,URLPattern,useSyncExternalStore

To pull a value such as 42 from /items/42, or the tag 猫 (cat) from /tags/猫, out of a URL path, you can use the browser's built-in URLPattern. If you write a pattern like /items/:id, exec() returns { id: '42' }.

URLPattern is useful in small apps where the view changes based on the URL, such as a product detail page or an article page, but adding a router library would be overkill. Here, I built functions that determine "which screen" and "the values used on that screen" from the URL, and connected them to React rendering.

Note

The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc and then transformed them with esbuild's development build. The only browser I tested was headless Chromium 153, run with Playwright 1.63.0. I did not test Firefox, Safari, server-side rendering, combinations with router libraries such as React Router, or use with a polyfill loaded in the browser.

Browser support

According to the MDN compatibility data, URLPattern is supported in Chrome and Edge from version 95, in Firefox from 142, and in Safari from 26. Node.js supports it from version 24.

The types are included in TypeScript's DOM type definitions. With the test environment's TypeScript 7.0.2, new URLPattern() and the type of the exec() result type-checked without errors using "lib": ["ES2022", "DOM"].

Extracting path values with exec()

You pass URLPattern the parts of the URL to match and the shape to match them against. To match only the path, pass pathname. A segment that starts with :, like :id, is a named group.

ts
const p = new URLPattern({ pathname: '/items/:id' });

p.test('https://example.com/items/3');                  // true
p.exec('https://example.com/items/3')?.pathname.groups; // { id: '3' }

exec() returns null if the pattern does not match, and otherwise returns a result for each part of the URL (MDN: exec()). Path values are in pathname.groups. Here are the results from several URLs I tried in Chromium in the test environment:

URL matched pathname.groups
https://example.com/items/3 { id: '3' }
https://example.com/items/3?tab=a#x { id: '3' }
https://example.com/items/3/ No match (null)
https://example.com/items/ No match (null)
https://example.com/items/猫 { id: '%E7%8C%AB' }

There are three things to watch out for with the extracted values.

First, the value is always a string. Even when I restricted it to digits with /items/:id(\\d+), typeof was 'string'. If you need a number, convert it with Number().

Second, characters such as Japanese are returned still percent-encoded. Passing /items/猫 returned %E7%8C%AB. When you display the value, convert it back to 猫 with decodeURIComponent().

Third, watch out for trailing slashes. /items/:id does not match /items/3/. As described in the MDN URL Pattern API documentation, adding {/}? at the end makes the pattern match with or without the slash. In the test environment, /items/:id{/}? returned { id: '3' } for both /items/3 and /items/3/.

Narrowing matches with pattern syntax

Writing a regular expression in ( ) after a group narrows the values that match (MDN: pattern syntax). Because the regular expression is written inside a string, \d is written as \\d in code. Here are the results from testing in the test environment:

Pattern Path tested Result
/items/:id(\\d+) /items/3 Match
/items/:id(\\d+) /items/abc No match
/blog/:year/:month? /blog/2026 { year: '2026' }
/blog/:year/:month? /blog/2026/11 { year: '2026', month: '11' }
/files/:path+ /files/a/b { path: 'a/b' }
/docs/* /docs/a/b/c { '0': 'a/b/c' }

A group followed by ? matches even when it is absent. For /blog/2026, the result did not contain a month value (reading groups.month gives undefined). Adding + captures the rest of the path, including any /, as one value. * also captures the rest of the path, but since it has no name, its key is '0'.

Matching is case-sensitive. /items/:id did not match /Items/3. If you want case-insensitive matching, use the ignoreCase option of the constructor. With new URLPattern({ pathname: '/items/:id' }, { ignoreCase: true }), /Items/3 matched.

Read query strings with URLSearchParams

Query strings such as ?q=cat can also be written in URLPattern's search. However, I tried { pathname: '/search', search: 'q=:q' } and got the following results:

URL matched search.groups
https://example.com/search?q=cat { q: 'cat' }
https://example.com/search?q=cat&page=2 { q: 'cat&page=2' }
https://example.com/search?page=2&q=cat No match (null)

According to MDN's description of the characters a group matches, a group matches every character except / only in pathname. In search, a group matches every character. As a result, everything after q=, including the &, ends up in q. Query parameters have no fixed order, so they are also not suited to matching with a search pattern.

For reliable reading of query values, use URLSearchParams, for example new URL(href).searchParams.get('page'). This gave '2' for page and 'cat' for q, regardless of order.

Build a function that decides the screen and values from a URL

From here on, I use the approach in React. First, I create matchRoute, a function that takes a URL string and returns "which screen" and "the values used on that screen." It is a plain function with nothing to do with React.

Diagram showing the flow: the URL path is read with URLPattern and the query with URLSearchParams; the tag is decoded with decodeURIComponent back to the cat tag, and page is converted with Number to 2, and both are combined into the return value of matchRoute (the labels in the image are in Japanese)
Extracting the tag and page number from /tags/%E7%8C%AB?page=2
ts
// routes.ts
// Extract which screen and the values used on it from the URL.
const itemPattern = new URLPattern({ pathname: '/items/:id(\\d+){/}?' });
const tagPattern = new URLPattern({ pathname: '/tags/:tag{/}?' });

export type Route =
  | { name: 'item'; id: number }
  | { name: 'tag'; tag: string; page: number }
  | { name: 'notFound' };

export function matchRoute(href: string): Route {
  const item = itemPattern.exec(href);
  if (item) {
    return { name: 'item', id: Number(item.pathname.groups.id) };
  }

  const tag = tagPattern.exec(href);
  if (tag) {
    const raw = tag.pathname.groups.tag ?? '';
    let decoded: string;
    try {
      decoded = decodeURIComponent(raw);
    } catch {
      return { name: 'notFound' }; // a broken value such as %E7%8C
    }
    // Read the query with URLSearchParams, not URLPattern
    const page = Number(new URL(href).searchParams.get('page') ?? '1');
    return { name: 'tag', tag: decoded, page: Number.isInteger(page) && page > 0 ? page : 1 };
  }

  return { name: 'notFound' };
}

The patterns are created once, at the top of the file. Creating them inside a component would mean recreating them on every render.

The type of groups from exec() is an object whose values are string | undefined. As it stands, the type cannot guarantee that id is present. So I made the function return a type Route that holds the values each screen needs. The caller branches on route.name, and then can use route.id as a number.

decodeURIComponent() throws an exception when given a value that is cut off partway through, such as %E7%8C. In the test environment, this threw URIError: URI malformed. To prevent an exception during rendering, I catch it with try and treat the page as not found.

Read the current URL in React and switch views

I read the current URL as a React value with useSyncExternalStore. The browser's back and forward buttons fire a popstate event, so I subscribe to it.

ts
// useLocationHref.ts
import { useSyncExternalStore } from 'react';

const NAVIGATE = 'app:navigate';

function subscribe(onChange: () => void) {
  window.addEventListener('popstate', onChange);
  window.addEventListener(NAVIGATE, onChange);
  return () => {
    window.removeEventListener('popstate', onChange);
    window.removeEventListener(NAVIGATE, onChange);
  };
}

// Read the current URL (location.href) as a React value
export function useLocationHref(): string {
  return useSyncExternalStore(subscribe, () => window.location.href);
}

export function navigate(to: string) {
  history.pushState(null, '', to);
  // pushState does not fire popstate, so notify manually
  window.dispatchEvent(new Event(NAVIGATE));
}

When a link is clicked, history.pushState() changes only the URL. As described in the MDN popstate documentation, calling pushState() does not fire popstate. So the code sends its own event named app:navigate. In the test environment, when I removed the dispatchEvent line and clicked the "Item 42" link, the address bar showed /items/42/, but the screen still showed the details for "Item 3."

In the component, I pass the URL that was read to matchRoute and choose what to display.

tsx
// App.tsx
import type { MouseEvent, ReactNode } from 'react';
import { matchRoute } from './routes';
import { navigate, useLocationHref } from './useLocationHref';

function Link({ to, children }: { to: string; children: ReactNode }) {
  const onClick = (e: MouseEvent<HTMLAnchorElement>) => {
    if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    e.preventDefault();
    navigate(to);
  };
  return <a href={to} onClick={onClick}>{children}</a>;
}

export function App() {
  const href = useLocationHref();
  const route = matchRoute(href);

  return (
    <main>
      <nav>
        <Link to="/items/3">商品3</Link> <Link to="/items/42/">商品42</Link>{' '}
        <Link to="/tags/%E7%8C%AB?page=2">タグ「猫」の2ページ目</Link>{' '}
        <Link to="/items/abc">商品abc</Link>
      </nav>
      <section>
        {route.name === 'item' && <h1>商品 {route.id} の詳細</h1>}
        {route.name === 'tag' && <h1>タグ「{route.tag}」の {route.page} ページ目</h1>}
        {route.name === 'notFound' && <h1>ページが見つかりません</h1>}
      </section>
    </main>
  );
}

Link does not call preventDefault() for clicks with a button other than the left one, or for clicks made while holding Ctrl or another modifier key. In those cases, it leaves the browser's normal behavior in place.

The test server returned the same HTML for every path that was requested. Here is what Playwright showed when I opened each URL directly. (The test code also displayed the type of id for confirmation.)

URL opened Display
/items/3 Item 3 details (id is number)
/items/3/ Item 3 details
/items/abc Page not found
/tags/%E7%8C%AB?page=2 Tag 猫, page 2
/tags/猫 Tag 猫, page 1
/tags/%E7%8C%AB?page=abc Tag 猫, page 1
/tags/%E7%8C Page not found
/Items/3 Page not found

I opened /items/3, then moved through links to "Tag 猫, page 2" and "Item 42." Then I went back twice and forward once in the history using Playwright. At every step, the display matched the URL. The page was loaded from the server zero times during this sequence.

Check before loading when URLPattern is missing

In browsers that do not support it, the name URLPattern does not exist at all. For testing, I removed window.URLPattern before the page opened to simulate such a browser.

At first, I imported App at the top of main.tsx and checked 'URLPattern' in globalThis before rendering. With this approach, nothing appeared on screen. The browser console showed the error URLPattern is not defined. This happened because new URLPattern() runs as soon as routes.ts is loaded, so the check never got a chance to run.

So I changed the code to check first and only then load App.

tsx
// main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root')!);

if ('URLPattern' in globalThis) {
  // routes.ts calls new URLPattern() as soon as it is loaded, so load it only after the check
  import('./App').then(({ App }) => {
    root.render(<StrictMode><App /></StrictMode>);
  });
} else {
  root.render(<p>このブラウザは URLPattern に対応していません</p>);
}

With this version, the page with URLPattern removed showed the fallback message in the code above, which says that the browser does not support URLPattern. The MDN URLPattern page also introduces a polyfill for URLPattern.

Test matchRoute on Node.js 22

matchRoute has nothing to do with React, so you can also test it with the Node.js test runner. However, Node.js 22 does not have URLPattern. In the test environment, typeof URLPattern was 'undefined', and loading routes.ts threw ReferenceError: URLPattern is not defined.

For the tests, I loaded urlpattern-polyfill 10.1.0 first. By writing import 'urlpattern-polyfill', this polyfill makes URLPattern available.

ts
// routes.test.ts
import 'urlpattern-polyfill'; // Node.js 22 does not have URLPattern
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { matchRoute } from '../src/routes';

test('商品の id を数値で取り出す', () => {
  assert.deepEqual(matchRoute('https://example.com/items/3/'), { name: 'item', id: 3 });
});

test('タグを日本語に戻し、ページ番号をクエリから読む', () => {
  assert.deepEqual(matchRoute('https://example.com/tags/%E7%8C%AB?page=2'), { name: 'tag', tag: '猫', page: 2 });
});

test('数字でない id は見つからない扱い', () => {
  assert.deepEqual(matchRoute('https://example.com/items/abc'), { name: 'notFound' });
});

I bundled everything into a single file with esbuild and ran it with node --test. All three tests passed.

text
$ npx esbuild test/routes.test.ts --bundle --platform=node --format=esm --outfile=dist/routes.test.mjs && node --test dist/routes.test.mjs
ok 1 - 商品の id を数値で取り出す
ok 2 - タグを日本語に戻し、ページ番号をクエリから読む
ok 3 - 数字でない id は見つからない扱い
# tests 3
# pass 3
# fail 0

The type check had one problem. Both the polyfill's type definitions and TypeScript's DOM type definitions declare URLPattern, so tsc reported errors such as Duplicate identifier 'URLPattern'. Adding "skipLibCheck": true to the test tsconfig made the errors go away.

json
{ "extends": "./tsconfig.json", "compilerOptions": { "types": ["node"], "skipLibCheck": true }, "include": ["src", "test"] }

​Posted by 86