Middleware Is Not a Router: What We Learned Running Auth at the Edge
We treated Next.js middleware like a mini router for auth and A/B tests. It bit us on cold starts, cookie races, and session drift. Here's the pattern we settled on.
Middleware in Next.js looks like the perfect place to put auth, locale negotiation, A/B flags, and bot detection. It runs before the request hits a route, it's globally configurable, and the edge runtime promises low latency everywhere. We leaned into that promise for about eighteen months across three production apps. Here's what actually happened, and the pattern we now reach for by default.
The seductive pitch of edge middleware
On paper, middleware.ts is a dream. One file, one matcher, and every request gets normalized before your route handlers or server components see it. We used it for:
- Session validation and redirects to
/login - Feature flag cohort assignment with a cookie
- Geo-based pricing and locale redirects
- Bot filtering before expensive RSC renders
The problem is that middleware is not a router, it's a pre-flight. The mental model matters because the failure modes are different. Routers own a response. Middleware shapes a request and optionally short-circuits. When you start treating it like a router — fetching user data, hitting your DB, rendering logic — you pay for it in ways that don't show up in local dev.
The symptoms we saw first
The first signal was TTFB getting worse, not better, after we added edge middleware in front of our dashboard. We expected the opposite. Vercel's analytics showed p75 TTFB climbing by what looked like 80 – 150 ms on cold regions. We also started seeing flaky logout behavior: users would click sign-out, land on /login, then get bounced back into the app on the next navigation.
Both problems traced back to the same mistake: we were doing too much work in middleware, and we were doing it against a mental model that didn't match the runtime.
Gotcha 1: The edge runtime isn't Node
The edge runtime is a constrained V8 isolate. No fs, no native crypto beyond SubtleCrypto, no most-of-npm. We knew this. What we underestimated was how much of our auth library quietly depended on Node APIs through transitive dependencies. Our first middleware.ts compiled fine, ran fine locally with next dev, and then failed to cold-start in two regions during a Friday deploy.
The fix is boring: verify your JWTs with jose, not jsonwebtoken. Don't import your ORM. Don't import anything that touches process.env at module scope if it might not exist at the edge.
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';
const SECRET = new TextEncoder().encode(process.env.AUTH_SECRET!);
export async function middleware(req: NextRequest) {
const token = req.cookies.get('session')?.value;
if (!token) return redirectToLogin(req);
try {
const { payload } = await jwtVerify(token, SECRET, {
algorithms: ['HS256'],
});
const res = NextResponse.next();
// Pass minimal claims forward via request headers
res.headers.set('x-user-id', String(payload.sub));
return res;
} catch {
return redirectToLogin(req);
}
}
function redirectToLogin(req: NextRequest) {
const url = req.nextUrl.clone();
url.pathname = '/login';
url.searchParams.set('next', req.nextUrl.pathname);
return NextResponse.redirect(url);
}
export const config = {
matcher: ['/((?!_next|api/public|login|favicon.ico).*)'],
};
Notice what's missing: no DB call, no session lookup, no fetch to an internal service. Middleware verifies the token's signature and expiry. That's it. The actual authorization — "is this user allowed to see this org?" — happens in the route or server component where you already have your full Node runtime.
Gotcha 2: Cookies set in middleware race with navigation
This was the logout bug. When you call response.cookies.set(...) in middleware, the cookie is attached to that response. But if the client-side router has already prefetched the next route, or if a server action is in flight, you can end up in a state where the browser has the new cookie but the in-flight RSC payload was rendered with the old one. The user sees stale UI, clicks something, and the server rejects it — or worse, re-authenticates them.
The mitigation is to treat any cookie mutation that changes auth state as a hard navigation boundary. In practice:
- Never mutate the session cookie in middleware on a GET that returns
NextResponse.next(). Only mutate it on redirects or explicit sign-in/sign-out routes. - For logout, return a redirect with
Clear-Site-Data: "cookies"on supported browsers and bust the router cache withrouter.refresh()on the client after the redirect lands. - Keep the cookie read in middleware purely for checking state, not changing it.
The matcher trap
The matcher config looks like a path filter. It's actually a build-time regex that Next.js compiles into the edge function's invocation rules. Two things we got wrong:
- We under-excluded. Our first matcher ran on
/_next/imageand prefetch requests, which multiplied invocations by ~4x. Every hover on a<Link>was hitting our JWT verify path. - We over-excluded. When we added public marketing pages, we excluded
/marketing/*, which meant our locale redirect stopped firing there. Users landed in the wrong language.
The cleanest pattern we've landed on: one matcher per concern, split across multiple logical branches inside a single middleware.ts, because Next.js only allows one middleware file.
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (isPublic(pathname)) return handleLocale(req);
if (isAuthCallback(pathname)) return NextResponse.next();
return handleAuth(req);
}
Gotcha 3: Observability gets worse before it gets better
Edge middleware runs in regions you don't fully control, in a runtime where your usual logger probably doesn't work. console.log works, but it's unstructured and sampled. We lost a week debugging a redirect loop because our logs from middleware and our logs from the route handler were in different dashboards with different timestamps.
What worked:
- Emit a single structured log line per middleware invocation with a request ID (generate it with
crypto.randomUUID()and forward it viax-request-id). - Propagate that ID into RSC via response headers and into server actions via a cookie or header.
- Sample aggressively. Edge middleware fires on every request. Logging 100% will eat your log budget before lunch.
Gotcha 4: Middleware is not free, even when it returns next()
There's a myth that NextResponse.next() is a no-op. It isn't. The edge function still cold-starts, still runs your imports, still awaits your jwtVerify. On a warm invocation we measured single-digit milliseconds. On a cold region invocation it was consistently higher — enough to matter for LCP on a landing page.
If your middleware is only relevant to authenticated routes, exclude everything else from the matcher. If you need it on public routes for something lightweight (geo, A/B), split the concern and consider doing it in a server component with the headers() API instead. For the auth-adjacent work, our rule is now: middleware only runs on paths that genuinely need a pre-flight check.
The pattern we ship now
After three rewrites, here's the shape we default to:
- Middleware does signature verification and nothing else. No DB, no fetch, no feature flag evaluation that requires remote config.
- Authorization lives in a server-side
requireUser()helper called at the top of layouts or server actions. It has full Node runtime, our ORM, and our audit logger. - Feature flags resolve in a root server component, not in middleware. We forward the cohort via a cookie set on the sign-in redirect, so steady-state navigation doesn't re-evaluate.
- Locale negotiation stays in middleware, because it's genuinely a redirect concern and the logic is trivial (
Accept-Languageparsing, no network). - Bot filtering moved to the CDN layer, not middleware. Your edge provider almost certainly does this better than you will.
This split keeps middleware under ~30 lines, keeps the edge bundle tiny, and keeps the interesting logic in a runtime where you can actually debug it.
Where we'd start
If you're inheriting a Next.js app with a 300-line middleware.ts, don't rewrite it on day one. Instead:
- Add structured logging with a request ID and run it for a week. Find out what middleware is actually doing on real traffic.
- Audit the matcher. Count invocations per path. You will find surprises.
- Move anything that fetches remote data out of middleware and into a server component or route handler.
- Keep JWT verification, locale redirects, and hard auth gates. Delete the rest.
If you want a second pair of eyes on an App Router migration or an edge-runtime audit, our team does this work day in and day out — see how we approach Next.js builds. Middleware is a sharp tool. Treat it like one, and it earns its keep. Treat it like a router, and it will quietly cost you both milliseconds and sleep.
Want a team like ours?
72Technologies builds production software for the kind of teams who actually read this blog.
Start a projectKeep reading
The Hidden Cost of `revalidateTag` at Scale: A Cache Invalidation Post-Mortem
We treated `revalidateTag` like a magic eraser. Then a product import triggered 40,000 simultaneous regenerations and took down our listing pages. Here's what we got wrong about Next.js tag-based invalidation and how we rebuilt it.
Why Our React Server Component Payloads Doubled After a 'Harmless' Refactor
A quiet refactor pushed our RSC payload from 180KB to 410KB on a single route. Here's how we found it, why it happened, and the serialization rules we now enforce in CI.
React 19's useOptimistic Is a Trap If You Don't Model Failure First
useOptimistic feels like free UX magic until a server action fails in ways you didn't plan for. Here's the mental model we wish we'd had before shipping it to production.
