Registry / http-networking / urlpattern-polyfill

urlpattern-polyfill

JSON →
library10.1.0jsnpmunverified

The `urlpattern-polyfill` package provides a robust and standards-compliant polyfill for the emerging URLPattern Web API, designed to bring powerful URL matching capabilities to environments lacking native support. Currently at version 10.1.0, this project is actively maintained, with releases typically following updates to the URLPattern specification and bug fixes. A key differentiator is its rigorous adherence to the official web platform test suite, ensuring functional parity with native browser implementations. This enables developers to utilize `URLPattern` for complex routing logic in web applications, service workers, and Node.js backend services without concerns about environment fragmentation. The polyfill integrates intelligently, only applying itself to `globalThis` if `URLPattern` is not already defined, preventing conflicts and ensuring efficient resource usage.

npm install urlpattern-polyfill
INSTALL
IMPORT
SIG · URLPATTERN-POLYFIL
U
urlpattern-polyfill
http-networkingjavascriptv10.1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

URLPattern (global)
if (!globalThis.URLPattern) { await import("urlpattern-polyfill"); }
import URLPattern from 'urlpattern-polyfill';
This is the recommended way to load the polyfill in ESM contexts. It has the side effect of making `URLPattern` available on `globalThis` only if it doesn't already exist. Importing a default export is incorrect as there isn't one for this global polyfill use case.
URLPattern (named export)
import { URLPattern } from 'urlpattern-polyfill';
import * as URLPattern from 'urlpattern-polyfill';
Use this named import if you need to explicitly reference the `URLPattern` class from the polyfill (e.g., to replace an existing implementation or avoid global side effects). Importing all as `*` is not the idiomatic way for a single named export.
URLPattern (global, CJS)
if (!globalThis.URLPattern) { require("urlpattern-polyfill"); }
const URLPattern = require('urlpattern-polyfill');
In CommonJS, `require` is used for its side effect of adding `URLPattern` to `globalThis` when the environment doesn't natively support it. Assigning the direct return of `require` to a variable is generally incorrect for the global polyfill use case.
URLPattern (destructured, CJS)
const { URLPattern } = require('urlpattern-polyfill');
const URLPattern = require('urlpattern-polyfill').URLPattern;
This CommonJS pattern allows explicit retrieval of the `URLPattern` class, similar to its ESM counterpart, for environments where direct assignment or explicit reference is preferred. While the latter `.` notation technically works, destructuring is idiomatic.

Demonstrates conditional loading of the polyfill, followed by basic URL matching with named groups and an advanced example of matching specific file types based on a base URL.

// First, ensure the polyfill is loaded if native URLPattern is absent. // @ts-ignore: Property 'URLPattern' does not exist on type 'typeof globalThis'. if (!globalThis.URLPattern) { // Using dynamic import for conditional loading, works in ESM contexts. await import("urlpattern-polyfill"); } // Basic example: Matching a simple path with a named group. // Ensure URLPattern is available after the conditional import. let p1 = new URLPattern({ pathname: '/foo/:name' }); let r1 = p1.exec('https://example.com/foo/bar'); console.log('--- Basic Example ---'); console.log(`Input: ${r1?.pathname?.input}`); // Expected: "/foo/bar" console.log(`Named group 'name': ${r1?.pathname?.groups?.name}`); // Expected: "bar" console.log('\n'); // More advanced example: Matching specific file types with a base URL. const p2 = new URLPattern({ pathname: '/*.:filetype(jpg|png)', baseURL: 'https://example.com' // Explicit baseURL for clarity, mimicking self.location }); const urlsToTest = [ 'https://example.com/images/photo.jpg', 'https://example.com/docs/report.pdf', 'https://example.com/assets/icon.png', 'https://anothersite.com/image.jpg' // This will not match due to baseURL ]; console.log('--- Filetype Matching Example ---'); urlsToTest.forEach(url => { const r2 = p2.exec(url); if (r2) { console.log(`Match for ${url}:`); console.log(` Filetype: ${r2.pathname.groups['filetype']}`); if (r2.pathname.groups['filetype'] === 'jpg') { console.log(' -> Process as JPG'); } else if (r2.pathname.groups['filetype'] === 'png') { console.log(' -> Process as PNG'); } else { console.log(' -> Unknown image type'); } } else { console.log(`No match for ${url}`); } });
Debug
Known issues
gotchaWhen conditionally loading the polyfill (`if (!globalThis.URLPattern) { await import("urlpattern-polyfill"); }`), TypeScript might flag `globalThis.URLPattern` as an unknown property because the polyfill hasn't loaded yet and the type definitions aren't globally applied at compile-time.
fix
Use a `//@ts-ignore` directive on the line referencing `globalThis.URLPattern` within the conditional check, as suggested in the package's README. Example: `// @ts-ignore: Property 'URLPattern' does not exist on type 'typeof globalThis'.`
affects: >=1.0
breakingWhile `urlpattern-polyfill` aims for spec compliance, relying on polyfills for core web platform features always carries a risk of subtle behavioral differences or performance implications compared to native implementations, especially as the standard evolves. This is inherent to polyfilling a rapidly developing specification.
fix
Always test applications thoroughly in target environments with and without the polyfill, and consider the implications of depending on a polyfill versus native support when designing systems. Keep the polyfill updated to the latest version to track specification changes.
affects: *
gotchaThe polyfill is designed to load conditionally, only activating if `globalThis.URLPattern` is undefined. If another polyfill has already been loaded, or if a browser's native implementation is present but potentially buggy or non-compliant, this polyfill will not overwrite it by default.
fix
If you explicitly need to replace an existing (native or polyfilled) `URLPattern` implementation, import the `URLPattern` class directly from the package and assign it to `globalThis.URLPattern`. Example: `import { URLPattern } from "urlpattern-polyfill"; globalThis.URLPattern = URLPattern;`
affects: >=1.0
Errors
Common errors & fixes
Property 'URLPattern' does not exist on type 'typeof globalThis'.
TypeScript compiler cannot find the `URLPattern` type on `globalThis` before the polyfill's types are globally applied, particularly within conditional `if` statements that check for its existence.
fix
Add `// @ts-ignore: Property 'URLPattern' does not exist on type 'typeof globalThis'.` above the line where `globalThis.URLPattern` is accessed for the conditional check.
Upgrade
Version history
10.1.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
15 hits · last 30 days
node
14
OpenAI (training)
1
Resources
urlpattern-polyfill — npm install urlpattern-polyfill · libregistry