0
0
NextjsConceptBeginner · 4 min read

What is Middleware in Next.js: Explanation and Example

In Next.js, middleware is a special function that runs before a request reaches a page or API route. It lets you modify the request or response, like redirecting users or adding headers, helping control access and behavior globally or for specific routes.
⚙️

How It Works

Middleware in Next.js acts like a gatekeeper for your web app. Imagine you have a security guard who checks everyone before they enter a building. Middleware checks every request before it reaches your page or API. It can decide to let the request continue, redirect it somewhere else, or even block it.

This happens on the server side, so it runs fast and can handle things like authentication, localization, or logging. Middleware runs on every request that matches its path, giving you a chance to change the request or response early.

💻

Example

This example shows middleware that redirects users to a login page if they are not authenticated.

javascript
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('token');
  const url = request.nextUrl.clone();

  if (!token && url.pathname !== '/login') {
    url.pathname = '/login';
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*'],
};
Output
When a user tries to access any route under /dashboard without a 'token' cookie, they are redirected to /login. Otherwise, the request proceeds normally.
🎯

When to Use

Use middleware in Next.js when you want to run code before a request reaches your page or API. Common uses include:

  • Checking if a user is logged in and redirecting if not
  • Setting language preferences based on user location
  • Adding security headers to responses
  • Logging or analytics before handling requests

Middleware is great for tasks that apply to many routes and need to happen early in the request process.

Key Points

  • Middleware runs before pages or API routes in Next.js.
  • It can modify requests, responses, or redirect users.
  • Middleware runs on the Edge Runtime for fast performance.
  • You define middleware in a middleware.js or middleware.ts file at the root or in folders.
  • Use matcher config to control which paths middleware applies to.

Key Takeaways

Middleware in Next.js runs before requests reach pages or APIs to control behavior early.
It is useful for authentication, redirects, localization, and adding headers.
Middleware runs on the Edge Runtime for fast, scalable handling.
You can target specific routes using the matcher configuration.
Middleware helps keep your app secure and organized by centralizing request logic.