Skip to main content

Hooks Example

Using global and route-specific hooks:

Global: Export a hook array from src/hooks.ts. It runs for every request in the app (e.g. logger, CORS).

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

export const onRequest = [
async (ctx: BurgerContext) => {
console.log(`${ctx.method} ${ctx.url}`);
},
];

Route-specific: Export hook points (transform, beforeRoute, afterRoute, mapResponse, onError) from a route's hooks.ts. They run only for that route directory. beforeRoute runs after global hooks and validation, before the handler.

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

export const beforeRoute = [
async (ctx: BurgerContext) => {
if (ctx.query.admin !== "true") {
return Response.json({ error: "Forbidden" }, { status: 403 });
}
},
];
// src/api/products/route.ts
import type { BurgerContext } from "burger-api";

export async function GET(ctx: BurgerContext) {
return Response.json({ data: [] });
}

A hook returns a Response to short-circuit the request, or undefined to continue. afterRoute and mapResponse can also return a function that transforms the response.

See Hook System, Global Hooks, and Route Hooks.