Skip to main content
Version: 4.x

The micro runtime

@expressots/micro is a router built on the Fetch API. A handler takes a Request and returns a Response or a value, so the same application runs on Node and on Cloudflare Workers, where its test suite runs, and is written for any runtime with the Fetch API, such as Vercel Edge, Deno and Bun. The package imports nothing from Node outside its Node adapter: a Worker built with it needs no nodejs_compat flag and is about 6 KiB gzipped.

It is new in 4.5, and it is what expressots new --target cloudflare builds on. micro() from @expressots/adapter-express, described in the Micro API guide, is unchanged and stays the way to run a micro application on Node with Express middleware and Studio.

npm install @expressots/micro

An application​

import { HttpError, micro } from "@expressots/micro";

const app = micro({ globalPrefix: "/api" });

app.get("/users/:id", (request, ctx) => {
const user = users.get(ctx.params.id);
if (!user) throw new HttpError(404, `User ${ctx.params.id} not found`);
return user;
});

app.post("/users", async (request, ctx) => {
const body = await ctx.body<{ name: string }>();
return Response.json(users.create(body.name), { status: 201 });
});

export default { fetch: app.handler };

What a handler returns​

What a handler returns is the response. The status does not depend on the method.

ReturnedResponse
a Responsesent as it is, so a status, headers or a stream are yours to set
a stringtext/html
undefined204 No Content
a ReadableStream, Blob, ArrayBuffer or typed arraythe body, streamed
anything elseJSON

The context​

The second argument, ctx, holds what the request does not:

MemberWhat it is
ctx.paramsThe route's path parameters, decoded
ctx.queryThe query string as an object. A key given more than once is an array of its values; brackets have no meaning
ctx.urlThe request's URL, parsed
ctx.envThe runtime's bindings: a Worker's env. Type it with micro<Env>()
ctx.waitUntil(promise)Keeps work running after the response, where the runtime allows it
ctx.body()Reads the body once and parses it by its Content-Type: JSON, a form (an object; a repeated field becomes an array; a file a File), text, or bytes (Uint8Array). undefined when there is no body
ctx.stateValues a middleware leaves for the handlers after it

Malformed JSON is answered with 400. A body over 1 MiB is answered with 413: from its declared length before a byte is read, and as it streams when it declares none. micro({ maxBodySize }) changes the limit, and 0 turns it off.

Routes​

Paths match as Express matches them: in any case, with or without a trailing slash. :name is a parameter, also inside a segment (/files/:name.:ext), and *name as the last segment is the rest of the path, as a string. A GET route answers HEAD too, and OPTIONS is answered with the methods a path has. app.routes() lists the routes, prefix included.

Middleware​

app.use(async (request, ctx, next) => {
const started = Date.now();
const response = await next();
response.headers.set("server-timing", `total;dur=${Date.now() - started}`);
return response;
});

app.use("/admin", (request) => {
if (!request.headers.get("authorization")) return new Response(null, { status: 401 });
});

app.get("/orders/:id", loadOrder, showOrder);

A middleware answers by returning a value, as a handler does, or lets the request go on by returning next() (whose response it may change) or by returning nothing. It runs in the order it was added among the routes, as in Express: middleware added after a route does not run for requests that route answers. Middleware for one route goes before its handler.

Express middleware does not run here: (req, res, next) functions need micro() from @expressots/adapter-express.

Errors​

Every error is answered with a problem document (RFC 9457, application/problem+json), with the same types and codes as the rest of ExpressoTS:

  • A route that does not exist: 404, EXP2003. Outside production the document lists the closest routes in suggestions.
  • An HttpError, or an error carrying a 4xx status: its status and message.
  • Anything else: 500, EXP2002. Its message is sent outside production only. A thrown value that is not an error is never echoed back.

app.setErrorHandler((error, request, ctx) => ...) answers errors your way; when it returns nothing, the problem document is sent.

The environment is NODE_ENV. When it is not set, it is development on Node, Bun and Deno, as in the rest of ExpressoTS, and production on Cloudflare Workers, which have no NODE_ENV. micro({ environment }) sets it explicitly.

Running it​

Cloudflare Workers, Deno, Bun, Vercel Edge: export the handler.

export default { fetch: app.handler };

On Workers, @expressots/micro/cloudflare gives typed tokens for KV, D1, R2 and Queue bindings, resolved from the env of the request being answered. A token names a binding of the right kind, or the code does not compile:

import { cloudflareBindings, servicesOf } from "@expressots/micro/cloudflare";

interface Env {
SETTINGS: KVNamespace;
CACHE?: KVNamespace;
}

const bindings = cloudflareBindings<Env>();
const Settings = bindings.kv("SETTINGS");

const app = micro<Env>();
app.get("/theme", async (request, ctx) => ({
theme: await servicesOf(ctx.env).get(Settings).get("theme"),
}));

Node:

import { serve } from "@expressots/micro/node";

await serve(app, { port: 3000 });

toNodeHandler(app) gives a node:http request listener for a server you create yourself. Request and response bodies stream in both directions, each Set-Cookie stays its own header, and a request's signal aborts when the client goes away.

Compared with micro() on Express​

@expressots/micromicro() from @expressots/adapter-express
Handler(request, ctx), returns the response(req, res, next), Express's objects
Runs onNode and Workers (tested); any runtime with the Fetch APINode; Workers and Lambda through an adapter
Worker~6 KiB gzip, no nodejs_compat~200 KiB gzip, nodejs_compat
Streamingyesnot on serverless adapters
Express middlewarenoyes
validateBody(schema)no: validate in the handler or a middlewareyes
Studio, expressots check, expressots inspectnoyes