AceDevHub
Intermediate Node.js Interview QuestionsIntermediatePractical

Node.js · Question 46

How do you parse JSON request bodies in Node.js?

Direct answer

Use express.json() middleware or manually read req stream and JSON.parse — set size limits, validate schema after parse, return 400 on malformed JSON; Fastify parses JSON bodies when Content-Type is application/json.

POST/PUT/PATCH bodies arrive as a readable stream on req — parsers aggregate chunks into req.body before your handler runs.

  • express.json() — built-in since Express 4.16; replaces body-parser for JSON.
  • Limit option — express.json({ limit: '100kb' }) prevents large payload DoS.
  • Content-Type — parser runs only when header is application/json.
  • Validation — Zod/Fastify schema after parse; never trust shape from client.
json-body.mjs
import express from "express";

const app = express();
app.use(express.json({ limit: "256kb" }));

app.post("/waitlist", (req, res) => {
  const { email, courseSlug } = req.body ?? {};
  if (!email || !courseSlug) {
    return res.status(400).json({ error: "email and courseSlug required" });
  }
  res.status(201).json({ ok: true });
});

// Raw http: collect chunks (Q28) then JSON.parse with try/catch