Today I’m going to explain and provide an example of middleware in Next.js

A middleware in Next.js is a function that runs before a request reaches your Next.js route or API. You can use middleware to handle and manipulate incoming requests.
Cookie Management: You can read, modify, or set cookies in incoming requests. Redirects: You can redirect users to different paths based on certain conditions. Authentication: You can check if a user is authenticated and, if not, redirect them to a login page. Request Modification: You can modify incoming requests, for example, by adding headers or changing the request method.
A middleware in Next.js is defined as an exported function (default or named) in a file in the pages/_middleware
folder or if you want it to affect the entire app, in the src root folder named middleware. This function receives a NextRequest
object and should return a NextResponse
object or void
.
Middleware Example
import { NextRequest, NextResponse } from 'next/server' export function middleware(req: NextRequest) { // Redirige a los usuarios no autenticados a la página de inicio de sesión if (!req.cookies.get('auth')) { return NextResponse.redirect('/login') } }
This middleware checks if an authentication cookie exists in the request. If it does not exist, it redirects the user to the login page.
