Introducing Sunder - A framework for ServiceWorkers (like Cloudflare Workers)
Originally posted on the Sunder blog.
Sunder is a framework for Service Workers like those found in Cloudflare Workers. It allows you to create testable APIs and websites in a similar way as you would using Node.js’s Koa or Express framework.
Sunder is designed to be minimal, testable, and easy to understand. It’s only a few hundred lines of code.
A small example
|
|
This is a complete example, bundle it using a tool like esbuild
in under 50ms and it’s ready for use in Cloudflare workers.
Everything is middleware#
Inspired by Koa and Elixir’s Plug, in Sunder everything is a middleware.
A middleware function takes two arguments, the request’s Context
and a function that invokes the next middleware. An example explains it best:
|
|
If you have used Koa in the past, this should look very familiar. By making use of the async
keyword we can await
asynchronous tasks and avoid callback hell.
By composing this core building block we can handle any request in an elegant way.
Strict routes#
Typescript recently released support for Template Literal Types. This allows us to type a route’s path parameters in a strict way and catch common mistakes.
Note: You can use Sunder without Typescript too, but you will miss out on this type checking.
So can I use this?#
Yes, you can install Sunder now (npm i sunder
) and use it in your projects. It is open source under the MIT license.
It is however still a work in progress, things will change, and the docs are incomplete. The amount of available pre-written middleware is small. Contributions are of course welcome!