Middleware
src/app/middleware.ts runs once per request BEFORE page dispatch. Returning undefined passes through; returning a Response short-circuits with that response (status, headers, body). The V8 isolate ships a minimal Response/Headers shim so the standard Web-API idioms work.
Try it
- /examples/middleware/protected — middleware returns a 401 because no token is present.
- /examples/middleware/protected?token=letmein — middleware passes through; the protected page renders.
Source
// src/app/middleware.ts
export default function middleware(request: Request, ctx: { path: string }): Response | undefined {
if (ctx.path.startsWith("/examples/middleware/protected")) {
const url = new URL(request.url);
if (url.searchParams.get("token") !== "letmein") {
return new Response("Unauthorized.\n", {
status: 401,
headers: { "content-type": "text/plain" },
});
}
}
return undefined; // pass-through
}