Lesson 15 of 15 · 4 min
Middleware in Next.js
Run code before a request reaches your Next.js pages: protect routes, redirect and rewrite URLs, set headers and cookies, and limit middleware to…
On this page
Introduction:
Sometimes you need to do something with a request before Next.js renders a page. Maybe a visitor who is not logged in should be sent to the login page, an old URL should redirect to a new one, or every response needs a security header. You could repeat that logic in every page, but Next.js gives you a single place for it: middleware.
Middleware is a function that runs on the server for every matching request. It can look at the URL, headers and cookies, and then decide to let the request continue, redirect it, rewrite it to a different page, or respond directly.
Note on naming: in Next.js 16 the middleware file was renamed from middleware.js to proxy.js, and the exported function from middleware to proxy. The way it works is the same. This lesson uses the new name and shows the older one in comments, so you can follow along on any recent version.
1. Creating Middleware:
Create a file called proxy.js (or middleware.js before Next.js 16) in the root of your project, next to the app or pages folder (inside src if you use a src directory). There is only one such file per project.
// proxy.js (Next.js 16+)
// middleware.js with "export function middleware" in Next.js 15 and earlier
import { NextResponse } from "next/server";
export function proxy(request) {
console.log("Request to:", request.nextUrl.pathname);
return NextResponse.next(); // let the request continue as normal
}
NextResponse.next() means “carry on”. The console.log output appears in your terminal, not in the browser, because this code runs on the server.
2. Choosing Which Paths Run Middleware:
By default middleware runs for every request, including images and JavaScript files. Usually you only want it for certain pages. Export a config object with a matcher:
export const config = {
// Run only for the dashboard and account pages
matcher: ["/dashboard/:path*", "/account/:path*"],
};
:path* means “this path and anything below it”, so /dashboard, /dashboard/settings and /dashboard/settings/profile all match.
You can also check the path inside the function:
export function proxy(request) {
if (request.nextUrl.pathname.startsWith("/admin")) {
// admin-only logic here
}
return NextResponse.next();
}
3. Protecting Routes (Authentication):
The most common use of middleware is to stop logged-out users from reaching private pages. Here we check for a session cookie and redirect to /login if it is missing. We also remember where the user was going, so the login page can send them back afterwards.
// proxy.js
import { NextResponse } from "next/server";
export function proxy(request) {
const token = request.cookies.get("session")?.value;
if (!token) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("from", request.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};
Important: middleware is a fast first check, not your only line of defence. Still verify the user inside your pages, API routes and server actions before you read or change private data.
4. Redirects:
A redirect tells the browser to go to a different URL, and the address bar changes. This is useful when you move or rename pages:
export function proxy(request) {
if (request.nextUrl.pathname === "/old-blog") {
return NextResponse.redirect(new URL("/blog", request.url), 308);
}
return NextResponse.next();
}
Status 308 is a permanent redirect, which tells search engines to update their links. Use 307 for a temporary one. For a fixed list of simple redirects, the redirects option in next.config.js is even simpler; reach for middleware when the decision depends on the request, such as a cookie or a header.
5. Rewrites:
A rewrite shows the content of a different page without changing the URL in the address bar. A classic example is A/B testing: half of your visitors see a new home page, but everyone still sees / in the address bar.
import { NextResponse } from "next/server";
export function proxy(request) {
let bucket = request.cookies.get("bucket")?.value;
if (!bucket) bucket = Math.random() < 0.5 ? "a" : "b";
const response = bucket === "b"
? NextResponse.rewrite(new URL("/home-new", request.url))
: NextResponse.next();
// Remember the bucket so the visitor keeps seeing the same version
response.cookies.set("bucket", bucket, { maxAge: 60 * 60 * 24 * 30 });
return response;
}
export const config = {
matcher: ["/"],
};
6. Setting Headers and Cookies:
Middleware can add headers to every response, for example security headers:
import { NextResponse } from "next/server";
export function proxy(request) {
const response = NextResponse.next();
response.headers.set("X-Frame-Options", "DENY");
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
return response;
}
You can read cookies with request.cookies.get(name), set them with response.cookies.set(name, value) and remove them with response.cookies.delete(name).
7. Responding Directly:
Middleware can also answer a request itself, without ever reaching a page. For example, you could block requests to an API that are missing an API key:
export function proxy(request) {
if (request.nextUrl.pathname.startsWith("/api/private")) {
const key = request.headers.get("x-api-key");
if (key !== process.env.PRIVATE_API_KEY) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
}
return NextResponse.next();
}
8. Tips for Good Middleware:
- Keep it fast. Middleware runs before every matching request, so avoid slow database queries in it. Reading a cookie or a header is ideal.
- Use a matcher. Skip static files and images so you do not slow them down.
- One file, many jobs. Since there is only one middleware file, split larger logic into small helper functions and call them from it.
- Do not rely on it alone for security. Check permissions again where the data is used.
Conclusion:
Middleware lets you run code before a request reaches your pages. You learned how to create the middleware file (proxy.js in Next.js 16, middleware.js before that), limit it with a matcher, protect private routes, redirect and rewrite URLs, set headers and cookies, and respond directly. Together with API routes and ISR, this gives you the main server-side tools you need to build a complete Next.js application.
More from Next.js Tutorial
- Lesson 1 · 4 minIntroduction“Discover Next.js, the future of web development. Explore its powerful features, benefits, and how it revolutionizes the way we build web…
- Lesson 2 · 3 minInstallation and setupDiscover Next.js: Learn how to install, set up, and create your first Next.js app with organized file structures and conventions
- Lesson 3 · 3 minNavigation Pages in Next.jsMaster Next.js routing: Create dynamic routes, link between pages, and explore a real-world example for seamless navigation.