Introduction
Most modern APIs exchange data in JSON format. When a client sends a POST or PUT request with a JSON body, Express does not parse it automatically — you must enable body-parsing middleware first. Express 4.16+ ships with a built-in express.json() middleware that handles this without needing a separate body-parser package.
Cricket analogy: A scorer receiving a handwritten note from the boundary doesn't automatically understand it; someone must first translate it into the official scoring format before it counts, just as express.json() must parse the raw body first.
Syntax
const express = require('express');
const app = express();
app.use(express.json()); // parses application/json bodies
app.post('/echo', (req, res) => {
res.json(req.body);
});Explanation
express.json() is middleware that inspects the Content-Type header of incoming requests; if it is application/json, it parses the raw request body and attaches the resulting object to req.body. Without this middleware, req.body is undefined. The middleware must be registered with app.use() before any routes that need to read req.body. You can also set an options object, such as { limit: '1mb' }, to guard against overly large payloads.
Cricket analogy: express.json() checks the delivery type label before deciding how to score it — only if it's a legal delivery (application/json) does it get recorded in the scorebook (req.body); a 1MB limit caps how big a single scoring entry can be.
Example
app.use(express.json({ limit: '1mb' }));
app.post('/users', (req, res) => {
const { name, age } = req.body;
if (typeof name !== 'string' || typeof age !== 'number') {
return res.status(400).json({ error: 'Invalid payload' });
}
res.status(201).json({ name, age });
});Output
Sending POST /users with a JSON body { "name": "Ana", "age": 30 } and header Content-Type: application/json returns 201 Created with the same data echoed back. Sending malformed JSON causes express.json() to throw a parsing error, which is passed to Express's error-handling mechanism.
Cricket analogy: It's like submitting a valid team sheet and getting it stamped 'accepted' with the same details echoed back, but a garbled, illegible sheet gets rejected and flagged to the match referee (error handler).
Key Takeaways
- express.json() must be registered with app.use() before routes that need req.body.
- Without body-parsing middleware, req.body is undefined for JSON requests.
- The Content-Type header must be application/json for express.json() to parse the body.
- Options like { limit: '1mb' } help guard against excessively large request bodies.
- Malformed JSON in the request body triggers a parsing error handled by Express's error middleware.
Practice what you learned
1. What must be true for express.json() to parse the incoming request body?
2. Where must app.use(express.json()) be placed relative to routes that use req.body?
3. What is req.body if express.json() middleware is never registered?
4. What happens when a client sends malformed JSON to a route protected by express.json()?
Was this page helpful?
You May Also Like
Request and Response Objects in Express
Explore the key properties and methods of Express's req and res objects used to read requests and craft responses.
Data Validation in Express
Validate incoming request data in Express using schema-based validation before it reaches your database layer.
Middleware in Express
Master the Express middleware chain, the next() function, and the special error-handling middleware signature.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics