今日已更新 135 条资讯 | 累计 24421 条内容
关于我们

Next.js Middleware in 2026: Auth Guards, A/B Tests, and What Belongs at the Edge

Ahmed Mahmoud 2026年07月27日 05:03 2 次阅读 来源:Dev.to

Headline: Next.js Middleware (middleware.ts at the project root) runs before every matched request — before cache, before rendering, before the route. That position makes it right for auth redirects, A/B cookie bucketing, and locale detection. Wrong for database queries and heavy imports. In 2026, Middleware on Vercel runs on Fluid Compute (standard Node.js), so the constraint is latency budget, not API availability. Key takeaways Middleware runs before every matched request — before cache, rendering, or route handler — the right layer for auth, locale, and A/B bucketing. Middleware can read requests, set cookies, redirect, rewrite, or return early — without the route running. DB queries and large packages add latency to every request. On Vercel in 2026, Middleware runs on Fluid Compute (standard Node.js). The constraint is latency: every added millisecond is paid on every matched request. Use matcher to scope Middleware to only the routes that need it; without it Middleware runs on every static asset request. Auth in Middleware = verifying a self-contained JWT without a DB call. Full session validation belongs in the route. I spent a long time only using Middleware for locale redirects. After shipping auth-protected routes and an A/B test, the full shape became clear. What is Next.js Middleware and where does it run? Middleware is exported from middleware.ts at the project root. It intercepts matched requests before route resolution, cache lookup, and Server Component execution. Returns one of four types: pass through ( NextResponse.next() ), redirect, rewrite (serve different content while keeping original URL in address bar), or a direct response. export function middleware ( request : NextRequest ) { return NextResponse . next (); } export const config = { matcher : [ ' /((?!_next/static|_next/image|favicon.ico).*) ' ], }; Without matcher , Middleware runs on every request including static files. On Vercel in 2026, Middleware runs on Fluid Compute — standard Nod

本文内容来源于互联网,版权归原作者所有
查看原文