How to Parse JSON Request Bodies Safely in Node.js
Read a JSON body from node:http with a size limit, a content type check, a timeout and clear errors, and see why JSON.parse alone is not enough.

JSON.parse(await readBody(req)) is the line most hand-written Node.js servers start with, and it is the line that fails first in production. A client sends a body that is not JSON, or a body that is a hundred megabytes, or one that never finishes, or one that is valid JSON of the wrong shape, and the server either crashes, hangs or accepts garbage. This post builds a body reader on node:http that handles each case on purpose: a size limit, a content type check, a read timeout, a parse step that turns syntax errors into a 400, and a shape check before the data reaches your logic. It is written for Node.js 26, and every API it uses is available on Node.js 22 and 24 as well.
What can go wrong
Reading a request body looks like a single step, but it is four separate ones, and each has its own failure.
| Step | Failure | Right response |
|---|---|---|
| Declare | Client sends the wrong content-type | 415 Unsupported Media Type |
| Receive | Body is larger than you can afford | 413 Content Too Large |
| Receive | Client stalls or trickles bytes | 408 Request Timeout |
| Parse | Body is not valid JSON | 400 Bad Request |
| Validate | JSON parses but has the wrong shape | 422 Unprocessable Content |
A server that handles none of them turns every one into a 500 or, worse, an unhandled rejection that ends the process. The HTTP semantics specification, RFC 9110, defines those status codes, and the sections below handle them in the order a request meets them.
The naive version and why it fails
Here is the version most people write first.
import { createServer } from "node:http";
createServer(async (req, res) => {
let raw = "";
for await (const chunk of req) raw += chunk;
const data = JSON.parse(raw);
res.end(`hello ${data.name}\n`);
}).listen(3000);Send it a malformed body and the JSON.parse call throws inside an async callback, so the returned promise rejects, nothing handles it, and Node.js treats an unhandled rejection as an uncaught error that ends the process by default. One bad request takes the server down.
curl -s -X POST localhost:3000 -d '{"name": 'node:internal/process/promises:394
triggerUncaughtException(err, true /* fromPromise */);
^
SyntaxError: Unexpected end of JSON inputThe stack trace lines that follow depend on your file path and are omitted. Two more problems hide in this code. The string concatenation raw += chunk decodes each chunk on its own, so a multi-byte character split across two chunks becomes garbage; collecting buffers and decoding once avoids that. And nothing limits how much raw can grow.
A limited reader
Collect chunks as buffers, count bytes as they arrive, and stop as soon as the count passes the limit. A client that declares a large content-length can be refused before any bytes are read, which is cheaper than discovering it later.
export class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
export async function readBody(req, { limit = 100_000, timeoutMs = 10_000 } = {}) {
const declared = Number(req.headers["content-length"]);
if (Number.isFinite(declared) && declared > limit) {
throw new HttpError(413, "Body too large");
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
const onAbort = () => req.destroy(new HttpError(408, "Body read timed out"));
controller.signal.addEventListener("abort", onAbort, { once: true });
try {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) throw new HttpError(413, "Body too large");
chunks.push(chunk);
}
return Buffer.concat(chunks).toString("utf8");
} catch (error) {
if (controller.signal.aborted) throw new HttpError(408, "Body read timed out");
throw error;
} finally {
clearTimeout(timer);
}
}The declared length is a hint, not a guarantee, which is why the running count stays: a client can lie in the header, or use chunked transfer encoding and send no length at all. The timeout covers the other attack, a client that opens a request and then sends one byte a minute. When the timer fires, destroying the request makes the for await loop throw, and the catch block reports a 408 instead of whatever error the destroyed stream produced. Node.js also has server-level timeouts such as server.requestTimeout and server.headersTimeout, described in the [http.Server documentation](https://nodejs.org/api/http.html#serverrequesttimeout); keep those on as a second line of defence.
The content type check
A JSON endpoint should insist on a JSON content type. Accepting anything lets a browser form post, which sends application/x-www-form-urlencoded or text/plain, reach your handler without a CORS preflight, and that is a cross-site request forgery vector for cookie-authenticated APIs. Requiring application/json forces the preflight.
import { HttpError } from "./read-body.js";
export function requireJson(req) {
const type = (req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
if (type !== "application/json" && !type.endsWith("+json")) {
throw new HttpError(415, "Content-Type must be application/json");
}
}The split(";") drops parameters such as charset=utf-8, and the +json suffix accepts structured types like application/merge-patch+json. The check is exact on the media type, not a substring match, so a header such as text/plain; x=application/json does not slip through.
Parsing, and what the error looks like
JSON.parse throws a SyntaxError whose message differs between engine versions, so never forward it to the client or match on its text. Catch it and answer with your own message. Two more details are worth handling here. An empty body is not valid JSON, so decide whether that is a 400 or an acceptable "no body" for the route. And JSON.parse("null") and JSON.parse("42") are valid JSON that is not an object, which most handlers do not expect.
import { HttpError, readBody } from "./read-body.js";
import { requireJson } from "./content-type.js";
export async function readJson(req, options) {
requireJson(req);
const text = await readBody(req, options);
if (text.trim() === "") throw new HttpError(400, "Request body is empty");
let value;
try {
value = JSON.parse(text);
} catch {
throw new HttpError(400, "Request body is not valid JSON");
}
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new HttpError(422, "Request body must be a JSON object");
}
return value;
}A body of {"name": now gets a clean 400 instead of crashing the process, and a body of [1, 2] gets a 422, because the handler expects an object.
Validating the shape
Parsed JSON is untrusted input with a friendly syntax. Check the fields you use before using them, and build a new object from the checked values rather than passing the parsed object further. That last habit also blocks mass assignment, where a client adds fields such as "role": "admin" that your code would otherwise copy into a record.
import { HttpError } from "./read-body.js";
export function parseNewUser(input) {
const errors = [];
if (typeof input.name !== "string" || input.name.trim() === "") {
errors.push("name must be a non-empty string");
}
if (typeof input.age !== "number" || !Number.isInteger(input.age) || input.age < 0) {
errors.push("age must be a non-negative integer");
}
if (errors.length > 0) throw new HttpError(422, errors.join("; "));
return { name: input.name.trim(), age: input.age };
}For larger schemas, a validation library or JSON Schema validator saves code, but the principle is the same: the output is a fresh object with only the fields you named. The __proto__ key deserves a mention. JSON.parse creates __proto__ as an ordinary own property rather than changing the prototype, so parsing is safe, but merging a parsed object into another with a naive deep-merge function can pollute prototypes. Copying known fields into a new object, as above, avoids the merge entirely.
Putting it together
A handler uses the helpers and a single place that maps HttpError to a response.
import { createServer } from "node:http";
import { readJson } from "./parse-json.js";
import { parseNewUser } from "./validate.js";
import { HttpError } from "./read-body.js";
function send(res, status, body) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"content-type": "application/json",
"content-length": Buffer.byteLength(payload),
});
res.end(payload);
}
createServer(async (req, res) => {
try {
if (req.method !== "POST" || req.url !== "/users") {
throw new HttpError(404, "Not found");
}
const user = parseNewUser(await readJson(req));
send(res, 201, user);
} catch (error) {
const status = error instanceof HttpError ? error.status : 500;
if (status === 500) console.error(error);
send(res, status, { error: status === 500 ? "Internal server error" : error.message });
}
}).listen(3000);Each failure now produces a precise response. Using curl -s -w "\n%{http_code}\n" to print the status after the body:
curl -s -w "\n%{http_code}\n" -X POST localhost:3000/users -H "content-type: application/json" -d '{"name":"Ada","age":36}'
curl -s -w "\n%{http_code}\n" -X POST localhost:3000/users -H "content-type: application/json" -d '{"name": '
curl -s -w "\n%{http_code}\n" -X POST localhost:3000/users -H "content-type: text/plain" -d '{"name":"Ada","age":36}'
curl -s -w "\n%{http_code}\n" -X POST localhost:3000/users -H "content-type: application/json" -d '{"name":"","age":-1}'{"name":"Ada","age":36}
201
{"error":"Request body is not valid JSON"}
400
{"error":"Content-Type must be application/json"}
415
{"error":"name must be a non-empty string; age must be a non-negative integer"}
422The 500 branch logs the real error and returns a generic message, because an internal error message can reveal file paths or library details to the caller.
Choosing the limit
A hundred kilobytes suits most JSON APIs, where payloads are a few fields. Raise the limit for the specific route that needs it, such as a bulk import, instead of raising it everywhere; the helper takes the limit as an option for exactly that reason. If a route must accept very large documents, do not buffer them at all. Stream the body to a parser or to disk, which is the approach covered in How to Stream a Large File in Node.js.


