v1.0.10

Understanding Cookie Middleware in Fastro

Cookies are a fundamental primitive for maintaining state in web applications. Fastro includes a small but useful cookie middleware that parses incoming Cookie headers into ctx.cookies and provides a helper ctx.setCookie() to append Set-Cookie headers to responses.

This post explains how the middleware works, how to use it in your modules, and a few security best practices.

Where to find the code

What it provides

Why this is useful: handlers can read cookies synchronously (const user = ctx.cookies?.user) and set cookies without manually formatting header strings.

Usage example

  1. Register the middleware globally in app/main.ts:
import { cookieMiddleware } from "../middlewares/cookie/mod.ts";

app.use(cookieMiddleware);
  1. Read cookie in a handler (e.g. modules/dashboard/handler.tsx):
const user = ctx.cookies?.user;
if (!user) return new Response(null, { status: 303, headers: { Location: "/signin" } });
  1. Set cookie after successful signin (e.g. modules/signin/handler.tsx):
ctx.setCookie("user", identifier, { httpOnly: true, path: "/", maxAge: 60 * 60 * 24 });
return new Response(null, { status: 303, headers: { Location: "/dashboard" } });

Security best practices

Testing

Unit tests for the middleware are located at middlewares/cookie/cookie.test.ts. They cover parsing and Set-Cookie handling behavior.

Further reading

If you want, I can add a short example module that demonstrates a full signin → dashboard flow using the cookie middleware.