Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/worker-tools/middleware
Placeholder for Worker-based middleware solution
https://github.com/worker-tools/middleware
cloudflare-workers deno http middleware server workers
Last synced: 1 day ago
JSON representation
Placeholder for Worker-based middleware solution
- Host: GitHub
- URL: https://github.com/worker-tools/middleware
- Owner: worker-tools
- Created: 2021-01-07T03:35:09.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2023-09-24T12:48:46.000Z (about 1 year ago)
- Last Synced: 2024-11-10T19:09:03.295Z (6 days ago)
- Topics: cloudflare-workers, deno, http, middleware, server, workers
- Language: TypeScript
- Homepage: https://workers.tools/middleware
- Size: 125 KB
- Stars: 6
- Watchers: 2
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Worker Middleware
A suite of standalone HTTP server middlewares for Worker Runtimes.
It is meant to be used with [Worker Router](../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.
```js
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.```js
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](https://workers.tools/kv-storage) for Cloudflare's KV storage and SQLite/Postgres for Deno.```js
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`
```js
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](#content-negotiation) and `bodyParser`:```js
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:```js
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('Documentation foradd
.')
}
}
```## Basics
TBD
--------
This module is part of the Worker Tools collection
β[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.
If you liked this module, you might also like:
- π§ [__Worker Router__][router] --- Complete routing solution that works across CF Workers, Deno and Service Workers
- π [__Worker Middleware__][middleware] --- A suite of standalone HTTP server-side middleware with TypeScript support
- π [__Worker HTML__][html] --- HTML templating and streaming response library
- π¦ [__Storage Area__][kv-storage] --- Key-value store abstraction across [Cloudflare KV][cloudflare-kv-storage], [Deno][deno-kv-storage] and browsers.
- π [__Response Creators__][response-creators] --- Factory functions for responses with pre-filled status and status text
- π [__Stream Response__][stream-response] --- Use async generators to build streaming responses for SSE, etc...
- π₯ [__JSON Fetch__][json-fetch] --- Drop-in replacements for Fetch API classes with first class support for JSON.
- π¦ [__JSON Stream__][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:
- βοΈ [__HTML Rewriter__][html-rewriter] --- Cloudflare's HTML Rewriter for use in Deno, browsers, etc...
- π [__Location Polyfill__][location-polyfill] --- A `Location` polyfill for Cloudflare Workers.
- π¦ [__Deno Fetch Event Adapter__][deno-fetch-event-adapter] --- Dispatches global `fetch` events using Denoβs native HTTP server.[router]: https://workers.tools/router
[middleware]: https://workers.tools/middleware
[html]: https://workers.tools/html
[kv-storage]: https://workers.tools/kv-storage
[cloudflare-kv-storage]: https://workers.tools/cloudflare-kv-storage
[deno-kv-storage]: https://workers.tools/deno-kv-storage
[kv-storage-polyfill]: https://workers.tools/kv-storage-polyfill
[response-creators]: https://workers.tools/response-creators
[stream-response]: https://workers.tools/stream-response
[json-fetch]: https://workers.tools/json-fetch
[json-stream]: https://workers.tools/json-stream
[request-cookie-store]: https://workers.tools/request-cookie-store
[extendable-promise]: https://workers.tools/extendable-promise
[html-rewriter]: https://workers.tools/html-rewriter
[location-polyfill]: https://workers.tools/location-polyfill
[deno-fetch-event-adapter]: https://workers.tools/deno-fetch-event-adapterFore more visit [workers.tools](https://workers.tools).