Next.jsEasy
How do you read request body in Route Handlers?
Call the Web Request body methods: await request.json() for JSON, await request.formData() for forms and file uploads, await request.text() for raw text (webhook signatures), await request.arrayBuffer() or request.blob() for binary, or read request.body as a stream. A body can be read only once.
Choosing the method
| Content-Type | Method |
|---|---|
application/json | request.json() |
multipart/form-data, application/x-www-form-urlencoded | request.formData() |
| Webhooks that verify a signature | request.text() (raw string) |
| Binary uploads | request.arrayBuffer() / blob() |
| Large or streaming uploads | request.body (ReadableStream) |
Rules and pitfalls
- The body is a stream: calling
json()aftertext()throws "body used already". Userequest.clone()if you must read it twice. request.json()throws on invalid JSON; wrap it intry/catchand return 400.- Always validate the parsed data (Zod); never trust its shape.
- There is no automatic body size limit in Route Handlers like Pages Router's 1MB
bodyParser; enforce limits yourself (checkContent-Lengthor count bytes while streaming), and remember your host may cap request size. GETandHEADrequests have no body; use search params instead.
Pages Router comparison
req.body is pre-parsed by bodyParser. Disable it (config.api.bodyParser = false) to get the raw stream for signatures.
Code example
tsx
1// app/api/contact/route.ts2import { z } from "zod";34const Contact = z.object({5 email: z.string().email(),6 message: z.string().min(10).max(5000),7});89export async function POST(request: Request) {10 const type = request.headers.get("content-type") ?? "";1112 let input: unknown;13 try {14 input = type.includes("application/json")15 ? await request.json()16 : Object.fromEntries(await request.formData()); // works for HTML forms too17 } catch {18 return Response.json({ error: "Invalid body" }, { status: 400 });19 }2021 const parsed = Contact.safeParse(input);22 if (!parsed.success) {23 return Response.json({ error: parsed.error.flatten().fieldErrors }, { status: 422 });24 }2526 // await sendEmail(parsed.data);27 return Response.json({ ok: true }, { status: 201 });28}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.