DEV Community

Guido Zuidhof
Guido Zuidhof

Posted on

Introducing Sunder: A framework for Cloudflare Workers

Today I released Sunder, a framework for Service Worker environments such as 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.

I am building it to scratch my own itch - I have written the same thing 4 times now from scratch for Cloudflare Worker projects, this would make much of that boilerplate unnecessary. Sunder is "Express" for Cloudflare Workers.

Sunder is designed to be minimal, testable, and easy to understand. It's only a few hundred lines of code.

A small example

import {Sunder, Router} from "sunder";

const app = new Sunder();
const router = new Router();

// Example route with a named parameter
router.get("/hello/:username", ({response, params}) => {
    response.body = `Hello ${params.username}`;
    response.headers.set("content-type", "text/plain");
});

app.use(router.middleware);

addEventListener('fetch', (event) => {
    app.handleEvent(event);
});
Enter fullscreen mode Exit fullscreen mode

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:

async function responseTimeMiddleware(ctx, next) {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.response.headers.set('X-Response-Time', `${ms}ms`);    
}
Enter fullscreen mode Exit fullscreen mode

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.

Strict routes GIF

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, and it's all open source.

Consider it a beta. Things will change, the docs are incomplete, the amount of available pre-written middleware is small, but all projects start somewhere. Contributions are welcome!

Oldest comments (0)