Sometimes you need to change a web request before sending it. This helps add extra info or fix details.
Request modification in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
Solution
Step 1: Understand middleware role in Next.js
Middleware runs before the app processes a request, allowing changes to the request.Step 2: Identify what request modification means
Modifying means changing headers, body, or other request parts before the app sees it.Final Answer:
To change request details like headers or body before the app processes it -> Option AQuick Check:
Request modification = change request details [OK]
- Confusing request modification with sending responses
- Thinking middleware updates databases directly
- Assuming middleware only logs requests
Solution
Step 1: Understand how to modify requests in Next.js middleware
You must create a new Request object with changes (like new headers) and pass it to NextResponse.next().Step 2: Check each option
return NextResponse.next(request); passes original request without changes. return NextResponse.next(new Request(request)); creates a new Request but without changes. return NextResponse.next(new Request(request, { headers: { 'x-new': 'value' } })); creates a new Request with modified headers correctly. return NextResponse.redirect('/new-path'); redirects instead of modifying request.Final Answer:
return NextResponse.next(new Request(request, { headers: { 'x-new': 'value' } })); -> Option DQuick Check:
New Request with changes + NextResponse.next() = D [OK]
- Returning original request without changes
- Using redirect instead of next() for modification
- Not creating a new Request object for changes
import { NextResponse } from 'next/server';
export function middleware(request) {
const newHeaders = new Headers(request.headers);
newHeaders.set('x-user', 'alice');
const newRequest = new Request(request.url, { headers: newHeaders });
return NextResponse.next(newRequest);
}Solution
Step 1: Analyze header modification in middleware
The code creates new headers from the original, sets 'x-user' to 'alice', then creates a new Request with these headers.Step 2: Determine header value passed to app
The app receives the new Request with 'x-user' header set to 'alice', so the value is 'alice'.Final Answer:
alice -> Option CQuick Check:
Header 'x-user' set to 'alice' in new Request [OK]
- Assuming original headers remain unchanged
- Thinking header is removed or null
- Confusing middleware response headers with request headers
import { NextResponse } from 'next/server';
export function middleware(request) {
request.headers.set('x-custom', '123');
return NextResponse.next(request);
}Solution
Step 1: Check how headers can be modified in Next.js middleware
Request headers are immutable; you cannot change them directly on the original request object.Step 2: Identify correct way to modify headers
You must create a new Headers object, modify it, then create a new Request with those headers.Final Answer:
Headers are immutable; cannot modify request.headers directly -> Option AQuick Check:
Request.headers immutable = B [OK]
- Trying to set headers directly on request.headers
- Assuming NextResponse.next() rejects Request objects
- Confusing async code requirement for headers
Solution
Step 1: Identify the correct conditional logic and immutable handling
Check !request.headers.has('x-trace-id'), then const headers = new Headers(request.headers); headers.set('x-trace-id', crypto.randomUUID()); const newRequest = new Request(request.url, { headers }); return NextResponse.next(newRequest); else return NextResponse.next().Step 2: Why it works
Clones headers immutably, adds conditionally if missing, preserves other headers, forwards new request or original.Step 3: Why others fail
Direct set on request.headers throws immutable error. new Request with { headers: { 'x-trace-id': ... } } replaces all headers. new Headers() starts empty, loses original headers.Final Answer:
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.headers.has('x-trace-id')) { const headers = new Headers(request.headers); headers.set('x-trace-id', crypto.randomUUID()); const newRequest = new Request(request.url, { headers }); return NextResponse.next(newRequest); } return NextResponse.next(); } -> Option BQuick Check:
Check header, clone headers, set new, return new Request = A [OK]
- Modifying request.headers directly
- Overwriting all headers instead of cloning
- Not checking if header already exists
