Hey there!
I was unable to find a modern URL router for usage in Cloudflare workers, so I made one and figured other developers might find it useful as well:
Thanks to Cloudflare for using the service worker standard it’s not specific to Cloudflare (though that was the main reason to build it).
Usage is very simple:
const router = new Router()
const user = async ({ request, params }) => {
const response = new Response(`Hello user with id ${params.id}.`)
response.headers.set('x-user-id', params.id)
return response
}
const ping = async () => new Response('pong')
router.get('/user/:id', user)
router.all('/_ping', ping)
addEventListener('fetch', event => {
// Will test event.request against the defined routes
// and use event.respondWith(handler) when a route matches
router.watch(event)
})
For me the main purpose for the router is to work with the current 1 worker per domain limit and keep the code maintainable, while serving multiple projects through a single worker.
Feel free to raise an issue on Github with feedback, I’m planning to release more worker related open-source code in the future.
Cheers!