---
title: "Middleware in Next.js"
url: https://khanwaseem.com/blog/course/middleware-in-next-js
author: "khan Waseem"
published: 2026-11-22
updated: 2026-11-22
topics: ["course", "Nextjs Tutorial"]
description: "Run code before a request reaches your Next.js pages: protect routes, redirect and rewrite URLs, set headers and cookies, and limit middleware to the paths you need."
---

# Middleware in Next.js

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)[1. Creating Middleware:](#1-creating-middleware)
- [2. Choosing Which Paths Run Middleware:](#2-choosing-which-paths-run-middleware)
- [3. Protecting Routes (Authentication):](#3-protecting-routes-authentication)
- [4. Redirects:](#4-redirects)
- [5. Rewrites:](#5-rewrites)
- [6. Setting Headers and Cookies:](#6-setting-headers-and-cookies)
- [7. Responding Directly:](#7-responding-directly)
- [8. Tips for Good Middleware:](#8-tips-for-good-middleware)

- [Conclusion:](#conclusion)

## 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.

```javascript
// 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
}Code language: JavaScript (javascript)
```

`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`:

```javascript
export const config = {
  // Run only for the dashboard and account pages
  matcher: ["/dashboard/:path*", "/account/:path*"],
};Code language: JavaScript (javascript)
```

`: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:

```javascript
export function proxy(request) {
  if (request.nextUrl.pathname.startsWith("/admin")) {
    // admin-only logic here
  }
  return NextResponse.next();
}Code language: JavaScript (javascript)
```

### 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.

```javascript
// 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*"],
};Code language: JavaScript (javascript)
```

**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:

```javascript
export function proxy(request) {
  if (request.nextUrl.pathname === "/old-blog") {
    return NextResponse.redirect(new URL("/blog", request.url), 308);
  }
  return NextResponse.next();
}Code language: JavaScript (javascript)
```

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.

```javascript
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: ["/"],
};Code language: JavaScript (javascript)
```

### 6. Setting Headers and Cookies:

Middleware can add headers to every response, for example security headers:

```javascript
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;
}Code language: JavaScript (javascript)
```

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:

```javascript
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();
}Code language: JavaScript (javascript)
```

### 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.

### Related posts:

[JavaScript and Cookies](https://blog.khanwaseem.com/javascript-and-cookies/)
[React Redux](https://blog.khanwaseem.com/react-redux/)
[API Routes in Next.js](https://blog.khanwaseem.com/api-routes-in-next-js/)
[CSS – Table](https://blog.khanwaseem.com/css-table/)

Powered by [YARPP](https://yarpp.com).
