Middleware in Next.js

In Next.js, Middleware allows you to run logic before a request is completed, enabling powerful features like authentication, redirects, and request modifications.

🧠 How Middleware Works:

  • Middleware runs before the request reaches a page or an API route.
  • It can inspect and modify the request, perform checks (like authentication), or rewrite/redirect responses.

Example of Middleware for authentication:

javascript
1// middleware.js 2import { NextResponse } from 'next/server'; 3 4export function middleware(req) { 5 const token = req.cookies.get('token'); 6 if (!token) { 7 return new NextResponse('Unauthorized', { status: 401 }); 8 } 9 return NextResponse.next(); 10}
  • In this example, the middleware checks for a token in cookies. If it's missing, the request is blocked with a 401 response.

In short:

  • Middleware runs code before routing completes.
  • Great for auth checks, logging, redirects, and other pre-processing logic.