Onion Middleware Pipeline

Katal v3 implements the Onion Middleware Pattern (familiar to users of Hono, Koa, and Fastify). Every middleware executes in two distinct phases: inward (before the controller) and outward (after the controller) around await next().

                    Incoming HTTP Request
                              │
                              ▼
                 ┌─────────────────────────┐
                 │    Global Middleware 1  │
                 │  ┌───────────────────┐  │
                 │  │ Named Middleware  │  │
                 │  │  ┌─────────────┐  │  │
                 │  │  │ Controller  │  │  │
                 │  │  │   handle()  │  │  │
                 │  │  └──────┬──────┘  │  │
                 │  │         │         │  │
                 │  │         ▼         │  │
                 │  │  Returns Response │  │
                 │  └─────────┬─────────┘  │
                 │            │            │
                 └────────────┼────────────┘
                              │
                              ▼
                     Outgoing Response

1. Middleware Signature

A middleware handler in Katal v3 is an asynchronous function that receives context and next:

import type { MiddlewareHandler } from "katal";

export const timingMiddleware: MiddlewareHandler = async (context, next) => {
    // 1. INWARD PASS: Executes before downstream middleware and controller
    const start = performance.now();
    context.state.startTime = start;

    // 2. DELEGATION: Yield control to next middleware or controller
    const response = await next();

    // 3. OUTWARD PASS: Executes after controller returns a Response
    const duration = (performance.now() - start).toFixed(2);

    // Inject headers or mutate the outgoing response
    response.headers.set("X-Response-Time", `${duration}ms`);
    return response;
};

2. Global Middleware

Global middleware wraps every route handled by the application:

import { Application } from "katal";

const app = new Application();

// 1. Attach reusable middleware handler
app.use(timingMiddleware);

// 2. Attach inline anonymous middleware
app.use(async (ctx, next) => {
    ctx.state.requestId = crypto.randomUUID();
    return await next();
});

3. Named Middleware & Route Assignment

Register middleware with an alias, then attach it to individual routes or route groups:

// 1. Register named middleware
app.middleware("apiKey", async (ctx, next) => {
    const key = ctx.request.headers.get("x-api-key");
    if (key !== process.env.API_SECRET) {
        return new Response(JSON.stringify({ error: "Invalid API Key" }), {
            status: 401,
            headers: { "Content-Type": "application/json" },
        });
    }
    return await next();
});

// 2. Attach to a single route
app.getRouter().get("/api/v1/metrics", MetricsController, {
    middleware: ["apiKey"],
});

// 3. Attach to a route group
app.group("/api/v1/admin", (router) => {
    router.get("/users", ListUsersController);
    router.delete("/users/:id", DeleteUserController);
}, { middleware: ["auth", "apiKey"] });

4. Pipeline Short-Circuiting (Early Exit)

To terminate request execution early (e.g. rate limit exceeded, missing authentication, maintenance mode), simply return a Response without invoking next():

export const maintenanceMiddleware: MiddlewareHandler = async (ctx, next) => {
    const isMaintenanceMode = false;

    if (isMaintenanceMode) {
        // Pipeline stops here! Downstream middleware and controller are NOT called.
        return new Response(JSON.stringify({
            message: "System temporarily down for maintenance.",
        }), {
            status: 503,
            headers: { "Content-Type": "application/json" },
        });
    }

    return await next();
};

5. Sharing State via context.state

ctx.state is a strongly typed container that persists across the entire request lifecycle. Set variables in early middleware and read them in controllers:

// Authentication middleware populates state
app.middleware("session", async (ctx, next) => {
    const sessionId = ctx.request.headers.get("x-session-id");
    ctx.state.session = await lookupSession(sessionId);
    return await next();
});

// Controller consumes state
class ProfileController extends Controller {
    async handle(ctx: RequestContext) {
        const session = ctx.state.session as Session;
        return this.success({ user: session.user });
    }
}

6. Error Boundaries & Guaranteed CORS Preservation

In Katal v3, uncaught exceptions thrown inside controllers bubble back up through the onion middleware stack. This guarantees that outer middleware (such as CORS, Structured Observability, or Error Handlers) can intercept errors and preserve critical headers:

// Global Error Boundary Middleware
app.use(async (ctx, next) => {
    try {
        return await next();
    } catch (err: any) {
        console.error("Uncaught exception in request boundary:", err);

        // Guarantees CORS and Problem Details headers even on 500 crashes
        return new Response(JSON.stringify({
            type: "about:blank",
            title: "Internal Server Error",
            status: 500,
            detail: process.env.NODE_ENV === "production" ? "An unexpected error occurred." : err.message,
        }), {
            status: 500,
            headers: {
                "Content-Type": "application/problem+json",
                "Access-Control-Allow-Origin": "*",
            },
        });
    }
});

7. Backward Compatibility: Legacy { before, after } Middleware

If you maintain legacy Katal v2 middleware using { before, after } objects, they continue to work seamlessly without modification:

// Legacy v2 format (automatically adapted to onion pipeline internally)
app.use({
    before: async (ctx) => {
        // Return null to continue, or Response to abort
        return null;
    },
    after: async (ctx) => {
        return ctx.response;
    },
});

See Also