npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@worker-tools/router

v0.3.0-pre.6

Published

A router for Worker Runtimes such as Cloudflare Workers and Service Workers.

Downloads

170

Readme

Worker Router

A router for Worker Runtimes such as Cloudflare Workers and Service Workers.

This router is inspired by previous work, specifically tiny-request-router and itty-router, but it improves on them by providing better support for middleware, type inference, nested routing, and broader URL matching for use in service workers.

🆓 Type Inference

The goal of Worker Router is to infer types based on usage so that no explicit typing is required for standard use cases. This allows even JavaScript users to benefit from inline documentation and API discoverability. For example,

const router = new WorkersRouter()
  .get('/about', basics(), (req, { userAgent }) => ok())
  .get('/login', unsignedCookies(), (req, { cookies }) => ok())

In this example your editor can infer the types and documentation for

  • userAgent, provided by the basics middleware
  • cookies, provided by the unsignedCookies middleware

🔋 Functional Middleware

Worker Router middlewares are just function that add properties to a generic context object. As such, they can be mixed and matched using standard tools from functional programming.

For convenience, this module provides a combine utility to combine multiple middlewares into one.

const myReusableMW = combine(
  basics(), 
  signedCookies({ secret: 'password123' }), 
  cookieSession({ user: '' })
);

const router = new WorkersRouter()
  .get('/', myReusableMW, () => ok())
  .post('/', combine(myReusableMW, bodyParser()), () => ok())

Note that type inference is maintained when combining middleware!

🪆 Nested Routing

Worker Router supports delegating entire sub routes to another router:

const itemRouter = new WorkerRouter()
  .get('/', (req, { params }) => ok(`Matched "/item/`))
  .get('/:id', (req, { params }) => ok(`Matched "/item/${params.id}`))

const router = new WorkersRouter()
  .get('/', () => ok('Main Page'))
  .use('/item*', itemRouter)

⚙️ Ready for Service... Worker

Internally, this router uses URLPattern for routing, which allows it match URLs in the broadest sense. For example, the following router, meant to be used in a Service Worker, can handle internal requests as well as intercept calls to external resources:

// file: "sw.js"
const router = new WorkersRouter()
  .get('/', () => ok('Main Page'))
  .get('/about', () => ok('About Page'))
  .external('https://plausible.io/api/*', req => {
    // intercepted
  })

💥 Error Handling Without Even Trying

Worker 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.

const router = new WorkersRouter()
  .get('/', () => ok('Main Page'))
  .get('/about', () => { throw Error('bang') })
  .recover('*', (req, { error, response }) => 
    new Response(`Something went wrong: ${error.message}`, response)
  );

✅ Works with Workers

Worker Router comes with out of the box support for a variety of Worker Runtimes:

To use it in an environment that provides a global fetch event, use

self.addEventListener('fetch', router)

(This works because the router implements the EventListener interface)

To use it with Cloudflare's module workers, use

export default router

(This works because the router implements a fetch method with compatible interface)

To use it with Deno/Deploy's serve function, use

serve(router.serveCallback)

Worker Tools are a collection of TypeScript libraries for writing web servers in Worker Runtimes such as Cloudflare Workers, Deno Deploy and Service Workers in the browser.

If you liked this module, you might also like:

  • 🧭 Worker Router --- Complete routing solution that works across CF Workers, Deno and Service Workers
  • 🔋 Worker Middleware --- A suite of standalone HTTP server-side middleware with TypeScript support
  • 📄 Worker HTML --- HTML templating and streaming response library
  • 📦 Storage Area --- Key-value store abstraction across Cloudflare KV, Deno and browsers.
  • 🆗 Response Creators --- Factory functions for responses with pre-filled status and status text
  • 🎏 Stream Response --- Use async generators to build streaming responses for SSE, etc...
  • 🥏 JSON Fetch --- Drop-in replacements for Fetch API classes with first class support for JSON.
  • 🦑 JSON Stream --- Streaming JSON parser/stingifier with first class support for web streams.

Worker Tools also includes a number of polyfills that help bridge the gap between Worker Runtimes:

Fore more visit workers.tools.