
Next.js Middleware Deep Dive: A/B Testing and Tenant Routing
What Middleware Is For Next.js middleware runs before a request reaches your route handler—at the edge, before any rendering. It's the right place for: Authentication checks Redirects based on user state Rate limiting A/B testing assignment Geolocation-based routing Request logging Basic Setup // middleware.ts (in root, next to app/) import { NextResponse } from ' next/server ' ; import type { NextRequest } from ' next/server ' ; export function middleware ( request : NextRequest ) { return NextResponse . next (); } // Which paths it runs on export const config = { matcher : [ ' /((?!_next/static|_next/image|favicon.ico|public/).*) ' , ], }; Authentication Middleware import { NextResponse } from ' next/server ' ; import type { NextRequest } from ' next/server ' ; import { verifyToken } from ' ./lib/auth ' ; const PUBLIC_PATHS = [ ' /login ' , ' /signup ' , ' /api/auth ' , ' / ' , ' /pricing ' ]; export async function middleware ( request : NextRequest ) { const { pathname } = request .
Continue reading on Dev.to
Opens in a new tab



