ESC

Type to search the knowledge base.

Middleware in Next.js

Next.js Middleware runs before a request completes: auth redirects, rewrites, matchers, and edge constraints.

intermediate3 min read
  • nextjs
  • middleware-in

Middleware (middleware.ts at the project root or src/) runs on the Edge before a request is completed. Use it for rewrites, redirects, headers, and lightweight auth gates — not for heavy business logic or database work.

Docs: Middleware.

Skeleton

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('session')?.value;
  if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
    const url = request.nextUrl.clone();
    url.pathname = '/login';
    url.searchParams.set('from', request.nextUrl.pathname);
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

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

Always set a matcher so static assets and _next are not processed unnecessarily.

Capabilities

Can Should not
Redirect / rewrite Full DB sessions with heavy queries (prefer shallow checks)
Read/set cookies Large JSON bodies processing
Set headers (CSP, geo experiments) Replace Server Components data loading
A/B path rewrites Complex multi-step workflows

Auth patterns

Middleware can check a session cookie exists or JWT is valid with a fast verify. Fetching full user records is often better in Server Components after the gate. Combine with auth patterns.

Edge runtime limits

Middleware runs on the Edge Runtime: limited Node APIs, smaller bundle. Prefer Web APIs (fetch, Request). See edge tradeoffs.

Debugging footguns

  • Infinite redirect loops (login page also matched).
  • Matcher too broad → performance tax on every asset.
  • Assuming Node fs works.
  • Mutating request in ways that break caching unexpectedly.

Interview out-loud

“Middleware runs on the edge before the route renders. I use it for auth redirects, rewrites, and headers with a tight matcher. Heavy data and full authorization still belong in server code after the gate. Edge API limits apply.”

Further reading

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Related guides