Middleware in Next.js runs before a request reaches a page or an API route. That makes it a good place for checks you want on every request: is this user logged in, is this client hammering the API, should this response be cached. It also makes it easy to slow every request down, so it is worth knowing what belongs there and what does not.

Note: Next.js 16 renamed Middleware to Proxy. The file is now proxy.ts and the function is proxy, but it works the same way. The examples below use the older middleware.ts name.

A first middleware

Create middleware.ts (or .js) next to your app or pages folder:

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

export function middleware(req: NextRequest) {
  console.log("Middleware ran for:", req.nextUrl.pathname);
  return NextResponse.next(); // carry on to the requested page
}

Without a matcher, this runs on every request, including images and static files. That is rarely what you want. Tell it which paths to care about:

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

Keeping logged-out users away from admin pages

A cookie check is enough to send someone without a session to the login page:

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

  if (!token && req.nextUrl.pathname.startsWith("/admin")) {
    return NextResponse.redirect(new URL("/login", req.url));
  }

  return NextResponse.next();
}

This only checks that the cookie exists. It does not prove the token is valid, so the admin pages and their API routes still need to verify the session themselves. Treat middleware as the first gate, not the only one.

Setting cache headers

You can add a Cache-Control header to responses on the way out:

export function middleware(req: NextRequest) {
  const res = NextResponse.next();

  if (req.nextUrl.pathname.startsWith("/api/public")) {
    res.headers.set("Cache-Control", "public, max-age=3600");
  }

  return res;
}

Be careful about where this applies. A public header on a page that shows a logged-in user's data lets a CDN serve one person's page to someone else. Limit it to responses that are the same for everyone.

Rate limiting an API

The simplest version remembers when each IP last made a request and turns it away if it comes back too soon:

const lastRequest = new Map<string, number>();

export function middleware(req: NextRequest) {
  const ip = req.headers.get("x-forwarded-for")?.split(",")[0] ?? "unknown";
  const now = Date.now();
  const previous = lastRequest.get(ip);

  if (previous && now - previous < 5000) {
    return new Response("Too many requests", { status: 429 });
  }

  lastRequest.set(ip, now);
  return NextResponse.next();
}

req.ip was removed from NextRequest in Next.js 15, so the IP comes from the x-forwarded-for header your host sets. This works on a single server. On Vercel or any setup with more than one instance, each instance has its own Map, so the limit leaks. For real traffic, keep the counters in a shared store such as Redis or Upstash.

What I would keep out of middleware

Middleware runs on every matched request, so anything slow there is slow everywhere. I keep it to quick checks on the request itself: cookies, headers and the path. Database lookups, full session validation and anything that calls another service belong in the route or the page.