Next.js Middleware

Middleware allows you to run code before a request is completed. Based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.

Next.js Middleware runs extremely fast because it executes on the Edge Network (Vercel Edge functions) inherently, meaning it runs incredibly close to the user geographically.

Creating Middleware

To create middleware, create a file named exactly middleware.js (or .ts) at the root of your project (in the same folder holding app or pages).

// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  // If user visits /legacy-url, redirect them to /new-url
  if (request.nextUrl.pathname.startsWith('/legacy-url')) {
    return NextResponse.redirect(new URL('/new-url', request.url));
  }

  // Otherwise, let the request proceed normally
  return NextResponse.next();
}

// Ensure the middleware only runs for specific paths!
export const config = {
  matcher: ['/legacy-url/:path*', '/dashboard/:path*'],
};

Use Cases for Middleware

1. Authentication & Authorization

Middleware is the perfect place to check if a user is logged in. If they are trying to access /admin/settings but have no secure session cookie, you can redirect them to /login immediately before the server even begins rendering the admin page.

2. A/B Testing & Rewrites

You can route half of your users to one marketing page design, and half to another, without changing the URL shown in their browser (Rewrite).

export function middleware(request) {
  if (request.nextUrl.pathname === '/marketing') {
    const random = Math.random();
    
    // Rewrites keep the URL the same, but fetch different code
    if (random < 0.5) {
      return NextResponse.rewrite(new URL('/marketing/version-a', request.url));
    } else {
      return NextResponse.rewrite(new URL('/marketing/version-b', request.url));
    }
  }
}

3. Geo-location Features

Middleware automatically injects geographic data (like country, city, and region) into the request object. You can use this to route users to localized versions of your site (e.g. /en-us vs /en-uk).

Limitations

Because Middleware runs on the Edge Runtime (not Node.js), you cannot use native Node.js libraries (like fs, mongoose, or bcrypt) inside of it unless they specifically support Edge computing.

Conclusion

Middleware provides powerful protection and routing capabilities before hitting your main app logic. In our next section, we’ll learn how to keep backend secrets safe using Environment Variables.