Bird
Raised Fist0
NextJSframework~20 mins

Request modification in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Next.js Request Modifier Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Next.js server action modifying a request header?

Consider this Next.js server action that modifies the request headers before processing:

export async function POST(request: Request) {
  const newHeaders = new Headers(request.headers);
  newHeaders.set('x-custom', '123');
  const modifiedRequest = new Request(request.url, {
    method: request.method,
    headers: newHeaders,
    body: await request.text()
  });
  const customHeader = modifiedRequest.headers.get('x-custom');
  return new Response(customHeader);
}

What will be the response body when this action is called?

NextJS
export async function POST(request: Request) {
  const newHeaders = new Headers(request.headers);
  newHeaders.set('x-custom', '123');
  const modifiedRequest = new Request(request.url, {
    method: request.method,
    headers: newHeaders,
    body: await request.text()
  });
  const customHeader = modifiedRequest.headers.get('x-custom');
  return new Response(customHeader);
}
A"123"
B"undefined"
C""
D"null"
Attempts:
2 left
💡 Hint

Think about how headers are copied and set in the new Request object.

📝 Syntax
intermediate
2:00remaining
Which option causes a syntax error in Next.js server action modifying request?

Identify which code snippet will cause a syntax error when trying to modify a request in a Next.js server action.

Aconst newReq = new Request(request.url, { method: 'POST', headers: newHeaders });
Bconst newHeaders = new Headers(request.headers); newHeaders.set('x', '1');
Cconst newReq = new Request(request.url, { method: 'POST', headers: request.headers.set('x', '1') });
Dconst newHeaders = new Headers(request.headers); newHeaders.append('x', '1');
Attempts:
2 left
💡 Hint

Check if the method used on headers returns a new object or modifies in place.

🔧 Debug
advanced
2:00remaining
Why does this Next.js server action fail to modify the request body?

Given this server action code:

export async function POST(request: Request) {
  const newHeaders = new Headers(request.headers);
  newHeaders.set('x-modified', 'true');
  const modifiedRequest = new Request(request.url, {
    method: 'POST',
    headers: newHeaders,
    body: request.body
  });
  const text = await modifiedRequest.text();
  return new Response(text);
}

Why does calling modifiedRequest.text() throw an error?

NextJS
export async function POST(request: Request) {
  const newHeaders = new Headers(request.headers);
  newHeaders.set('x-modified', 'true');
  const modifiedRequest = new Request(request.url, {
    method: 'POST',
    headers: newHeaders,
    body: request.body
  });
  const text = await modifiedRequest.text();
  return new Response(text);
}
AHeaders cannot be modified after the request is created, causing a runtime error.
BThe original request body is a stream that can only be read once, so passing request.body causes an error.
CThe method 'POST' is invalid in the new Request constructor, causing a syntax error.
DThe new Request constructor requires a JSON body, so passing a stream causes a type error.
Attempts:
2 left
💡 Hint

Think about how request bodies behave as streams in web APIs.

state_output
advanced
2:00remaining
What is the value of the header after this Next.js server action modifies it twice?

Analyze this server action:

export async function POST(request: Request) {
  const headers = new Headers(request.headers);
  headers.set('x-count', '1');
  headers.set('x-count', String(Number(headers.get('x-count')) + 1));
  return new Response(headers.get('x-count'));
}

What will be the response body?

NextJS
export async function POST(request: Request) {
  const headers = new Headers(request.headers);
  headers.set('x-count', '1');
  headers.set('x-count', String(Number(headers.get('x-count')) + 1));
  return new Response(headers.get('x-count'));
}
A"undefined"
B"1"
C"NaN"
D"2"
Attempts:
2 left
💡 Hint

Consider how headers.set and headers.get work sequentially.

🧠 Conceptual
expert
2:00remaining
Which statement about modifying requests in Next.js server actions is true?

Choose the correct statement about modifying incoming requests in Next.js server actions.

ATo modify headers or body, you must create a new Request object with the desired changes because Request objects are immutable.
BYou can directly modify the incoming Request object headers and body without creating a new Request.
CModifying the headers object returned by request.headers directly changes the original request headers.
DNext.js server actions automatically clone and allow mutation of the request object passed in.
Attempts:
2 left
💡 Hint

Think about immutability of web Request objects.

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

  1. Step 1: Understand middleware role in Next.js

    Middleware runs before the app processes a request, allowing changes to the request.
  2. Step 2: Identify what request modification means

    Modifying means changing headers, body, or other request parts before the app sees it.
  3. Final Answer:

    To change request details like headers or body before the app processes it -> Option A
  4. Quick Check:

    Request modification = change request details [OK]
Hint: Middleware changes requests before app sees them [OK]
Common Mistakes:
  • Confusing request modification with sending responses
  • Thinking middleware updates databases directly
  • Assuming middleware only logs requests
2. Which of the following is the correct way to return a modified request in Next.js middleware?
easy
A. return NextResponse.next(request);
B. return NextResponse.next(new Request(request));
C. return NextResponse.redirect('/new-path');
D. return NextResponse.next(new Request(request, { headers: { 'x-new': 'value' } }));

Solution

  1. 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().
  2. 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.
  3. Final Answer:

    return NextResponse.next(new Request(request, { headers: { 'x-new': 'value' } })); -> Option D
  4. Quick Check:

    New Request with changes + NextResponse.next() = D [OK]
Hint: Wrap new Request with changes inside NextResponse.next() [OK]
Common Mistakes:
  • Returning original request without changes
  • Using redirect instead of next() for modification
  • Not creating a new Request object for changes
3. Given this middleware code snippet, what will be the value of the header 'x-user' in the request seen by the app?
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);
}
medium
A. null
B. undefined
C. alice
D. original header value if any

Solution

  1. 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.
  2. 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'.
  3. Final Answer:

    alice -> Option C
  4. Quick Check:

    Header 'x-user' set to 'alice' in new Request [OK]
Hint: Headers set in new Request appear in app request [OK]
Common Mistakes:
  • Assuming original headers remain unchanged
  • Thinking header is removed or null
  • Confusing middleware response headers with request headers
4. Identify the error in this Next.js middleware code that tries to add a custom header:
import { NextResponse } from 'next/server';
export function middleware(request) {
  request.headers.set('x-custom', '123');
  return NextResponse.next(request);
}
medium
A. Headers are immutable; cannot modify request.headers directly
B. NextResponse.next() cannot accept a Request object
C. Missing await keyword for asynchronous header setting
D. Middleware must return a Response, not NextResponse

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Headers are immutable; cannot modify request.headers directly -> Option A
  4. Quick Check:

    Request.headers immutable = B [OK]
Hint: Request.headers are read-only; create new Headers to modify [OK]
Common Mistakes:
  • Trying to set headers directly on request.headers
  • Assuming NextResponse.next() rejects Request objects
  • Confusing async code requirement for headers
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

  1. 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().
  2. Step 2: Why it works

    Clones headers immutably, adds conditionally if missing, preserves other headers, forwards new request or original.
  3. 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.
  4. 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
  5. 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]
Common Mistakes:
  • Modifying request.headers directly
  • Overwriting all headers instead of cloning
  • Not checking if header already exists