Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Modify a Request in Next.js API Route
📖 Scenario: You are building a Next.js API route that receives a JSON request with a user's name and age. You want to modify the request data by adding a new field before sending the response.
🎯 Goal: Create a Next.js API route that reads the incoming JSON request body, adds a new field isAdult based on the age, and returns the modified JSON object.
📋 What You'll Learn
Create an API route handler function named handler that accepts req and res parameters
Read the JSON body from req.body containing name and age
Add a new boolean field isAdult which is true if age is 18 or more, otherwise false
Return the modified object as JSON in the response using res.status(200).json()
💡 Why This Matters
🌍 Real World
API routes in Next.js are used to handle backend logic like processing form data, modifying requests, and sending responses in web applications.
💼 Career
Understanding how to modify request data and send JSON responses is essential for backend development in Next.js, a popular React framework used in many companies.
Progress0 / 4 steps
1
Create the API route handler function
Create an async function called handler that takes req and res as parameters.
NextJS
Hint
Start by defining the function with the exact name handler and parameters req and res.
2
Extract the JSON body from the request
Inside the handler function, create a constant called data and assign it the value of req.body.
NextJS
Hint
Use const data = req.body to get the JSON data sent in the request.
3
Add the isAdult field based on age
Create a new constant called modifiedData that copies all properties from data and adds a new property isAdult which is true if data.age is 18 or more, otherwise false.
NextJS
Hint
Use object spread syntax { ...data, isAdult: data.age >= 18 } to add the new field.
4
Send the modified data as JSON response
Use res.status(200).json(modifiedData) to send the modified data back as a JSON response inside the handler function.
NextJS
Hint
Use res.status(200).json(modifiedData) to send the response with status code 200.
Practice
(1/5)
1. In Next.js, what is the main purpose of modifying a request in middleware?
easy
A. To change request details like headers or body before the app processes it
B. To directly send a response to the client without processing
C. To update the database with request data
D. To log request details only without changing anything
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 A
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.
5. You want to add a custom header 'x-trace-id' with a unique value to every request in Next.js middleware, but only if the header is not already present. Which code snippet correctly implements this?
hard
A. import { NextResponse } from 'next/server';
export function middleware(request) {
const headers = request.headers;
if (!headers.has('x-trace-id')) {
headers.set('x-trace-id', crypto.randomUUID());
}
return NextResponse.next(request);
}
B. 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();
}
C. import { NextResponse } from 'next/server';
export function middleware(request) {
const newRequest = new Request(request.url, { headers: { 'x-trace-id': crypto.randomUUID() } });
return NextResponse.next(newRequest);
}
D. import { NextResponse } from 'next/server';
export function middleware(request) {
const headers = new Headers();
headers.set('x-trace-id', crypto.randomUUID());
const newRequest = new Request(request.url, { headers });
return NextResponse.next(newRequest);
}
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 B
Quick Check:
Check header, clone headers, set new, return new Request = A [OK]
Hint: Clone headers, check presence, set if missing, return new Request [OK]