Home ci 38. functions / edge-middleware: middleware api

38. functions / edge-middleware: middleware api

Last updated on Aug 05, 2025

To set up Edge Middleware in Next.js, follow these steps:

  1. Create a Middleware Function: Define your middleware function that processes each request.

  2. Define Route Matching with Config: Use the config object to specify which routes should trigger this middleware. The matcher property can be a single path or a regex for more complex routing.

  3. Extract Geo and IP Data: Access the client's location using request.geo.country or their IP address via helper functions like ipAddress(). Default values ensure you don't encounter undefined errors.

  4. Modify Responses Using Helpers:

    • Use NextResponse.rewrite() to redirect requests based on conditions.
    • Continue middleware chains with NextResponse.next() to add headers and pass control to subsequent middlewares or handlers.
  5. Handle Async Operations: Utilize waitUntil() from the RequestContext for async tasks like database calls, ensuring proper handling of asynchronous operations.

  6. Implement No-Op for Empty Handling: If no action is needed, return a simple response using NextResponse.next() to maintain request flow without altering content.

Example Implementation:

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

export default function middleware(request: NextRequest) {
  const country = (request.geo?.country || 'US');
  console.log(`Visitor from ${country}`);

  if (country === 'SE') {
    return NextResponse.rewrite('/login');
  }
  
  return NextResponse.rewrite('/secret-page');
}

Config Object:

export const config = {
  matcher: '/secret-page',
};