{"id":20563863,"url":"https://github.com/worker-tools/router","last_synced_at":"2025-04-14T15:03:04.310Z","repository":{"id":56899863,"uuid":"325918664","full_name":"worker-tools/router","owner":"worker-tools","description":"A router for Worker Runtimes such and Cloudflare Workers or Service Workers.","archived":false,"fork":false,"pushed_at":"2023-11-25T02:37:14.000Z","size":71,"stargazers_count":32,"open_issues_count":4,"forks_count":5,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-09T09:18:02.635Z","etag":null,"topics":["cloudflare","cloudflare-workers","http","router","routing"],"latest_commit_sha":null,"homepage":"https://workers.tools/router","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/worker-tools.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-01T04:50:21.000Z","updated_at":"2025-04-04T16:16:00.000Z","dependencies_parsed_at":"2024-06-21T04:17:32.637Z","dependency_job_id":"631bbb1b-25cc-4b1d-89fd-027966e29f1a","html_url":"https://github.com/worker-tools/router","commit_stats":{"total_commits":80,"total_committers":1,"mean_commits":80.0,"dds":0.0,"last_synced_commit":"5e5a96b33178567c535f99644522e562f1a55947"},"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/worker-tools%2Frouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/worker-tools%2Frouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/worker-tools%2Frouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/worker-tools%2Frouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/worker-tools","download_url":"https://codeload.github.com/worker-tools/router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248903950,"owners_count":21180830,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cloudflare","cloudflare-workers","http","router","routing"],"created_at":"2024-11-16T04:21:55.562Z","updated_at":"2025-04-14T15:03:04.275Z","avatar_url":"https://github.com/worker-tools.png","language":"TypeScript","readme":"# Worker Router\nA router for [Worker Runtimes](https://workers.js.org) such as Cloudflare Workers and Service Workers.\n\nThis router is inspired by previous work, specifically `tiny-request-router` and `itty-router`, but it\nimproves on them by providing better support for middleware, type inference, nested routing, and broader URL matching for use in service workers.\n\n## 🆓 Type Inference\nThe goal of Worker Router is to *infer types based on usage* so that **no explicit typing** is required for standard use cases.\nThis allows even JavaScript users to benefit from inline documentation and API discoverability. For example,\n\n```js\nconst router = new WorkersRouter()\n  .get('/about', basics(), (req, { userAgent }) =\u003e ok())\n  .get('/login', unsignedCookies(), (req, { cookies }) =\u003e ok())\n```\n\nIn this example your editor can infer the types and documentation for\n  - `userAgent`, provided by the `basics` middleware \n  - `cookies`, provided by the `unsignedCookies` middleware \n\n\n## 🔋 Functional Middleware\nWorker Router [middlewares](https://workers.tools/middleware) are *just function* that add properties to a generic context object. \nAs such, they can be *mixed and matched* using standard tools from functional programming.\n\nFor convenience, this module provides a `combine` utility to combine multiple middlewares into one.\n\n```js\nconst myReusableMW = combine(\n  basics(), \n  signedCookies({ secret: 'password123' }), \n  cookieSession({ user: '' })\n);\n\nconst router = new WorkersRouter()\n  .get('/', myReusableMW, () =\u003e ok())\n  .post('/', combine(myReusableMW, bodyParser()), () =\u003e ok())\n```\n\nNote that type inference is maintained when combining middleware!\n\n\n## 🪆 Nested Routing\nWorker Router supports delegating entire sub routes to another router:\n\n```js\nconst itemRouter = new WorkerRouter()\n  .get('/', (req, { params }) =\u003e ok(`Matched \"/item/`))\n  .get('/:id', (req, { params }) =\u003e ok(`Matched \"/item/${params.id}`))\n\nconst router = new WorkersRouter()\n  .get('/', () =\u003e ok('Main Page'))\n  .use('/item*', itemRouter)\n```\n\n\n## ⚙️ Ready for Service... Worker\nInternally, this router uses [`URLPattern`](https://web.dev/urlpattern/) for routing, which allows it match URLs in the broadest sense. \nFor example, the following router, meant to be used in a Service Worker, can handle internal requests as well as intercept calls to external resources:\n\n```js\n// file: \"sw.js\"\nconst router = new WorkersRouter()\n  .get('/', () =\u003e ok('Main Page'))\n  .get('/about', () =\u003e ok('About Page'))\n  .external('https://plausible.io/api/*', req =\u003e {\n    // intercepted\n  })\n```\n\n## 💥 Error Handling Without Even Trying\nWorker Router has first class support for error handling. Its main purpose is to let you write your handlers without having to wrap everything inside a massive `try {} catch` block. Instead, you can define special recover routes that get invoked when something goes wrong. \n\n```js\nconst router = new WorkersRouter()\n  .get('/', () =\u003e ok('Main Page'))\n  .get('/about', () =\u003e { throw Error('bang') })\n  .recover('*', (req, { error, response }) =\u003e \n    new Response(`Something went wrong: ${error.message}`, response)\n  );\n```\n\n## ✅ Works with Workers\nWorker Router comes with out of the box support for a variety of Worker Runtimes:\n\nTo use it in an environment that provides a global `fetch` event, use\n\n```js\nself.addEventListener('fetch', router)\n```\n\n(This works because the router implements the [`EventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventListener) interface)\n\nTo use it with Cloudflare's module workers, use\n\n```js\nexport default router\n```\n\n(This works because the router implements a `fetch` method with compatible interface)\n\nTo use it with Deno/Deploy's `serve` function, use\n\n```js\nserve(router.serveCallback)\n```\n\n\u003c!-- While Worker Router is influenced by earlier work, it is __not in the tradition__ of express, koa and other modify-in-place routers, save for aspects of its high level  API.\nAt it's core, Worker Router is a function of `(req: Request, ctx: Context) =\u003e Promise\u003cResponse\u003e`. In this model, \nmiddleware is another function that *adds* properties to the context, which is fully tracked by the type system. Conversely, middleware that is not applied is also absent and not polluting the context object. --\u003e\n\n\u003cbr/\u003e\n\n--------\n\n\u003cbr/\u003e\n\n\u003cp align=\"center\"\u003e\u003ca href=\"https://workers.tools\"\u003e\u003cimg src=\"https://workers.tools/assets/img/logo.svg\" width=\"100\" height=\"100\" /\u003e\u003c/a\u003e\n\u003cp align=\"center\"\u003eThis module is part of the Worker Tools collection\u003cbr/\u003e⁕\n\n[Worker Tools](https://workers.tools) are a collection of TypeScript libraries for writing web servers in [Worker Runtimes](https://workers.js.org) such as Cloudflare Workers, Deno Deploy and Service Workers in the browser. \n\nIf you liked this module, you might also like:\n\n- 🧭 [__Worker Router__][router] --- Complete routing solution that works across CF Workers, Deno and Service Workers\n- 🔋 [__Worker Middleware__][middleware] --- A suite of standalone HTTP server-side middleware with TypeScript support\n- 📄 [__Worker HTML__][html] --- HTML templating and streaming response library\n- 📦 [__Storage Area__][kv-storage] --- Key-value store abstraction across [Cloudflare KV][cloudflare-kv-storage], [Deno][deno-kv-storage] and browsers.\n- 🆗 [__Response Creators__][response-creators] --- Factory functions for responses with pre-filled status and status text\n- 🎏 [__Stream Response__][stream-response] --- Use async generators to build streaming responses for SSE, etc...\n- 🥏 [__JSON Fetch__][json-fetch] --- Drop-in replacements for Fetch API classes with first class support for JSON.\n- 🦑 [__JSON Stream__][json-stream] --- Streaming JSON parser/stingifier with first class support for web streams.\n\nWorker Tools also includes a number of polyfills that help bridge the gap between Worker Runtimes:\n- ✏️ [__HTML Rewriter__][html-rewriter] --- Cloudflare's HTML Rewriter for use in Deno, browsers, etc...\n- 📍 [__Location Polyfill__][location-polyfill] --- A `Location` polyfill for Cloudflare Workers.\n- 🦕 [__Deno Fetch Event Adapter__][deno-fetch-event-adapter] --- Dispatches global `fetch` events using Deno’s native HTTP server.\n\n[router]: https://workers.tools/router\n[middleware]: https://workers.tools/middleware\n[html]: https://workers.tools/html\n[kv-storage]: https://workers.tools/kv-storage\n[cloudflare-kv-storage]: https://workers.tools/cloudflare-kv-storage\n[deno-kv-storage]: https://workers.tools/deno-kv-storage\n[kv-storage-polyfill]: https://workers.tools/kv-storage-polyfill\n[response-creators]: https://workers.tools/response-creators\n[stream-response]: https://workers.tools/stream-response\n[json-fetch]: https://workers.tools/json-fetch\n[json-stream]: https://workers.tools/json-stream\n[request-cookie-store]: https://workers.tools/request-cookie-store\n[extendable-promise]: https://workers.tools/extendable-promise\n[html-rewriter]: https://workers.tools/html-rewriter\n[location-polyfill]: https://workers.tools/location-polyfill\n[deno-fetch-event-adapter]: https://workers.tools/deno-fetch-event-adapter\n\nFore more visit [workers.tools](https://workers.tools).","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fworker-tools%2Frouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fworker-tools%2Frouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fworker-tools%2Frouter/lists"}