Vercel Edge Middleware Patterns for Auth and A/B Testing
Gate auth with a locally verified JWT and run A/B tests with no flash of wrong content, using Vercel middleware (proxy.ts in Next.js 16).
Key takeaways
- Use Vercel middleware for coarse, pre-render decisions: verify a signed JWT cookie for a logged-in gate, assign A/B buckets with a sticky cookie and rewrite, and route by geolocation headers.
- In Next.js 16 the file is proxy.ts and runs on Node.js by default.
- Keep permissions, billing and revocation checks at the origin.
On this page
Put two jobs in Vercel middleware: verify a signed session cookie locally (no call to your auth API) and assign A/B buckets with a sticky cookie plus NextResponse.rewrite, so the right variant renders with no flicker. In Next.js 16 the file is proxy.ts, not middleware.ts. Keep anything needing fresh authority at the origin.
Verified against
Next.js 16 (16.4.3 on npm), jose 6.2, @vercel/functions, against the Next.js proxy.js file-convention reference and Vercel's Routing Middleware and @vercel/functions docs. Checked October 2026.
The usual trigger is a homepage headline test shipped as a client-side flag check. The old headline paints, the flag resolves, the new one swaps in, and on a slow phone it looks broken. Moving the decision before render removes the flicker, and once middleware is in place, auth gating follows naturally.
Two naming changes matter as of October 2026. Next.js 16 deprecated the middleware file convention and renamed it proxy (the codemod is npx @next/codemod@canary middleware-to-proxy .), and Proxy now defaults to the Node.js runtime. Vercel calls the platform feature Routing Middleware: it runs globally before the cache, and it is billed on the fluid compute model, by compute used. Older posts that say "Edge Middleware runs on the edge runtime with no Node APIs" are describing the pre-16 world.
Auth gating without a round trip to your API
The naive approach calls your auth service from middleware. Don't. That turns a local decision into a network hop to wherever your API lives, on every matched request. Instead, verify a signed token in middleware and only go to the origin when you need fresh data.
We use a JWT in an httpOnly cookie, verified with jose, which is built on Web Crypto and runs in both the Node.js and edge runtimes:
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';
const secret = new TextEncoder().encode(process.env.JWT_SECRET!);
export const config = {
matcher: ['/app/:path*', '/settings/:path*'],
};
export async function proxy(req: NextRequest) {
const token = req.cookies.get('session')?.value;
if (!token) {
return NextResponse.redirect(new URL('/login', req.url));
}
try {
const { payload } = await jwtVerify(token, secret, { algorithms: ['HS256'] });
const headers = new Headers(req.headers);
headers.delete('x-user-id'); // never trust a client-supplied copy
headers.set('x-user-id', String(payload.sub));
return NextResponse.next({ request: { headers } });
} catch {
const res = NextResponse.redirect(new URL('/login', req.url));
res.cookies.delete('session');
return res;
}
}
Three things people miss here. First, the matcher keeps middleware off static assets and public pages; without one, the Next.js docs warn it runs on every request, including _next/static and images. Second, the user ID goes on the request headers via NextResponse.next({ request: { headers } }). Setting it with res.headers.set puts it on the response, which leaks it to the browser and never reaches your page. Third, delete any incoming x-user-id first, or a client can send its own and impersonate anyone on routes your matcher skips.
Token lifetime is the tradeoff. A 15-minute JWT with a refresh token means a revoked session can stay valid for up to 15 minutes at this layer. For most apps that's fine. For anything touching money, keep the sensitive checks at the origin and use middleware only for the coarse "logged in or not" gate. The Next.js docs make the same point about Server Functions: a matcher change can silently drop coverage, so verify auth inside each one too. We go deeper on key rotation and kid handling in validating JWTs at the edge without origin round trips.
A/B testing that doesn't flicker
The flicker goes away when assignment happens before render. Middleware reads a bucket cookie, assigns one if it's missing, and rewrites to the variant path.
import { NextRequest, NextResponse } from 'next/server';
export const config = { matcher: ['/'] };
export function proxy(req: NextRequest) {
const existing = req.cookies.get('exp_homepage')?.value;
const bucket = existing === 'a' || existing === 'b' ? existing : Math.random() < 0.5 ? 'a' : 'b';
const res = NextResponse.rewrite(new URL(`/variants/${bucket}`, req.url));
if (!existing) {
res.cookies.set('exp_homepage', bucket, { maxAge: 60 * 60 * 24 * 30, sameSite: 'lax' });
}
return res;
}
rewrite is the key verb, not redirect. The URL in the browser stays /, but the variant page is served, so the user never sees a bounce. Because assignment is sticky in the cookie, a returning visitor lands in the same bucket, which keeps conversion metrics honest. Validate the cookie value before interpolating it into a path; an attacker-chosen bucket is a path you didn't plan to expose.
Two caveats. Don't name the folder _variants: in the App Router, an underscore prefix makes a private folder that isn't routable, so the rewrite 404s. And the two variants must have separate cache entries. Rewriting to distinct paths gives you that; rewriting both to one dynamic route keyed on a header does not, and bucket A starts serving bucket B's HTML from cache. When the experiment ends, delete the cookie logic and the losing variant, a cleanup step teams skip constantly, as we cover in feature flags in production.
Geolocation without an external lookup
Vercel adds geolocation headers such as x-vercel-ip-country to every request middleware receives. req.geo was removed from NextRequest in Next.js 15; read the headers with the geolocation() helper from @vercel/functions:
// proxy.ts (excerpt)
import { geolocation } from '@vercel/functions';
const { country } = geolocation(req);
if (country === 'DE' && !req.cookies.get('consent')) {
return NextResponse.rewrite(new URL('/consent', req.url));
}
Treat a missing country as unknown, not as "US". Local development and some proxies send no geo headers, and defaulting to one country silently skips the consent flow for everyone you can't place.
What it costs and where it breaks
We're not going to quote latency numbers for your app; they depend on region placement and whatever your middleware imports. The structural facts are stable. Middleware adds a compute invocation in front of every matched request, billed under fluid compute, so the matcher is your main cost control. Vercel's own docs suggest static vercel.json redirects, rewrites and has/missing conditions for anything that needs no custom code, since those run on the CDN without invoking your function. Requests through middleware are also capped: 14 KB URLs, 4 MB bodies, 64 headers and 16 KB of total header size. If you pin middleware to the edge runtime in an older Next.js, the API restrictions in edge runtime limits still apply.
Questions people ask
Is Next.js middleware deprecated?
The middleware file convention is deprecated as of Next.js 16 and renamed to proxy. You create proxy.ts at the project root and export a function named proxy (or a default export). Behavior is the same: it runs before routes render and can rewrite, redirect, set headers or respond directly. Run npx @next/codemod@canary middleware-to-proxy . to rename the file and function automatically.
Can I verify a JWT in Vercel middleware?
Yes. Use jose, which relies on Web Crypto and runs in both the Node.js and edge runtimes, to call jwtVerify on a cookie with a pinned algorithm list. Verification is local, so there is no round trip to an auth server. The tradeoff is revocation: a valid token keeps working until it expires, so keep tokens short-lived and recheck sensitive actions at the origin.
How do I run an A/B test on Vercel without flicker?
Assign the bucket in middleware before the page renders. Read a bucket cookie, assign one randomly if it's missing, and NextResponse.rewrite to a per-variant path while setting the cookie on the response. The browser URL doesn't change, returning visitors stay in their bucket, and each variant gets its own cache entry because it lives at its own path.
The call we'd make
Put the coarse decisions in middleware: is this user logged in, which bucket are they in, which region. Keep anything that needs fresh authority (permissions, billing state, session revocation for sensitive actions) at the origin. If you try to make middleware do everything, you'll either call your API from it and lose the latency win, or cache stale auth and ship a security bug. The sweet spot is narrow, and staying inside it is the whole job.
Sources
Cite this article
Kiril Urbonas (2026). Vercel Edge Middleware Patterns for Auth and A/B Testing. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/vercel-edge-middleware-patterns-auth-ab-testing
[Vercel Edge Middleware Patterns for Auth and A/B Testing](https://www.devopsness.com/blog/vercel-edge-middleware-patterns-auth-ab-testing) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from Cloud
Explore more articles in this category
Edge Databases for Low-Latency Apps: D1, Turso, Neon Serverless
Edge compute is useless without an edge data layer. Three serverless databases that put data within ms of your edge functions, with the tradeoffs that aren't on the marketing pages.
Edge Computing with AWS: CloudFront and Lambda@Edge
We use CloudFront + Lambda@Edge for specific patterns. The wins, the production gotchas, and where we hit Lambda@Edge's limits.
Azure Workload Identity Federation Without Secrets
You can remove every client secret from CI by pointing Azure federated credentials at GitHub's OIDC issuer. Here's the exact setup and the claims that trip people up.
You might have missed
Evergreen posts worth revisiting.