Lesson 15 / 32
Edge Middleware Patterns
Use edge code for redirects, rewrites, headers, early auth checks and sticky A/B testing without slowing every request.
By Rahul Agarwal · 15 years in web development
A thin, fast layer in front of the origin
A very common use of edge compute is not a whole API but a thin layer in front of your origin, often called edge middleware. It runs before the cache or origin and can redirect (old URLs, country-specific sites), rewrite (serve /variants/B/pricing while the browser still shows /pricing), add or remove headers (security headers, a request ID), check an auth token before traffic reaches expensive servers, or assign users to A/B test buckets. Platforms expose request metadata such as the visitor's approximate country, which enables geo-routing; on Cloudflare it appears on request.cf. The design rule is to keep middleware fast and mostly self-contained: it sits on the critical path of every matching request, so one slow call inside it slows the whole site. Frameworks such as Next.js have their own middleware conventions that deploy to this layer; check your framework version's documentation for file names and supported runtimes.
Sticky A/B buckets with a rewrite
A returning visitor with the ab=B cookie keeps bucket B, so no new cookie is set. New visitors are assigned randomly and receive the cookie.
// Edge A/B test: sticky bucket via cookie, then rewrite to a variant path.
function pickBucket(request) {
const cookie = request.headers.get('cookie') ?? '';
const match = cookie.match(/(?:^|;\s*)ab=(A|B)/);
if (match) return { bucket: match[1], isNew: false };
return { bucket: Math.random() < 0.5 ? 'A' : 'B', isNew: true };
}
async function handle(request) {
const { bucket, isNew } = pickBucket(request);
const url = new URL(request.url);
url.pathname = `/variants/${bucket}${url.pathname}`;
// A real edge function would now fetch(url) from the origin.
const res = new Response(`served ${url.pathname}`);
if (isNew) res.headers.append('set-cookie', `ab=${bucket}; Path=/; Max-Age=2592000`);
return res;
}
const res = await handle(new Request('https://shop.example/pricing', { headers: { cookie: 'ab=B' } }));
console.log(await res.text(), '| set-cookie:', res.headers.get('set-cookie'));
Output:
served /variants/B/pricing | set-cookie: null
Variants and caching must agree
If the CDN caches /pricing by URL alone, bucket A users may be served bucket B's cached page. Because the rewrite changes the path, each variant gets its own cache key here. When you vary content by a cookie or header instead, make sure that value is part of the cache key.
The security desk at a tech park
The guard at the gate checks your ID, sends you to the right tower and hands you a visitor badge, all in seconds. If the guard started phoning every office to confirm each visitor, the queue would reach the main road. Middleware should behave like the good guard.
Quick check: Which job is the poorest fit for edge middleware?
- Redirecting old blog URLs to new ones
- Rejecting requests that carry an invalid token
- Adding security headers to every response
- Generating a 50-page PDF report from several database queries
Answer
Generating a 50-page PDF report from several database queries — Middleware sits in front of every matching request and has tight CPU limits. Heavy, data-bound work belongs in a regional function or a background job.