What is the URLPattern API?
The URLPattern API is a standardized browser API that lets you match URLs against patterns with named groups, wildcards, and regex support. Part of Baseline since September 2025, it eliminates the need for complex regular expressions or third-party routing libraries for common URL matching tasks.
As part of our modern JavaScript development approach, URLPattern represents the evolution of browser capabilities--bringing native URL handling to web applications without external dependencies. This native solution is particularly valuable for SEO optimization where clean, predictable URLs improve search rankings and user experience.
The Problem Before URLPattern
Traditionally, developers had to parse URLs using the URL constructor, then apply custom regex patterns for routing logic. This approach was error-prone, required deep regex knowledge, and varied across codebases. URLPattern brings a consistent, readable syntax to URL matching.
How URLPattern Solves This
With URLPattern, you define patterns using a familiar syntax inspired by path-to-regexp libraries. The API understands URL structure--protocol, hostname, pathname, search, and hash--and provides named parameters automatically extracted from matches. No dependencies, no learning curve for regex, just clean, maintainable code suitable for AI-powered automation workflows.
Creating Patterns: Constructor Options
URLPattern offers two ways to create patterns--using a structured object or a simple string--giving you flexibility based on your use case.
Object-Based Constructor
The object syntax lets you specify patterns for each URL component separately. This is ideal for complex matching rules involving multiple URL parts:
const pattern = new URLPattern({
pathname: '/products/:category/:id',
hostname: '*.example.com',
search: 'sort=:sortOrder'
});
pattern.test('https://api.example.com/products/electronics/123?sort=price');
// true - matches all components
String-Based Constructor
For simpler pathname matching, the string syntax is concise and readable:
// Absolute URL pattern
const apiPattern = new URLPattern('/api/v:version/*');
// Relative pattern with baseURL
const userPattern = new URLPattern('/users/:id', 'https://example.com');
Constructor Options
The optional ignoreCase parameter enables case-insensitive matching:
const pattern = new URLPattern(
{ pathname: '/products/:id' },
{ ignoreCase: true }
);
URLPattern supports multiple pattern types for flexible matching
Literal Matching
Fixed text that matches exactly, perfect for static route segments like '/products' or '/about'
Wildcards
The `*` wildcard matches any characters--in pathname it matches everything except '/', enabling flexible path matching
Named Groups
`:name` syntax extracts parameters by name, making code more readable than positional regex capture groups
Regex Groups
Embed regular expressions like `(:id\\d+)` to constrain matches to specific patterns like numeric IDs
Matching and Extraction Methods
URLPattern provides two methods for working with patterns--test() for simple boolean checks and exec() for full parameter extraction.
test() Method
Use test() for conditional logic when you only need to know if a URL matches:
const pattern = new URLPattern('/products/:id');
pattern.test('https://example.com/products/123'); // true
pattern.test('https://example.com/users/456'); // false
pattern.test('https://example.com/products/'); // false
exec() Method
Use exec() when you need to extract parameter values. The result contains groups for each matched URL component:
const pattern = new URLPattern('/books/:category/:id');
const result = pattern.exec('https://example.com/books/fiction/789');
// result.pathname.groups = { category: 'fiction', id: '789' }
const { category, id } = result.pathname.groups;
console.log(`Loading ${id} from ${category}`);
Each URL component (pathname, hostname, search, hash) has its own groups object with the extracted named parameters.
Practical Use Cases
URLPattern excels in scenarios where modern web applications need to work with URLs dynamically.
Client-Side Routing
For custom routing logic or middleware that needs URL pattern matching without framework dependencies:
const routes = [
new URLPattern('/products/:category/:id'),
new URLPattern('/users/:userId/orders/:orderId'),
new URLPattern('/search?q=:query')
];
function handleNavigation(url) {
for (const route of routes) {
const match = route.exec(url);
if (match) {
return { handler: 'loadPage', params: match.pathname.groups };
}
}
return { handler: 'notFound' };
}
Service Worker Request Interception
URLPattern is ideal for matching fetch requests in service workers and applying different caching strategies. This is particularly valuable when building progressive web applications that need offline capabilities:
const IMAGE_PATTERN = new URLPattern({ pathname: '/images/*' });
const API_PATTERN = new URLPattern({ pathname: '/api/*' });
self.addEventListener('fetch', (event) => {
if (IMAGE_PATTERN.test(event.request.url)) {
event.respondWith(cacheFirst(event.request));
} else if (API_PATTERN.test(event.request.url)) {
event.respondWith(networkFirst(event.request));
}
});
Form Validation
Validate that user-provided URLs match expected patterns:
const youtubePattern = new URLPattern(
'https://youtu.be/:videoId',
'https://www.youtube.com'
);
function isValidYoutubeLink(input) {
return youtubePattern.test(input);
}
Browser Support and Compatibility
URLPattern became part of Baseline in September 2025, meaning it works across all modern browser versions:
- Chrome/Edge: Version 94+
- Firefox: Version 86+
- Safari: Version 16.4+
The API is also available in Web Workers, enabling URL matching in background scripts without DOM access.
For projects needing to support older browsers, a polyfill is available, though adoption of modern browsers makes this increasingly unnecessary.
Best Practices
Pattern Design
- Use the object syntax for complex patterns involving multiple URL components--it improves readability and maintainability
- Use named groups for all extracted parameters instead of regex capture groups
- Keep patterns focused--specific patterns are easier to debug and reason about
Performance
- Reuse patterns rather than creating new ones for each match
- Pre-compile common patterns at module load time for frequently-matched routes
Error Handling
- Invalid patterns throw
TypeErrorduring construction - Non-matching URLs return
falsefromtest()andnullfromexec() - Always check results before accessing groups
Framework Integration
URLPattern complements rather than replaces framework routing systems. For applications built with Next.js or modern JavaScript frameworks, URLPattern is valuable for:
- Custom routing logic beyond framework capabilities
- Service worker request handling
- Edge cases where framework routing isn't available
- Building lightweight routing for simple applications that benefit from our web development expertise
Summary
The URLPattern API brings standardized, dependency-free URL matching to modern web development. Its pattern syntax--inspired by path-to-regexp libraries--provides named groups, wildcards, and regex support in a readable format. Whether you're building client-side routing, handling service worker requests, or validating URLs, URLPattern offers a native solution that works across all major browsers.
For developers building with Next.js or modern JavaScript frameworks, URLPattern is a valuable tool for situations requiring custom URL logic beyond framework routing capabilities. Combined with our full-stack development expertise, it enables building sophisticated web applications with clean, maintainable URL handling code.
As browsers continue to expand native capabilities, APIs like URLPattern represent the future of web development--powerful enough to replace complex third-party solutions, yet simple enough to use without additional dependencies. Our AI automation services leverage these modern browser APIs to build intelligent systems that understand and process URL structures automatically.
Sources
- MDN Web Docs - URL Pattern API - Comprehensive official documentation covering pattern syntax, constructors, and usage patterns
- web.dev - URLPattern is now Baseline Newly available - Google's official blog explaining the API's arrival in Baseline 2025 and practical use cases
- MDN - URLPattern() constructor - Detailed constructor documentation with parameters and options