Sometimes you need to change a web request before sending it. This helps add extra info or fix details.
Request modification in NextJS
import { NextRequest, NextResponse } from 'next/server'; export function middleware(request: NextRequest) { // Modify request here const modifiedRequest = request.clone(); // Example: add header modifiedRequest.headers.set('X-Custom-Header', 'value'); return NextResponse.next(); }
Use middleware in Next.js to intercept and modify requests.
You can clone the request to safely change it without affecting the original.
export function middleware(request) { const url = request.nextUrl.clone(); url.pathname = '/new-path'; return NextResponse.rewrite(url); }
export function middleware(request) { const response = NextResponse.next(); response.headers.set('X-Added-Header', 'hello'); return response; }
export function middleware(request) { if (!request.headers.get('authorization')) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }
This middleware checks if the request comes from a bot by looking at the user-agent header. If it finds 'bot', it redirects the request to a special '/bots' page. Otherwise, it lets the request continue as normal.
import { NextResponse } from 'next/server'; export function middleware(request) { // Check if user-agent contains 'bot' const userAgent = request.headers.get('user-agent') || ''; if (userAgent.toLowerCase().includes('bot')) { // Redirect bots to a special page return NextResponse.redirect(new URL('/bots', request.url)); } // Otherwise, continue normally return NextResponse.next(); }
Middleware runs before your page or API code, so it can change requests early.
Be careful not to create infinite redirects when modifying requests.
Use NextResponse.next() to continue without changes.
Request modification lets you change or redirect requests before they reach your app.
Use Next.js middleware to inspect and change headers, paths, or redirect users.
This helps with authentication, routing, and customizing user experience.