Middleware file in Next.js

Tiempo de lectura: < 1 minuto

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.

Here are some things you can do with middleware in Next.js:

  1. Cookie handling: You can read, modify, or set cookies on incoming requests.
  2. Redirects: You can redirect users to different routes based on certain conditions.
  3. Authentication: You can check if a user is authenticated and, if not, redirect them to a login page.
  4. 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) {
  // Redirects unauthenticated users to the login page
  if (!req.cookies.get('auth')) {
    return NextResponse.redirect('/login')
  }
}

This middleware checks if an authentication cookie exists in the request. If it doesn’t exist, it redirects the user to the login page.

Leave a Comment