How does body parsing work in Express.js?
Body Parsing in Express.js
When a client sends data (JSON, form, file), it arrives as a stream of bytes in the request body. Express's built-in body parsers read and parse this data, making it available on req.body.
Built-in Parsers (Express 4.16+)
const express = require('express');
const app = express();
// Parse JSON bodies: { "name": "Alice" }
app.use(express.json());
// Parse URL-encoded form bodies: name=Alice&age=30
app.use(express.urlencoded({ extended: true }));No extra packages needed — these are built into Express 4.16+.
express.json()
Parses requests with Content-Type: application/json.
app.use(express.json({ limit: '10mb' })); // increase size limit
app.post('/users', (req, res) => {
console.log(req.body); // { name: 'Alice', email: 'alice@example.com' }
res.status(201).json(req.body);
});Client must send: Content-Type: application/json header.
express.urlencoded()
Parses HTML form submissions (Content-Type: application/x-www-form-urlencoded).
app.use(express.urlencoded({ extended: true }));
// extended: true → uses 'qs' library (nested objects)
// extended: false → uses 'querystring' (flat only)
app.post('/login', (req, res) => {
const { username, password } = req.body;
// ...
});Raw & Text Parsers
// Parse raw binary body
app.use(express.raw({ type: 'application/octet-stream' }));
// Parse plain text body
app.use(express.text({ type: 'text/plain' }));File Uploads with Multer
For multipart/form-data (file uploads), use the multer package:
npm install multerconst multer = require('multer');
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage, limits: { fileSize: 5 * 1024 * 1024 } }); // 5MB
app.post('/upload', upload.single('avatar'), (req, res) => {
console.log(req.file); // uploaded file info
console.log(req.body); // other form fields
res.json({ filename: req.file.filename });
});
// Multiple files
app.post('/photos', upload.array('photos', 5), (req, res) => {
console.log(req.files); // array of files
});Route-Specific Parsing
Apply parsers only to specific routes:
// Only parse JSON for API routes
app.use('/api', express.json());
// Different limits per route
app.post('/webhook',
express.raw({ type: 'application/json' }), // raw for Stripe webhook verification
handleWebhook
);Common Mistakes
// ❌ Forgot to add body parser
app.post('/users', (req, res) => {
console.log(req.body); // undefined!
});
// ✅ Add BEFORE route definitions
app.use(express.json());
app.post('/users', (req, res) => {
console.log(req.body); // { name: 'Alice' }
});Summary
Use express.json() for API endpoints and express.urlencoded() for HTML forms. Add these middleware at the top of your app, before route definitions. For file uploads, use the multer package.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.