Introduction
Middleware lets you run code before your API route handles a request. It helps you check or change requests easily.
Jump into concepts and practice - no test required
Middleware lets you run code before your API route handles a request. It helps you check or change requests easily.
import { NextResponse } from 'next/server'; export function middleware(request) { // Your code here return NextResponse.next(); } export const config = { matcher: '/api/:path*', };
The middleware function runs before your API route.
Use NextResponse.next() to continue to the API handler.
import { NextResponse } from 'next/server'; export function middleware(request) { console.log('API called:', request.url); return NextResponse.next(); }
import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.headers.get('authorization'); if (!token) { return new NextResponse('Unauthorized', { status: 401 }); } return NextResponse.next(); }
This middleware blocks requests from user agents that include the word 'bot'. Others continue to the API route.
import { NextResponse } from 'next/server'; export function middleware(request) { const userAgent = request.headers.get('user-agent') || ''; if (userAgent.toLowerCase().includes('bot')) { return new NextResponse('Bots are not allowed', { status: 403 }); } return NextResponse.next(); } export const config = { matcher: '/api/:path*', };
Middleware runs on the edge, so keep it fast and simple.
Use matcher to limit middleware to API routes only.
You can modify requests or responses inside middleware before they reach your API.
Middleware runs code before your API route handles a request.
Use it to check, block, or modify requests easily.
Remember to use NextResponse.next() to continue to the API handler.
x-auth: secret is sent?
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.headers.get('x-auth') !== 'secret') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
return NextResponse.next();
}import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.headers.get('authorization')) {
NextResponse.redirect('/login');
}
return NextResponse.next();
}token is missing or empty. Which code correctly implements this behavior?