← Back to Node.js, page 2

nodejs-0040 · Medium mid

How do you read and validate a JSON request body in a plain Node.js server, and why set a size limit?

The body arrives as chunks on the request stream. Collect the chunks, enforce a maximum size while collecting, then parse the JSON and validate it. A limit protects memory from huge uploads, and clear status codes tell the client what went wrong: 400 for bad JSON, 413 for too large, 415 for the wrong content type.

Full answer

A request body is a stream. A client can send a few bytes or several gigabytes. If you push all chunks into an array without a limit, one malicious or buggy client can use all the memory of the server.

Steps for a safe JSON endpoint:

  1. Check the Content-Type header. If it is not application/json, answer 415.
  2. Read chunks and add up their length. If the total goes above the limit (for example 1 MB), stop reading and answer 413. Check Content-Length for an early rejection, but still count real bytes, because the header can lie or be missing (chunked encoding).
  3. Join the chunks with Buffer.concat and decode once as UTF-8. Decoding each chunk separately can break multi-byte characters.
  4. JSON.parse inside try/catch. A parse error is the client's fault, so answer 400.
  5. Validate the shape (types, ranges, allowed fields) with a schema library or explicit checks. Do not trust parsed JSON.
  6. Answer with a JSON error body that has a stable code.

For file uploads, do not buffer at all. Stream the body to disk or object storage, and set limits on size and time.

Related server settings: requestTimeout and headersTimeout stop slow clients, and a reverse proxy usually adds its own body limit as well.

javascript
const http = require('node:http');

function readJson(req, limit) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    let tooBig = false;
    req.on('data', (chunk) => {
      if (tooBig) return;
      size += chunk.length;
      if (size > limit) {
        tooBig = true;
        chunks.length = 0; // drop what we collected, keep draining
        return reject(Object.assign(new Error('body too large'), { status: 413 }));
      }
      chunks.push(chunk);
    });
    req.on('end', () => {
      if (tooBig) return;
      try {
        resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
      } catch {
        reject(Object.assign(new Error('invalid JSON'), { status: 400 }));
      }
    });
    req.on('error', reject);
  });
}

const server = http.createServer(async (req, res) => {
  try {
    if (!String(req.headers['content-type']).startsWith('application/json')) {
      throw Object.assign(new Error('send application/json'), { status: 415 });
    }
    const body = await readJson(req, 1024);
    if (typeof body.name !== 'string' || !Number.isInteger(body.marks)) {
      throw Object.assign(new Error('name must be text and marks an integer'), { status: 422 });
    }
    res.writeHead(201, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ saved: body.name }));
  } catch (err) {
    res.writeHead(err.status || 500, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: err.message }));
  }
});

server.listen(0, async () => {
  const url = 'http://127.0.0.1:' + server.address().port;
  const post = (body, type = 'application/json') =>
    fetch(url, { method: 'POST', headers: { 'Content-Type': type }, body }).then(async (r) => r.status + ' ' + (await r.text()));

  console.log('valid:       ', await post(JSON.stringify({ name: 'Asha', marks: 78 })));
  console.log('bad JSON:    ', await post('{"name": '));
  console.log('wrong shape: ', await post(JSON.stringify({ name: 'Asha', marks: 'high' })));
  console.log('too large:   ', await post(JSON.stringify({ name: 'x'.repeat(2000), marks: 1 })));
  console.log('wrong type:  ', await post('name=Asha', 'text/plain'));
  server.close();
});

Each request tests one rule. The limit is 1 KB here so the large case is easy to trigger. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): valid: 201 {"saved":"Asha"} bad JSON: 400 {"error":"invalid JSON"} wrong shape: 422 {"error":"name must be text and marks an integer"} too large: 413 {"error":"body too large"} wrong type: 415 {"error":"send application/json"}

Key points

  • Read chunks, count bytes, enforce a limit while reading.
  • Decode once after joining all chunks.
  • Use 400, 413 and 415 to explain the failure.
  • Validate the parsed data. Parsing is not validation.

Common mistakes

  • Collecting chunks with no size limit.
  • Calling JSON.parse outside try/catch.
  • Treating valid JSON as valid data.
  • Calling chunk.toString() on each chunk separately.

Follow-ups

  • How would you handle a multipart file upload?
  • How does a reverse proxy limit body size?
  • What changes when the client sends Transfer-Encoding: chunked?

Tips

  • List the status codes in the order they occur.
  • Say 'parsing is not validation'.
  • Mention streaming for uploads to show you know when buffering is wrong.