What is Middleware in Next.js: Explanation and Example
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.
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*'], };
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.jsormiddleware.tsfile at the root or in folders. - Use
matcherconfig to control which paths middleware applies to.