Next.js Course
Next.js
/
Intermediate

Request & Response Objects

Definition

Next.js Route Handlers strictly use the native Web standard `Request` and `Response` objects, replacing the old Node.js/Express `req` and `res` objects.

Explain Like I'm New

When handling APIs, you need to read the incoming data (Request) and send data back (Response). Next.js uses the exact same `Request` object that Service Workers and the `fetch` API use, making the knowledge transferable.

Real World Example

Reading a `?search=shoes` URL query parameter from the incoming Request, and returning a `404 Not Found` Response if no shoes exist.

Common Use Cases

  • •Reading URL parameters
  • •Parsing JSON bodies
  • •Setting HTTP headers

Interactive Example

import { NextRequest, NextResponse } from 'next/server';

// NextRequest provides extra Next.js specific helpers over standard Request
export async function GET(request: NextRequest) {
  
  // 1. Read Query Parameters (?query=apple)
  const searchParams = request.nextUrl.searchParams;
  const query = searchParams.get('query');
  
  // 2. Read Headers (e.g. Authorization token)
  const authHeader = request.headers.get('authorization');
  
  if (!authHeader) {
    // 3. Return a custom error Response with headers
    return NextResponse.json(
      { error: 'Unauthorized' }, 
      { status: 401, headers: { 'x-custom-header': 'hello' } }
    );
  }
  
  return NextResponse.json({ success: true, query });
}

Interview Questions

basic

  • How do you read the JSON body sent by a client in a `POST` request?

intermediate

  • How do you read a query parameter (like `?id=5`) from a `NextRequest` object?

Flash Cards

Question

Read JSON body?

Click to reveal answer
Answer

By calling `await request.json()`.

Question

Read query parameter?

Click to reveal answer
Answer

By using the `searchParams` property of the URL object: `request.nextUrl.searchParams.get('id')`.