Next.js Middleware Patterns I Use in Every Production Application
Next.js middleware runs at the edge before every matched request hits your application. It can rewrite URLs, redirect requests, set headers, and return responses — all with sub-millisecond latency because it runs on edge infrastructure close to users.
I use middleware in every production Next.js application. Here are the patterns that have proven valuable repeatedly.
Pattern 1: Authentication Gate
The most common middleware pattern: protecting routes that require authentication.
Instead of checking authentication in every page component (repetitive and error-prone), middleware intercepts requests to protected routes and redirects unauthenticated users to the login page.
The implementation: check for a session cookie or JWT token. If present and valid, allow the request to continue. If missing or expired, redirect to /login with a returnUrl parameter so the user returns to their intended page after authenticating.
The key consideration: middleware runs on the edge with limited runtime capabilities. You cannot make database queries (no database drivers in the edge runtime). For JWT-based auth, you can validate the token signature and expiration directly in middleware. For session-based auth, you need a session store accessible from the edge (like a Redis-based session with HTTP validation, or an encrypted cookie that contains the session data).
Our approach at AIDToolStack: we use Clerk for authentication. Clerk provides middleware that validates the session cookie at the edge without a database round-trip. The cookie contains a signed JWT with basic user info (ID, subscription tier). Detailed user data is fetched server-side only when needed.
Routes we protect: /account, /control (admin panel), /api routes that modify data. Routes we do not protect: the homepage, tool pages, blog posts — these are public.
Pattern 2: Smart Redirects
Middleware handles URL redirects more efficiently than Next.js config redirects because you can apply logic:
Redirect www to non-www (or vice versa): check the host header and redirect if it includes www.
Redirect HTTP to HTTPS: check the x-forwarded-proto header and redirect if it is not https.
Redirect old URLs to new URLs: when you restructure your URL scheme, middleware handles the mapping without maintaining a giant list in next.config.
Redirect based on user state: if a user is already authenticated and visits /login, redirect them to /account. If a user visits a Pro feature without a Pro subscription, redirect them to /pricing.
The advantage over static redirects: middleware redirects can be conditional, dynamic, and based on request context (cookies, headers, geo data). Static redirects in next.config are fixed patterns.
Pattern 3: Feature Flags at the Edge
Feature flags traditionally require: a feature flag service call, database lookup, or environment variable check inside your server components. This adds latency to every request.
Middleware approach: set a cookie or header indicating which features are enabled for this user. Then server components and client components read the cookie directly — no additional service calls.
Implementation: on the first request (no feature flag cookie exists), middleware decides which features to enable based on: user ID (percentage-based rollout), geographic location (features available in certain regions), or random assignment (A/B testing).
It sets a cookie with the feature flag values. On subsequent requests, the cookie already exists, so middleware passes through without computation. Feature flag decisions are made once and cached on the client.
We use this for: gradual rollouts of new features (enable for 10% of users, then 50%, then 100%), geographic features (showing local pricing based on country), and A/B testing UI changes.
Pattern 4: Geo-Based Routing
Vercel and other edge platforms provide geographic information in the request: country, city, region. Middleware can use this for:
Content localization: serve different content based on the user's country. Not full i18n (that is heavier), but showing prices in local currency, adjusting date formats, or displaying region-specific announcements.
Compliance routing: serve different privacy policies or consent banners based on whether the user is in the EU (GDPR), California (CCPA), or elsewhere.
Regional blocking: if your service is not available in certain countries (licensing, legal restrictions), middleware can redirect those users to an explanatory page.
Our usage: we display tool pricing in the user's local currency (detected by geo) and show GDPR cookie consent banners only for EU visitors.
Pattern 5: Bot Detection and Crawl Budget Optimization
Search engine crawlers, AI scrapers, and bots generate significant traffic. Middleware can identify and handle them differently:
Identify bots: check the User-Agent header for known bot signatures (Googlebot, Bingbot, GPTBot, Claude-Web).
Serve optimized content: for known crawlers, you might skip expensive personalization, disable analytics scripts, or serve cached versions of pages.
Block unwanted bots: some AI scrapers aggressively crawl your entire site. Middleware can check robots.txt compliance and block scrapers that ignore it. Or rate-limit aggressive crawlers to protect your server.
Log crawl activity: track which bots visit which pages for SEO insights. Understanding Google's crawl patterns helps you optimize your site structure.
Pattern 6: Request Headers for Downstream Use
Middleware can set custom headers that server components and API routes read:
User context headers: x-user-id, x-user-tier (extracted from the auth token in middleware). Downstream code reads these instead of re-parsing the auth token.
Request metadata: x-country (from geo lookup), x-request-id (generated UUID for tracing), x-feature-flags (computed in middleware).
This pattern avoids redundant computation. Parse the auth token once in middleware, propagate user info via headers, and every downstream handler has instant access without re-parsing.
Performance Considerations
Middleware runs on every matched request. Keep it fast:
Avoid external API calls in middleware. Each request adds latency. If you must make an API call, cache the result in a cookie or use background revalidation.
Match routes specifically. Use the matcher config to limit middleware to routes that need it. Do not run authentication checks on static assets or public pages.
Keep the middleware bundle small. Edge runtime has bundle size limits. Do not import large libraries. Use lightweight JWT validation (jose library) instead of heavy auth frameworks.
Measure middleware latency. Add timing headers (x-middleware-duration) to track how long your middleware adds to each request. It should be under 5ms for most patterns.
The Matcher Configuration
Configure which routes trigger your middleware:
We match: all routes under /account, /control, and /api (except public API routes). We exclude: static files (/_next/static), images (/_next/image), public assets (/favicon.ico, /logos/), and the login/signup pages themselves (to avoid redirect loops).
The matcher syntax supports patterns: '/account/:path*' matches all routes under /account. Use an array of patterns for multiple route groups.
Common Mistakes
Redirect loops: middleware redirects to a page that also triggers middleware, which redirects again. Always exclude the redirect target from middleware matching.
Cookie size limits: browsers limit cookies to about 4KB. Do not store too much data in cookies set by middleware. Use cookies for flags and IDs, not large payloads.
Edge runtime limitations: no Node.js APIs (fs, crypto from Node — use Web Crypto instead), no database drivers, limited npm packages. Test your middleware locally with next dev to catch these issues early.
Middleware is one of the most powerful features in Next.js for production applications. Use it wisely — for cross-cutting concerns that apply to many routes — and keep it fast.
Written by AIDToolStack Editorial
The AIDToolStack editorial team reviews developer tools, AI products, and MCP servers with hands-on testing and honest assessments. We use the tools we review every day in production.
References & Further Reading
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.