Next.jsMedium

How do you add middleware to API routes?

Use proxy.ts (formerly middleware.ts) with a matcher for /api/:path* to run shared logic, such as CORS, rate limiting or request IDs, before every API request. For logic that needs the handler's context, write wrapper functions (higher-order handlers) around your Route Handlers.

Option 1: Proxy

  • One proxy.ts at the project root (or in src/).
  • export const config = { matcher: ["/api/:path*"] }.
  • Can rewrite, redirect, add headers, return a response early (401, 429), or pass data upstream with request headers.
  • Runs on Node.js since Next.js 16, but should stay fast: avoid slow database calls. fetch caching does not work in Proxy.

Option 2: Handler wrappers

Compose functions like withAuth(withValidation(schema, handler)). Each wrapper receives the request and context, does its check, and either returns an error response or calls the inner handler. This keeps authorization next to the code that needs it, which is safer than Proxy alone.

Option 3: Shared helpers

Plain helper calls at the top of each handler (const user = await requireUser()) are explicit and easy to test.

Pages Router

pages/api routes are also covered by Proxy. Libraries like next-connect add Express-style middleware chains to API routes.

What not to do

Do not rely only on Proxy for authorization. A matcher typo or a moved route silently removes protection. Always check permissions in the handler too.

Code example

tsx
1// lib/with-auth.ts - higher-order Route Handler
2import { verifySession } from "@/lib/dal";
3
4type Handler<C> = (req: Request, ctx: C, user: { userId: string }) => Promise<Response>;
5
6export function withAuth<C>(handler: Handler<C>) {
7 return async (req: Request, ctx: C) => {
8 const user = await verifySession();
9 if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
10 return handler(req, ctx, user);
11 };
12}
13
14// app/api/me/route.ts
15export const GET = withAuth(async (_req, _ctx, user) => Response.json({ id: user.userId }));
16
17// proxy.ts - cross-cutting concerns for all API routes
18// export function proxy(req: NextRequest) {
19// const res = NextResponse.next();
20// res.headers.set("x-request-id", crypto.randomUUID());
21// return res;
22// }
23// export const config = { matcher: ["/api/:path*"] };

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app