Request bodies and limits
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Accept valid bounded JSON
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});async function readJson(req, limit) { let size=0; const parts=[]; let oversized=false; for await(const chunk of req){ size+=chunk.length; if(size>limit){oversized=true;continue;} parts.push(chunk); } if(oversized) return {status:413}; try{return {status:200,value:JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(parts))) };} catch{return {status:400};}}const handler=(req,res)=>{ readJson(req,16).then(result=>{ res.statusCode=result.status;res.setHeader('content-type','application/json'); res.end(JSON.stringify(result.value??{error:result.status})); }).catch(()=>{if(!res.destroyed){res.statusCode=400;res.end();}});};await withServer(handler,async base=>{const r=await localFetch(base,{method:'POST',headers:{'content-type':'application/json'},body:'{"count":2}'});console.log(r.status,(await r.json()).count);});Run:
node main.mjsExpected stdout:
200 2Exit status: 0. Expected stderr: empty.
How it works
Count received bytes, not JavaScript string length or only a claimed Content-Length. The helper accumulates at most 16 bytes and rejects excess with 413 after draining the tiny known fixture request; it is not a production ingress policy. Decode UTF-8 strictly and then parse JSON; malformed content returns 400. A real server must also enforce content type (415 for unsupported media), transport deadlines, connection limits and an early termination strategy for unbounded bodies. Parsing alone does not validate field types.
Reject malformed and oversized input
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});async function readJson(req, limit) { let size=0; const parts=[]; let oversized=false; for await(const chunk of req){ size+=chunk.length; if(size>limit){oversized=true;continue;} parts.push(chunk); } if(oversized) return {status:413}; try{return {status:200,value:JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(parts))) };} catch{return {status:400};}}const handler=(req,res)=>{ readJson(req,16).then(result=>{ res.statusCode=result.status;res.setHeader('content-type','application/json'); res.end(JSON.stringify(result.value??{error:result.status})); }).catch(()=>{if(!res.destroyed){res.statusCode=400;res.end();}});};await withServer(handler,async base=>{for(const body of ['{broken','{"name":"long name"}']){const r=await localFetch(base,{method:'POST',headers:{'content-type':'application/json'},body});await r.text();console.log(r.status);}});Run:
node main.mjsExpected stdout:
400413Exit status: 0. Expected stderr: empty.
Common mistake
Do not concatenate unrestricted request data or trust Content-Length alone. A parser limit is not a complete resource limit. Never reuse this drain-to-end demo for arbitrary Internet uploads.
Practice
Try a 16-byte valid JSON string and a 17-byte one. Explain why the byte limit must be checked before decoding.
Further reading: Authoritative source 1 · Authoritative source 2. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Request bodies and limits — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What unit should the body byte limit use?
Which status indicates content too large?
Does valid JSON ensure a valid order?