Skip to main content

Global Hooks

Global hooks are defined once and applied across the app. Define them in src/hooks.ts with one named export per hook point:

// src/hooks.ts
import type { BurgerContext } from "burger-api";

export const beforeRoute = [
async (ctx: BurgerContext) => {
if (!ctx.headers.get("authorization")) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
},
];

You can export any of the six hook points: onRequest, transform, beforeRoute, afterRoute, mapResponse, onError.

Hook factories from ecosystem/hooks/ compose here too:

// src/hooks.ts
import { cors } from "../ecosystem/hooks/cors/cors";
import { logger } from "../ecosystem/hooks/logger/logger";

export const onRequest = [logger(), cors({ origin: ["https://app.example.com"] })];

Scope order: Framework → Plugin → Global → Route for request hooks. Response hooks (afterRoute, mapResponse) and error hooks (onError) run nearest-first: Route → Global → Plugin → Framework.

transform​

transform is not a function: it is a map of field names to factory functions. Each factory receives ctx and its result is shallow-assigned onto the context before validation runs, so handlers and later hooks can read it.

// src/hooks.ts
import type { GlobalHooks } from "burger-api";

export const transform: GlobalHooks["transform"] = {
tenant: (ctx) => ctx.headers.get("x-tenant"),
};

Built-in fields are reserved and cannot be replaced: every field, getter and method on BurgerContext (for example params, query, json, route, set, services, ip) plus internal names such as cache and _-prefixed keys. A transform entry with a reserved name throws at startup, so the typo is fixed before a request runs. Global transform entries apply before route-level entries, so a route can override a global value.

onRequest, afterRoute and mapResponse run for every response the app produces, including pages, assets, /docs and /openapi.json. transform and beforeRoute run for matched API routes and WebSocket upgrades.

Use global hooks for logging, CORS, auth checks, or any logic that should run across routes. See Hook System and Ecosystem.