Advanced
Advanced
Middleware
Implement middleware for request modification, redirects, authentication, and custom logic.
25 min
2 sections
middleware
redirects
auth
1
2
01. Creating Middleware
Section 1 of 2
Middleware runs before a request is completed, allowing you to modify the response or redirect.
typescript
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Add custom header
const response = NextResponse.next();
response.headers.set('x-custom-header', 'value');
return response;
}
export const config = {
matcher: '/about/:path*',
};Exercise
Create a Locale Middleware
Practice
Create middleware that checks for a locale cookie and redirects to the appropriate localized route.
Back to Course