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/middleware

v0.1.0-pre.36

Published

A suite of standalone HTTP server middlewares for Worker Runtimes.

Downloads

351

Readme

Worker Middleware

A suite of standalone HTTP server middlewares for Worker Runtimes.

It is meant to be used with Worker Router, but can also be used with simple request handlers.

Cookies

Supports singed, unsigned and encrypted cookies.

Signed and encrypted cookies use the Web Cryptography API internally to en/decrypt sign and verify cookies.

router.get('/', signedCookies({ secret: 'password123' }), (request, { cookies, cookieStore }) => {
  cookieStore.set('foo', 'bar') // no await necessary
  return ok(cookie.foo === 'bar' ? 'Welcome back!' : 'Welcome!')
})

The cookieStore property implements the web's Cookie Store API for maximum standard compatibility. For better DX, the middleware also provides a read-optimized cookies property, which are the request's cookies parsed into a plain JS object.

Modifying cookies is done via the cookie store. While the cookie store API is async, there is no need to await every result, as the cookie store keeps track of all operations and awaits them internally before sending the headers.

Session

Session middleware provides a plain JavaScript object that is serialized/deserialized via the Structured Clone Algorithm, i.e. it behaves largely the same as storing an object in IndexedDB. In other words, it can have Maps, Sets, and ArrayBuffers, etc.

cookieSession

The cookie session encodes the entire session object into a cookie and is meant for prototyping and small use cases.

router.get('/', combine(
  signedCookies({ secret: 'password123' }),
  cookieSession({ 
    defaultSession: { id: '', iv: new Uint8Array([]) }
  }) 
), (request, { session }) => {
  if (!session.id) {
    session.id = crypto.randomUUID();
    session.iv = crypto.getRandomValues(new Uint8Array(32))
  }
  return ok()
})

storageSession

The storage session uses a KV Storage API-compatible storage object to persist the session object between requests. Worker Tools has storage adapters for Cloudflare's KV storage and SQLite/Postgres for Deno.

router.get('/', combine(
  signedCookies({ secret: 'password123' }), 
  storageSession({ 
    storage: new StorageArea('sessions'),
    defaultSession: { id: '', iv: new Uint8Array([]) },
  }) 
), (request, { session }) => {
  if (!session.id) {
    session.id = crypto.randomUUID();
    session.iv = crypto.getRandomValues(new Uint8Array(32))
  }
  return ok()
})

Both cookieSession and storageSession must be combined with a cookie middleware.

The session object is persisted once at the end of the request.

Body Parser

Because Worker Runtimes already provide helpers like .json() and .formData() in the Request type, the need for a body parser is less pronounced. The value of Middleware's body parser mainly comes from content negotiation and rejecting large payloads:

defaultBodyParser

router.any('/form', 
  defaultBodyParser({ maxSize: 1024**2 }), // 1MB 
  (req, { accepted, ...ctx }) => {
    switch (accepted) {
      case 'application/x-www-form-urlencoded': {
        ctx.form // instanceof URLSearchParams
        return ok()
      }
      case 'multipart/form-data': {
        ctx.formData // instanceof FormData
        return ok()
      }
      case 'application/json': {
        ctx.json
        return ok()
      }
      case 'application/octet-stream':
      case 'application/x-binary': { // commonly used non-standard mime type
        ctx.blob // instanceof Blob
        ctx.buffer // instanceof ArrayBuffer
        return ok()
      }
      default: {
        return ok()
      }
    }

    return ok()
  })

bodyParser

You can also limit what is acceptable to the endpoint by combining the content negotiation middleware and bodyParser:

router.any('/form', combine(
  accepts(['application/x-www-form-urlencoded', 'multipart/form-data']), 
  bodyParser()
), (request, { accepted, body }) => {
  switch (accepted) {
    case 'application/x-www-form-urlencoded': {
      body // instanceof URLSearchParams
      return ok()
    }
    case 'multipart/form-data': {
      body // instanceof FormData
      return ok()
    }
  }
})

NOTE: It's currently only possible to limit what the body parser accepts.

Content Negotiation

Provides generic content negotiation for HTTP endpoints.

contentTypes

The contentTypes middleware lets you specify what content types the endpoint can provide. For example, we can build a mini deno.land that either serves raw JavaScript or a HTML page depending on accepts header:

router.get('/add.js', combine(
  contentTypes(['text/html', 'text/javascript'])
), (request, { type }) => {
  // `type` is either 'text/html' or 'text/javascript',
  // depending on the client's `Accepts` header (best match)
  switch (type) {
    case 'text/javascript': 
      return ok('export function add(a, b) { return a + b }')
    case 'text/html': 
      return ok('<html>Documentation for <code>add</code>.</html>')
  }
}

Basics

TBD


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.