← Back to Docs
RECIPE

Middleware Patterns

Composable guards, rate-limiters, and session validators that run at the edge before your route handlers fire.

Chain of Responsibility

Stack middleware functions in middleware.ts. Each layer inspects the request and either passes control via NextResponse.next() or short-circuits with a redirect. Order matters — place authentication before rate-limiting so banned tokens never reach the counter.

Matcher-Driven Scoping

Use the config.matcher export to restrict middleware to specific paths. Protect /dashboard/* while leaving public assets and API health-checks untouched. Negative lookaheads exclude static files without extra conditionals.

Token-Bucket Rate Limiting

Store counters in Upstash KV keyed by IP or session ID. On each request, decrement the bucket. When the bucket empties, return a 429 with a Retry-After header. Refill buckets on a cron or lazily on next access.

Geo-Fencing at the Edge

Read the x-vercel-ip-country header injected by Vercel's edge network. Block or redirect traffic from embargoed regions before it touches your origin. Combine with a country allow-list stored in environment variables for zero-latency enforcement.