Why this matters
Middleware runs on many requests; unnecessary work multiplies cost.
Keep middleware fast and side-effect free (no DB writes). Narrow the matcher and skip static assets. Use Route Handlers for heavy logic.
Middleware runs on many requests; unnecessary work multiplies cost.
Side-by-side examples engineers can pattern-match during review.
// middleware.ts
await db.audit.insert({ path: req.nextUrl.pathname })// middleware.ts
import { NextResponse } from 'next/server'
export const config = { matcher: ['/((?!_next|.*\\..*|api/health).*)'] }
export function middleware(req){ /* cheap checks */ return NextResponse.next() }Heavy I/O inside middlewarematcher that skips assets and healthFrom the same buckets as this rule.