{"id":16258,"library":"urlpattern-polyfill","title":"URLPattern Polyfill","description":"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.","status":"active","version":"10.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/kenchris/urlpattern-polyfill","tags":["javascript","typescript"],"install":[{"cmd":"npm install urlpattern-polyfill","lang":"bash","label":"npm"},{"cmd":"yarn add urlpattern-polyfill","lang":"bash","label":"yarn"},{"cmd":"pnpm add urlpattern-polyfill","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"import URLPattern from 'urlpattern-polyfill';","symbol":"URLPattern (global)","correct":"if (!globalThis.URLPattern) { await import(\"urlpattern-polyfill\"); }"},{"note":"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.","wrong":"import * as URLPattern from 'urlpattern-polyfill';","symbol":"URLPattern (named export)","correct":"import { URLPattern } from 'urlpattern-polyfill';"},{"note":"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.","wrong":"const URLPattern = require('urlpattern-polyfill');","symbol":"URLPattern (global, CJS)","correct":"if (!globalThis.URLPattern) { require(\"urlpattern-polyfill\"); }"},{"note":"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.","wrong":"const URLPattern = require('urlpattern-polyfill').URLPattern;","symbol":"URLPattern (destructured, CJS)","correct":"const { URLPattern } = require('urlpattern-polyfill');"}],"quickstart":{"code":"// First, ensure the polyfill is loaded if native URLPattern is absent.\n// @ts-ignore: Property 'URLPattern' does not exist on type 'typeof globalThis'.\nif (!globalThis.URLPattern) {\n  // Using dynamic import for conditional loading, works in ESM contexts.\n  await import(\"urlpattern-polyfill\");\n}\n\n// Basic example: Matching a simple path with a named group.\n// Ensure URLPattern is available after the conditional import.\nlet p1 = new URLPattern({ pathname: '/foo/:name' });\nlet r1 = p1.exec('https://example.com/foo/bar');\nconsole.log('--- Basic Example ---');\nconsole.log(`Input: ${r1?.pathname?.input}`); // Expected: \"/foo/bar\"\nconsole.log(`Named group 'name': ${r1?.pathname?.groups?.name}`); // Expected: \"bar\"\nconsole.log('\\n');\n\n// More advanced example: Matching specific file types with a base URL.\nconst p2 = new URLPattern({\n  pathname: '/*.:filetype(jpg|png)',\n  baseURL: 'https://example.com' // Explicit baseURL for clarity, mimicking self.location\n});\n\nconst urlsToTest = [\n  'https://example.com/images/photo.jpg',\n  'https://example.com/docs/report.pdf',\n  'https://example.com/assets/icon.png',\n  'https://anothersite.com/image.jpg' // This will not match due to baseURL\n];\n\nconsole.log('--- Filetype Matching Example ---');\nurlsToTest.forEach(url => {\n  const r2 = p2.exec(url);\n\n  if (r2) {\n    console.log(`Match for ${url}:`);\n    console.log(`  Filetype: ${r2.pathname.groups['filetype']}`);\n    if (r2.pathname.groups['filetype'] === 'jpg') {\n      console.log('  -> Process as JPG');\n    } else if (r2.pathname.groups['filetype'] === 'png') {\n      console.log('  -> Process as PNG');\n    } else {\n      console.log('  -> Unknown image type');\n    }\n  } else {\n    console.log(`No match for ${url}`);\n  }\n});","lang":"typescript","description":"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."},"warnings":[{"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'.`","message":"When 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.","severity":"gotcha","affected_versions":">=1.0"},{"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.","message":"While `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.","severity":"breaking","affected_versions":"*"},{"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;`","message":"The 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.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"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.","cause":"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.","error":"Property 'URLPattern' does not exist on type 'typeof globalThis'."}],"ecosystem":"npm"}