Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Route URLs with the global URLPattern

Match a Node HTTP pathname with URLPattern, capture its numeric ID, and dispatch the request using the match result.

A small Node server splits the request path to get a job ID. Then /jobs/42/logs falls into the same branch as /jobs/42 because both paths have the ID in the same slot. A URL pattern can check the shape and extract the ID in one call.

Match the URL and read the group

Node 24 exposes URLPattern globally as an experimental API. Run this example on Node 24 or later. Make the pattern once and use a named group for the segment you want. Pass an absolute URL or a relative target with a base URL.

const origin = 'http://localhost'
const jobRoute = new URLPattern({ pathname: '/jobs/:id(\\d+)' })

for (const target of ['/jobs/42?view=detail', '/jobs/42/logs', '/jobs/new']) {
  const match = jobRoute.exec(target, origin)
  console.log(target, match?.pathname.groups.id ?? 'no match')
}

The first target returns the string 42, and the other two print no match.

The JavaScript string needs two backslashes to put one backslash in the pattern. The :id name becomes a key in pathname.groups. The group constraint accepts decimal digits. The query string sits in a different URL component, so ?view=detail does not change this pathname match.

The URL Pattern Standard defines matching by URL component. With the object form above, you constrain the pathname and leave the other components open. If the caller supplies an absolute URL and the host matters, check the origin separately. A hostname constraint alone still allows other schemes or ports.

Dispatch after the match

In a Node HTTP handler, supply the request target as the first argument and a known base as the second. Branch on the HTTP method in the handler. exec() returns null for a target that fails the URL pattern, which gives you a branch for another route or a 404.

The captured ID is text. Keep it as text if your database represents identifiers that way. If you need a JavaScript number, convert it and check Number.isSafeInteger() before passing it to the query. The route accepts digit sequences longer than a safe integer.

A pattern picks the handler. The handler still needs to check that the job exists and that the caller has access. If you support a Node release without the global, keep your current matcher or add a compatible implementation for that runtime.