NextRequest & NextResponse

The Next.js extensions to standard Web APIs.

Next.js3 min readConcept 47 of 65

Extending Web Standards

Instead of using Node.js's IncomingMessage or Express's Request objects, Next.js uses the modern Web API standards (the same ones used in the fetch API).

It then extends them with NextRequest and NextResponse to add powerful Next.js-specific helpers.

Quality of Life

Native Web Requests require you to manually parse raw cookie strings.

NextRequest gives you a convenient req.cookies.get('token') method.

It also includes req.nextUrl, which parses the URL for you, making it trivial to read query parameters or pathnames.

Usage in Route Handlers

You import them from next/server.

To read JSON bodies: const data = await req.json(); (Notice it is an async method).

To send JSON: return NextResponse.json({ success: true });

Express vs Next.js

Examine the difference between legacy Express.js syntax and modern Next.js (Web API) syntax when handling an API request.

Legacy Node.js (Express)

server.js
app.post('/api/users', (req, res) => {
// Synchronous object access
const body = req.body;
// Mutating a response object
const token = req.cookies.token;
res.status(200).send({ body, token });
});

Modern Next.js (Web API)

route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
// Await the JSON stream parser
const body = await req.json();
// NextRequest cookie helper
const token = req.cookies.get('token');
// Return a new Response instance
return NextResponse.json({ body, token });
}

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1How do you extract a JSON payload from an incoming POST request in a Next.js Route Handler?

Remember this

  • NextRequest and NextResponse extend standard Web APIs.
  • Use req.cookies and req.nextUrl for convenient data extraction.
  • Do not use Express syntax like req.body or res.send().
  • Always await req.json() to parse incoming JSON payloads.

Done with this concept?

Mark it complete to track your progress. No login needed.