Node.js body parsing middleware
body-parser is a middleware library for Node.js that extracts and parses the body of incoming HTTP requests, making the data available as JavaScript objects, strings, or buffers on the req.body property. It handles four primary content types: application/json, application/x-www-form-urlencoded, raw buffers, and plain text. The package automatically decompresses gzip, Brotli, and deflate-encoded payloads, making it transparent to your application code.
Originally developed as a standalone package, body-parser became the de facto standard for parsing request bodies in Express applications before being absorbed into Express core in version 4.16.0. Despite this integration, the standalone package continues to receive 70+ million weekly downloads, indicating widespread use in legacy codebases, custom frameworks, and projects requiring explicit dependency management. It provides robust error handling for malformed payloads, configurable size limits to prevent DoS attacks, and extensive options for customizing parsing behavior.
The package is particularly valuable in REST API development, webhook handlers, form processing, and any server-side application that receives structured data from clients. Its parsing factories are middleware functions that intercept requests matching specific Content-Type headers, transforming raw byte streams into usable JavaScript data structures. This abstraction eliminates boilerplate code and standardizes request handling across Node.js applications.
For new projects using Express 4.16+, the built-in express.json() and express.urlencoded() methods offer identical functionality without additional dependencies. However, body-parser remains essential for non-Express frameworks, custom HTTP servers built on Node's http module, or applications requiring the original implementation for compatibility reasons.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({
limit: '10mb',
strict: true,
type: 'application/json'
}));
app.use(bodyParser.urlencoded({
extended: true,
limit: '2mb',
parameterLimit: 1000
}));
app.use(bodyParser.raw({
type: 'application/octet-stream',
limit: '5mb'
}));
app.post('/api/users', (req, res) => {
const { name, email, preferences } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'Missing required fields' });
}
res.status(201).json({
id: Date.now(),
name,
email,
preferences: preferences || {}
});
});
app.post('/webhook/stripe', bodyParser.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['stripe-signature'];
const payload = req.body;
res.status(200).send('Webhook received');
});
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'Invalid JSON payload' });
}
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: 'Payload too large' });
}
next(err);
});
app.listen(3000, () => console.log('Server running on port 3000'));REST API Development: Parse JSON payloads from client applications making POST, PUT, or PATCH requests to store or update resources. The json() parser automatically converts stringified JSON into JavaScript objects, enabling direct property access and validation.
HTML Form Submissions: Handle traditional web form data encoded as application/x-www-form-urlencoded. The urlencoded() parser with extended: true supports nested objects and arrays, allowing complex form structures beyond simple key-value pairs.
Webhook Receivers: Process incoming webhook payloads from third-party services like Stripe, GitHub, or Shopify. The raw() parser preserves the original buffer for cryptographic signature verification before parsing, essential for security validation.
Content Management Systems: Accept and parse plain text content submissions, markdown documents, or CSV data using the text() parser, which maintains formatting and special characters without interpretation.
Microservices Communication: Parse internal service-to-service requests in distributed architectures where multiple content types flow between components, using middleware chaining to support JSON APIs alongside URL-encoded legacy endpoints.
npm install body-parserpnpm add body-parserbun add body-parser