Consider this Next.js API middleware that adds a custom header before the API handler runs. What will the client receive in the response headers?
import { NextResponse } from 'next/server'; export function middleware(request) { const response = NextResponse.next(); response.headers.set('X-Custom-Header', 'HelloWorld'); return response; } export async function GET(request) { return NextResponse.json({ message: 'API response' }); }
Middleware can modify response headers before the handler runs.
The middleware uses NextResponse.next() to continue to the handler and sets a custom header. This header is included in the final response.
Identify the correct way to write middleware for Next.js API routes to run before the handler.
Next.js middleware uses the NextResponse object and a single request parameter.
Next.js middleware receives a request object and returns a NextResponse. It does not use Express-style req, res, next parameters.
This middleware tries to add a JSON field to the API response body but it does not work. Why?
import { NextResponse } from 'next/server'; export function middleware(request) { const response = NextResponse.next(); const json = JSON.parse(response.body || '{}'); json.middlewareAdded = true; response.body = JSON.stringify(json); return response; } export async function GET(request) { return NextResponse.json({ message: 'Hello' }); }
Think about when middleware runs relative to the API handler.
Middleware runs before the API handler sends the response body, so it cannot modify the body content. It can only modify headers or redirect.
Given two middleware functions that both set the same header, what will the client receive?
import { NextResponse } from 'next/server'; export function middleware(request) { const response = NextResponse.next(); response.headers.set('X-Trace-Id', 'first'); return response; } export function secondMiddleware(request) { const response = NextResponse.next(); response.headers.set('X-Trace-Id', 'second'); return response; }
Headers with the same name get overwritten by later middleware.
When multiple middleware set the same header, the last one to run overwrites the previous value.
Choose the correct statement about how Next.js middleware works with API routes.
Think about the middleware lifecycle and what it can access.
Next.js middleware runs before the API handler and can modify the request or response headers, redirect, or rewrite, but it cannot modify the response body generated by the handler.