Open Source: Fast URL router for workers (JS & TypeScript)

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). :smile:

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!

5 Likes

Awesome! Thanks for sharing!

1 Like

Very elegant, fast and compact! Superb! Love the TypeScript support too!

Thanks for sharing :heart_eyes:

1 Like