Skip to content

Lesson 8 of 9 · 24m

Middleware, Edge Runtime, and Their Limits

Middleware is a request filter, not a second application server: use it for rewrites, redirects, and cheap auth gates while understanding runtime and latency constraints.

Middleware sits before routing and can rewrite, redirect, mutate headers, or reject a request. That position is powerful and dangerous. Every request pays for it, including static assets unless you configure the matcher carefully. Teams that treat middleware as a convenient place to put business logic end up with a distributed, hard-to-debug second backend running on the edge.

What middleware is good at

// middleware.ts
import { NextResponse, type NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const session = request.cookies.get("session")?.value;

  if (!session && request.nextUrl.pathname.startsWith("/console")) {
    const login = new URL("/login", request.url);
    login.searchParams.set("next", request.nextUrl.pathname);
    return NextResponse.redirect(login);
  }

  return NextResponse.next();
}

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

Cheap gatekeeping, locale redirects, canonical host normalization, experiment assignment cookies, security headers — these fit. They are bounded, fast, and do not need deep application state.

What middleware is bad at

  • Full session validation against a primary database.
  • Large authorization policy engines.
  • Parsing request bodies.
  • Complex business workflows.
  • Anything that needs Node-only libraries in an edge runtime.

Edge middleware often runs in a lightweight runtime without the full Node API surface. The exact capability depends on deployment platform and runtime selection. Assume constrained unless proven otherwise.

The example above is a UX gate, not a security boundary. It redirects obvious unauthenticated users, but it does not prove the session is valid. Server components, route handlers, and server actions must still validate the session authoritatively.

That sounds redundant until middleware is bypassed by a matcher mistake, a new route is added outside the matcher, or a cached payload is accessed through a path you did not expect. Defense in depth is not optional here.

Matcher mistakes are production incidents

The common negative regex matcher that excludes only api, static assets, images, and favicon.ico means "almost everything." If your middleware does even 20 milliseconds of work, you just taxed every page view. Worse, a memory-heavy middleware can become the bottleneck before your application servers notice traffic.

Prefer explicit prefixes. Review matcher changes with the same care as firewall rules.

Runtime confusion shows up as dependency errors

A middleware import chain that reaches jsonwebtoken, bcrypt, or a database driver may fail because those libraries rely on Node primitives. Use edge-safe token verification where appropriate, or keep verification in server code and use middleware only for coarse routing.

Field notes

  • Middleware cannot see the final rendered page. Do not use it to make decisions that depend on page data.
  • Rewrites hide URLs from the browser; redirects change them. Choose deliberately for SEO, analytics, and supportability.
  • Geolocation and IP headers are platform-specific. Test the deployed environment, not just local development.
  • Middleware ordering is outside the normal route tree. Log decisions at debug level with request IDs so production behavior is reconstructable.

Was this lesson helpful?

Sign in to rate