API Middlewares
Middleware in Next.js lets you run code before a request is completed. You can modify the response, redirect, rewrite URLs, or set headers based on the incoming request.
Think of middleware as a security guard at the entrance of your building. It checks each visitor before they enter, ensuring they have the right credentials or directing them to the appropriate place.
Creating Middleware
To create middleware, you add a middleware.js file at the root of your project. This file exports a middleware function that runs on every request matching your configuration.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
// Run on every request
console.log('Request:', request.url);
// Continue with the request
return NextResponse.next();
}
export const config = {
matcher: '/api/:path*',
};
The matcher configuration tells Next.js which routes should trigger the middleware.
Common Middleware Patterns
Here are some practical middleware patterns:
Authentication: Check for valid tokens before allowing access to protected routes.
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('auth-token');
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
Rate limiting: Limit how often users can access certain endpoints.
const rateLimit = {};
export function middleware(request) {
const ip = request.ip || 'anonymous';
const now = Date.now();
const windowMs = 60 * 1000; // 1 minute
const maxRequests = 100;
if (!rateLimit[ip]) {
rateLimit[ip] = [];
}
rateLimit[ip] = rateLimit[ip].filter(time => now - time < windowMs);
if (rateLimit[ip].length >= maxRequests) {
return NextResponse.json(
{ error: 'Too many requests' },
{ status: 429 }
);
}
rateLimit[ip].push(now);
return NextResponse.next();
}
Middleware Response Types
Middleware can return different types of responses:
NextResponse.next() - Continues to the next middleware or route handler.
NextResponse.redirect() - Redirects the user to a different URL.
NextResponse.rewrite() - Rewrites the URL without changing what's displayed.
NextResponse.json() - Returns a JSON response directly from middleware.
These response types give you full control over how requests are processed.
Middleware Configuration
The config object lets you specify which routes the middleware applies to. You can use exact paths, wildcards, or regular expressions.
export const config = {
matcher: [
'/api/:path*', // All API routes
'/dashboard/:path*', // All dashboard routes
'/((?!_next).*)', // All routes except Next.js internals
],
};
This flexibility lets you apply middleware only where it's needed, improving performance.