Build Your Own Router with URLPattern()

https://news.ycombinator.com/rss Hits: 5
Summary

Build Your Own Router Published 2025-11-11, About 8 minute read. URLPattern just became available in all browsers: So I wanted to dig into what it would take to make a simple SPA router with vanilla JavaScript and browser APIs. We should be able to make a component that takes in a router configuration and renders the appropriate component determined by the browser URL. What does URLPattern() Do? 馃搸 Conditionally rendering components is not the difficult part with routers. The difficult part is accurately testing the browser URL to determine which component should render. And not only that, we have to be able to capture dynamic parts of routes (think something like /posts/{post_id}.) So, without further ado, here are some examples showing how to test if a route URL matches a pattern! You can then use this mechanism to create a router with easily configured paths. You might be surprised by the fourth example above. There is a distinction between /cat and /cat/. So to handle this, you can make the pattern optionally include an ending forward slash in a group with curly brackets and mark it optional with ?: Yet another surprise! You may expect that you can accept more after /cat/. To do that, include a wildcard asterisk: Where do we start? 馃搸 I'm going to use an array of config objects that tie a URL route to specific web components. It's very similar to how you can create routers with vue-router. The order of the config objects matters. We'll be testing each pattern one by one, and if we find a match, we'll render that web component. How do we do the rendering? That would be the job of the web component we're placing all this logic in. The component will look at the current window URL, test that against all the router configs that we set up with URLPattern, and create and render the appropriate web component as a child. Some frameworks call this router the "outlet" component. Of course, you will need to have the web components my-home, my-posts, and my-about registered a...

First seen: 2025-11-29 14:44

Last seen: 2025-11-29 18:44