🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Next.js Middleware: Edge Requests in Depth

Next.js BackendđŸŸĸ Free Lesson

Next.js Middleware: Edge Requests In Depth

Middleware is a single function that runs before a request is finalized — after the URL is known, before the page or route handler executes. That position makes it the right place for cross-cutting decisions: redirect anonymous users, attach a request id for tracing, rewrite legacy paths, add security headers, or pick a locale. It runs on the Edge runtime by default, close to the user, with no cold starts and no access to your database driver.

The power comes with sharp edges. Middleware executes for every matched request, so a wasteful implementation taxes your entire site. It cannot use Node APIs, so anything heavy belongs behind it. And because it can rewrite requests, a bug in middleware can expose pages you thought were private. This lesson covers the API surface, the runtime constraints, matcher patterns that keep costs sane, and patterns that are safe to run at the edge.

Prerequisites

  • !App Router project with pages and route handlers
  • !Understanding of HTTP redirects, rewrites, and headers
  • !Familiarity with cookies and authorization basics

What You'll Learn

  • 1Write middleware that redirects, rewrites, and mutates headers
  • 2Scope work with precise matcher patterns
  • 3Recognize Edge runtime limitations before they hit production
  • 4Combine middleware auth with page-level checks safely

The function and the request object

Middleware exports a function that receives a NextRequest — a superset of the standard Request with helpers for cookies, nextUrl, and geo — and returns a NextResponse. Returning nothing continues to the destination unchanged.

javascript
// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const requestId = crypto.randomUUID();
  const startTime = Date.now();

  const response = NextResponse.next();
  response.headers.set('x-request-id', requestId);
  response.headers.set('x-user-country', request.geo?.country ?? 'unknown');

  console.log(JSON.stringify({
    request_id: requestId,
    path: request.nextUrl.pathname,
    duration_ms: Date.now() - startTime,
  }));

  return response;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};

Notice what is absent: no database call, no JSON parsing of large bodies, no filesystem. Middleware should complete in single-digit milliseconds. The request id header is a small habit that pays off the moment you try to correlate an edge log line with an application log for the same user action. Logging sparingly and structurally — one JSON line per request, sampled in production — keeps the edge observability useful instead of noisy.

Rewrites, redirects, and header mutation

The three response verbs cover most needs. A redirect tells the browser to go elsewhere with a new URL. A rewrite serves different content under the same URL, which is invisible to the user and ideal for A/B tests, path versioning, and proxying. Header mutation lets you attach cookies, CSP, or feature flags to the downstream response.

javascript
// middleware.js — three jobs in one function
import { NextResponse } from 'next/server';

export function middleware(request) {
  const { pathname } = request.nextUrl;

  // 1. Redirect: permanent URL rename, visible to the browser
  if (pathname === '/docs') {
    return NextResponse.redirect(
      new URL('/documentation', request.url),
      301
    );
  }

  // 2. Rewrite: serve variant under the same URL
  const variant = request.cookies.get('ab-variant')?.value ?? 'a';
  if (pathname.startsWith('/pricing')) {
    const url = request.nextUrl.clone();
    url.pathname = `/variants/${variant}${pathname}`;
    return NextResponse.rewrite(url);
  }

  // 3. Headers: harden the response for every HTML route
  const response = NextResponse.next();
  response.headers.set(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self' https://cdn.example.com"
  );
  response.headers.set('X-Frame-Options', 'DENY');
  return response;
}

export const config = {
  matcher: ['/docs', '/pricing/:path*'],
};

A redirect to a new domain — say a marketing microsite consolidation — needs an absolute URL and a security check: never build redirect targets from user-controlled input without an allowlist, or you have built an open redirector. Rewrites, being invisible to the user, deserve the same suspicion: a rewrite pattern that can be influenced by a query parameter effectively lets callers address internal routes directly.

Matcher patterns keep the bill and latency down

Without a matcher, middleware runs on every request including static chunks and images. The matcher config takes path-to-regexp patterns, and negative lookahead is the standard way to exclude assets:

javascript
export const config = {
  matcher: [
    '/dashboard/:path*',
    '/api/private/:path*',
    '/((?!_next/static|_next/image|favicon.ico|robots.txt).*)',
  ],
};

Two practical rules: list explicit prefixes for anything protected so the intent is readable in review, and test the matcher against real URLs with the middleware matcher debugger during development. A pattern that accidentally matches _next/static adds latency to every JS chunk download for every user.

Edge runtime constraints

The Edge runtime is not Node. There is no fs, no net, no native database drivers, and many npm packages that assume Node globals will fail at build time with module resolution errors. Crypto is available through the Web Crypto API, as the request id example shows. When middleware needs something the edge cannot do — verify a JWT with a library that needs Node crypto, query Postgres — the standard shape is a cheap cookie or signature check at the edge, plus the authoritative check in the page or route handler where full Node runs.

OperationEdge middlewareNode page or route
Read cookies and headersYesYes
Redirect, rewrite, set headersYesLimited
Web Crypto (HMAC, UUID)YesYes
Database drivers (pg, Prisma native)NoYes
Filesystem accessNoYes
Heavy CPU workNo, and it blocks other requestsYes, with care

Auth and geo patterns that hold up

The most common production uses are session gating and localization. Auth middleware verifies the session cookie shape and redirects; the page still calls auth() because middleware can be misconfigured. Geo logic chooses a default locale or shows region-specific pricing, but remember that geo data is approximate and privacy-sensitive — always provide a manual override.

javascript
// middleware.js — locale detection with override cookie
import NextAuth from 'next-auth';
import { auth } from '@/auth';

const { middleware: authMiddleware } = NextAuth({ providers: [] });

const locales = ['en', 'es', 'fr'];
const defaultLocale = 'en';

export function localeMiddleware(request) {
  const { pathname } = request.nextUrl;

  const hasLocale = locales.some(
    (l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`)
  );
  if (hasLocale) return;

  const cookieLocale = request.cookies.get('locale')?.value;
  const headerLocale = request.headers
    .get('accept-language')
    ?.split(',')[0]
    ?.split('-')[0];

  const locale =
    [cookieLocale, headerLocale, defaultLocale].find((l) => locales.includes(l)) ??
    defaultLocale;

  const url = request.nextUrl.clone();
  url.pathname = `/${locale}${pathname === '/' ? '' : pathname}`;
  return NextResponse.redirect(url);
}

Order matters when combining middleware: perform auth checks before locale redirects or users bounce through unnecessary hops, and keep the combined function's matcher union tight.

Production pitfalls

The incident reports share a shape: a regex in middleware that backtracks catastrophically on crafted URLs, taking the site down at the edge. Middleware that reads the request body to authenticate, discovering too late that the stream is consumed and downstream handlers receive nothing. A debug header leaking internal user ids to every visitor because it was added during an outage and never removed. And the subtlest one — assuming a successful middleware check means the page is safe, until a route handler mounted outside the matcher serves the same data unauthenticated.

Testing middleware before it reaches production

Middleware is awkward to test because it runs outside the component tree, but the function's shape makes it more testable than its reputation suggests. Because middleware(request) receives a standard-ish Request and returns a Response, unit tests can construct both with the Request and NextResponse constructors and assert on status codes, headers, and the rewritten pathname. Matcher patterns deserve their own test file: feed the matcher a list of representative URLs — static assets, API routes, protected pages, root path — and assert which ones the config claims. This catches the classic regression where a refactor broadens the pattern and suddenly every image request pays a middleware invocation. For integration coverage, one end-to-end case per redirect rule is enough: visit the unprotected URL, assert the destination, and assert the cookie that made the rule fire. What you do not need is a browser test for every header mutation; those belong in the unit file where a failure points at a line rather than a network trace. Teams that invest an afternoon in this split see middleware refactors stop being scary, which is worth more than the marginal coverage itself.

Common Mistakes

Running database queries inside middleware

Fix: Do only what the edge can do — verify signatures, check cookie shape — and leave data access to the Node runtime in the page.

Using a broad matcher that includes _next/static

Fix: Exclude framework assets with negative lookahead or list only the protected prefixes explicitly.

Building redirect targets from unvalidated query parameters

Fix: Allowlist destination paths or hosts; anything else is an open redirect waiting to be abused.

Treating middleware auth as the only authorization layer

Fix: Repeat the check where data is read; middleware is a fast filter, not the source of truth.

Best Practices

  • Attach a request id header in middleware and log it on both sides of the boundary
  • Keep middleware functions small and compose them in a defined order
  • Profile matcher patterns against realistic URLs before each release
  • Version security header policies so changes are reviewable and reversible

Interview Questions

Q1: Why can middleware not use Prisma or pg directly?

It runs on the Edge runtime, which lacks Node APIs such as net and fs that native database drivers depend on. Use Web-safe checks at the edge and query data in the Node runtime.

Q2: What is the difference between a rewrite and a redirect?

A rewrite serves different content while the browser URL stays unchanged. A redirect returns a status code that makes the browser request a new URL, which is visible and shareable.

Q3: How do you avoid middleware latency on static assets?

Use the config matcher to exclude _next/static, _next/image, and favicon, or to include only the route prefixes that need the logic.

Key Takeaways

  • Middleware runs before the route and is the place for redirects, rewrites, headers, and cheap auth checks.
  • It executes on the Edge runtime: Web APIs yes, Node drivers and filesystem no.
  • Matcher patterns control both cost and latency — exclude assets and scope protected prefixes.
  • Keep the function fast, never read request bodies you do not need, and repeat authorization at the data layer.
  • Request ids flowing from middleware into application logs make edge incidents debuggable.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement