The request body arrives as a stream of chunks, so you collect them and join them before parsing. Here is how to read JSON and form bodies safely with the node:http module.
The short answer
#The request object is a readable stream, so the body is not available straight away. Read all the chunks, join them, then parse. The shortest way is the json helper from node:stream/consumers.
_10import { createServer } from 'node:http';_10import { json } from 'node:stream/consumers';_10_10createServer(async (req, res) => {_10 const body = await json(req);_10 res.end(`Hello ${body.name}`);_10}).listen(3000);
Why it happens
#Frameworks like Express or Fastify give you req.body because they read and parse the body for you. The plain node:http module does not. It calls your handler as soon as the headers arrive, before the body has been received, so that large uploads can be processed piece by piece instead of being held in memory.
That is why req.body is undefined in a plain server. The data is there, but you have to read it from the stream.
How to fix it
#Read the stream with for await
Requests are async iterable, so you can loop over the chunks. Each chunk is a Buffer.
_28import { createServer } from 'node:http';_28_28async function readBody(req, limit = 1_000_000) {_28 const chunks = [];_28 let size = 0;_28_28 for await (const chunk of req) {_28 size += chunk.length;_28 if (size > limit) {_28 const err = new Error('Body too large');_28 err.status = 413;_28 throw err;_28 }_28 chunks.push(chunk);_28 }_28_28 return Buffer.concat(chunks).toString('utf8');_28}_28_28createServer(async (req, res) => {_28 try {_28 const text = await readBody(req);_28 res.end(`Received ${text.length} characters`);_28 } catch (err) {_28 res.statusCode = err.status ?? 500;_28 res.end(err.message);_28 }_28}).listen(3000);
Joining buffers with Buffer.concat before turning them into a string matters. A multi-byte character such as an emoji can be split across two chunks, and converting each chunk separately would corrupt it.
The size limit matters too. Without it, anyone can send a huge body and fill your server's memory.
Parse JSON safely
Check the content type and catch parse errors, so bad input gets a 400 response rather than crashing the handler.
_22createServer(async (req, res) => {_22 if (req.method !== 'POST') {_22 res.writeHead(405).end();_22 return;_22 }_22_22 if (!req.headers['content-type']?.startsWith('application/json')) {_22 res.writeHead(415).end('Expected JSON');_22 return;_22 }_22_22 let data;_22 try {_22 data = JSON.parse(await readBody(req));_22 } catch {_22 res.writeHead(400).end('Invalid JSON');_22 return;_22 }_22_22 res.writeHead(201, { 'Content-Type': 'application/json' });_22 res.end(JSON.stringify({ ok: true, received: data }));_22}).listen(3000);
Use node:stream/consumers for short code
The node:stream/consumers module has helpers named text, json, buffer and arrayBuffer that read a whole stream for you.
_10import { text, json } from 'node:stream/consumers';_10_10const raw = await text(req);_10const data = await json(req); // use one or the other, a stream can only be read once
These are handy for scripts and internal tools. They do not apply a size limit, so for a public server, use your own reader with a limit as shown above.
Parse HTML form posts
A normal HTML form sends application/x-www-form-urlencoded. Read the text, then parse it with URLSearchParams.
_10const params = new URLSearchParams(await readBody(req));_10const email = params.get('email');
File uploads use multipart/form-data, which is much harder to parse by hand. Use a library such as busboy for those.
Common pitfalls
#- Reading the body twice. A stream can only be consumed once. Read it into a variable and reuse that.
- Responding before reading. If you send a response without reading the body, the rest of the upload may be discarded or the connection closed. Read or drain it first.
- Converting chunks to strings one at a time. This breaks multi-byte characters. Collect buffers and join them.
- No size limit. Always cap the body size on a public server and reply with 413 when it is exceeded.
- Forgetting GET requests. GET and HEAD requests normally have no body. Check
req.methodbefore trying to parse one.
Related reading
#Was this resource helpful?