Next.js middleware: edge patterns and pitfalls
middleware.ts runs on the Edge before a request hits your Node server or static asset. That makes it ideal for fast redirects, header injection, and coarse auth gates—and dangerous for heavy logic or remote calls if you care about TTFB.
Matcher precision
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};
Exclude static assets or you pay middleware cost on every image request.
Auth redirect pattern
Read a session cookie or JWT, validate signature cheaply (symmetric key or pre-parsed claims), and NextResponse.redirect unauthenticated users away from /app/*.
Do not replace full authorization: middleware should enforce “logged in vs not”, not fine-grained RBAC for every route—that belongs in Server Components or API routes with DB lookups.
Headers and experiments
export function middleware(req: NextRequest) {
const res = NextResponse.next();
res.headers.set('x-request-id', crypto.randomUUID());
return res;
}
Use request IDs to correlate logs across services.
Limitations
- No Node-only APIs (
fs, somecryptoshapes) depending on runtime. - Long
fetchto external services on every request adds latency globally—cache sparingly or move to lazy checks.
Summary
Middleware is a sharp knife: great for redirects, security headers, and request tagging; poor as a second application server. Keep it fast, match narrowly, and defer heavy authz to deeper layers.