Edge middleware
Tiny code that runs at the CDN on every request, before your page does, to redirect, rewrite, or tag the visitor.
See it
What it is
A small function that runs at the CDN on every matched request, before your page or API route gets involved. It sees the incoming request and can do one of three things: let it continue, rewrite it to different content, or answer it outright with a redirect or a response. In Next.js it is one file at the project root with a matcher config: 'middleware.ts' up to Next.js 15, renamed to 'proxy.ts' in Next.js 16, with the runtime and execution details shifting between versions. Cloudflare and Netlify have the same shape under their own names.
The jobs it is good at: country and language redirects, bucketing visitors into an A/B cookie, gating a route on a session cookie, feature flags, adding security headers, blocking obvious junk traffic. The common thread is a cheap decision that must happen before anything renders and applies across the whole site.
Two traps. First, it sits on the critical path of every request it matches, so a lazy matcher that also catches '/_next' and every image makes the whole site slower for no benefit. Second, where it runs depends on your framework version and your host. Treat the tight budget as the safe assumption (no Node built-ins, small bundle, short execution limit) and then check what your version and platform actually do, because reaching for a database driver or a heavy npm package here is how people find out the hard way.
Ask AI for it
Detect the installed Next.js version first, then add this at the project root in the file that version expects: 'proxy.ts' on Next.js 16 or newer, 'middleware.ts' on anything earlier. Read the visitor's country from the geo metadata my deployment provider actually exposes, looked up for that provider rather than assumed, and rewrite DE and FR traffic to the matching localized path prefix. Set an A/B cookie ('bucket=a' or 'bucket=b') when it is missing, and continue otherwise. Add a matcher that excludes '/_next', '/api', and static asset extensions, since this runs on every request it matches. Keep it dependency-light with no network calls in the request path, and do not assume an edge-only runtime: tell me which runtime my version and host actually use.