iNext Blog

article-thumbnail

Modern Middleware in Next.js 12 and Above: A Comprehensive Guide

Quick SummaryIn the latest versions of Next.js (12 and above), many developers face challenges when trying to implement middleware using the traditional approach `"/page/../_middleware.{ts, js}"`. This often results many errors.

Modern Middleware in Next.js 12 and Above: A Comprehensive Guide

In the latest versions of Next.js (12 and above), many developers face challenges when trying to implement middleware using the traditional approach "/page/../_middleware.{ts, js}". This often results many errors.

Vercel, the parent company of Next.js, has recently introduced a new method for integrating middleware into your Next.js project.

What Is Middleware?

In simple terms, middleware is a function that runs before a request is fully processed. It allows you to manipulate the response based on the incoming request by rewriting URLs, redirecting users, adding custom headers, or setting cookies.

Middleware Before Next.js 12

Previously, you could create a "_middleware.{ts, js}" file within any directory under "/pages/**". This meant that the execution of the middleware was tied to the directory where it was located.

Middleware in Next.js 12 and Beyond

With the release of Next.js 12, Vercel introduced a more streamlined method for implementing middleware. Now, you need to create a single middleware file in the root folder of your Next.js application, without using the "_" prefix. This middleware file can still have either a .ts or .js extension.

Note: The middleware defined this way will be invoked for every route in your application.

To specify which routes should use this middleware, you can utilize a custom matcher in an exported configuration object. Here's an example:

// middleware.ts

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/about')) {
    return NextResponse.rewrite(new URL('/about-2', request.url))
  }

  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.rewrite(new URL('/dashboard/user', request.url))
  }
}

Summary

  • In Next.js 12 and above, use a single middleware file in the root folder of your project.
  • Avoid using the "_" prefix in the middleware file name.
  • Middleware can no longer produce a response body for security reasons.

This new approach to middleware in Next.js offers a more structured and secure way to handle request processing in your applications.