Skip to content

Next.js Middleware Explained — Request Interception

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Next.js Middleware Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Next.js middleware runs on every request before matching routes, enabling authentication checks, redirects, header manipulation, geolocation-based routing, and A/B testing.

What You'll Learn

  • Middleware file structure
  • Config matcher for route filtering
  • Authentication checks
  • Geolocation-based redirects
  • Header and cookie manipulation

Why It Matters

Middleware executes at the edge (CDN), providing fast, global request processing without running server code. It is essential for auth, localization, and feature flags.

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

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

  // Protected routes
  if (pathname.startsWith("/dashboard") && !token) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  // Guest-only routes (login, register)
  if (pathname.startsWith("/login") && token) {
    return NextResponse.redirect(new URL("/dashboard", request.url));
  }

  // Geolocation-based routing
  const country = request.geo?.country || "US";
  const response = NextResponse.next();
  response.cookies.set("country", country);

  // Add security headers
  response.headers.set("X-Frame-Options", "DENY");
  response.headers.set("X-Content-Type-Options", "nosniff");

  return response;
}

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

Expected output: Middleware runs on matching routes, redirects unauthenticated users, sets country cookie, and adds security headers.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro