body-parser: Node.js Body Parsing Middleware
body-parser is a Node.js middleware for parsing incoming request bodies, making them available under the `req.body` property in web frameworks like Express. It supports JSON, URL-encoded forms, raw buffers, and plain text, but explicitly does not handle multipart form data. The current stable version is 2.2.2, with active development and maintenance occurring across both the v1.x and v2.x major release lines.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'body')
cause The appropriate `body-parser` middleware was not used for the request's `Content-Type`, or the header was missing/incorrect.fixEnsure `app.use()` calls for `bodyParser.json()`, `bodyParser.urlencoded()`, etc., are correctly placed before your routes, and verify the client sends the correct `Content-Type` header (e.g., `application/json`). -
PayloadTooLargeError: request entity too large
cause The incoming request body exceeded the configured `limit` option for the active body parser.fixIncrease the `limit` option for the relevant parser. For example, to allow up to 5MB JSON: `app.use(bodyParser.json({ limit: '5mb' }))`. -
SyntaxError: Unexpected token < in JSON at position 0
cause The request body sent with `Content-Type: application/json` was not valid JSON, or the content type was mismatched.fixVerify that the client is sending well-formed JSON data. If the client is sending HTML or another format, adjust the `Content-Type` header or use the appropriate `body-parser` middleware (e.g., `bodyParser.text()`). -
RangeError: Maximum call stack size exceeded
cause A URL-encoded request body contained deeply nested data that exceeded the `depth` option (defaulting to 32) of the `urlencoded` parser.fixIf deeply nested URL-encoded data is expected, increase the `depth` option: `app.use(bodyParser.urlencoded({ extended: true, depth: 64 }))`. -
TypeError: body-parser.json is not a function
cause This usually indicates `body-parser` was imported or required incorrectly, or an attempt was made to call a parser method on an undefined `body-parser` object.fixEnsure `body-parser` is correctly imported/required (e.g., `const bodyParser = require('body-parser')` or `import bodyParser from 'body-parser';`) and that parser methods are called on the `bodyParser` object, like `bodyParser.json()`.
Warnings
- breaking Version 2.0.0 elevated the minimum supported Node.js version to 18.
- breaking The combined `bodyParser()` middleware was removed in v2.x. You must now explicitly use specific parsers like `bodyParser.json()` or `bodyParser.urlencoded()`.
- breaking The default `depth` for URL-encoded parsing was changed from `Infinity` to `32` in v1.20.3 (and carried into v2.x), limiting nested object/array depth.
- gotcha `req.body` contains user-controlled input and its properties should always be validated before use to prevent security vulnerabilities (e.g., prototype pollution) or runtime errors.
- gotcha `body-parser` does not handle `multipart/form-data` request bodies, which are commonly used for file uploads.
Install
-
npm install body-parser -
yarn add body-parser -
pnpm add body-parser
Imports
- bodyParser
const bodyParser = require('body-parser')
Quickstart
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
const port = process.env.PORT ?? 3000;
// Middleware to parse JSON bodies
app.use(bodyParser.json());
// Middleware to parse URL-encoded bodies (e.g., from HTML forms)
// 'extended: true' allows parsing of rich objects and arrays from URL-encoded data
app.use(bodyParser.urlencoded({ extended: true }));
// Example POST endpoint to receive data
app.post('/api/data', (req, res) => {
console.log('Received body:', req.body);
// req.body contains the parsed data based on Content-Type
res.json({ message: 'Data received successfully!', data: req.body });
});
// Start the server
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});