CPCODELAB
Next.js

Middleware

8 min read

Running Code Before Every Request

Middleware runs at the Edge before a request reaches your pages or API routes. It is defined in src/middleware.ts (or middleware.ts at the project root). Use it for authentication guards, locale redirects, A/B testing, and request logging.

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

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

  const isAuthRoute = req.nextUrl.pathname.startsWith("/admin");

  if (isAuthRoute && !token) {
    const loginUrl = new URL("/login", req.url);
    loginUrl.searchParams.set("from", req.nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

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

The matcher config restricts which paths the middleware runs on. Without a matcher it runs on every request, which can slow down static asset delivery.

Middleware runs in the Edge Runtime, which is a restricted environment — it does not have access to Node.js APIs like fs, crypto, or most npm packages. Keep middleware logic lightweight.

Ready to test yourself?
Practice Next.js— quiz & coding exercises