To set up Edge Middleware in Next.js, follow these steps:
-
Create a Middleware Function: Define your middleware function that processes each request.
-
Define Route Matching with Config: Use the
configobject to specify which routes should trigger this middleware. Thematcherproperty can be a single path or a regex for more complex routing. -
Extract Geo and IP Data: Access the client's location using
request.geo.countryor their IP address via helper functions likeipAddress(). Default values ensure you don't encounter undefined errors. -
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.
- Use
-
Handle Async Operations: Utilize
waitUntil()from theRequestContextfor async tasks like database calls, ensuring proper handling of asynchronous operations. -
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',
};