README.md
1 # body-parser 2 3 [![NPM Version][npm-version-image]][npm-url] 4 [![NPM Downloads][npm-downloads-image]][npm-url] 5 [![Build Status][ci-image]][ci-url] 6 [![Test Coverage][coveralls-image]][coveralls-url] 7 [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] 8 9 Node.js body parsing middleware. 10 11 Parse incoming request bodies in a middleware before your handlers, available 12 under the `req.body` property. 13 14 **Note** As `req.body`'s shape is based on user-controlled input, all 15 properties and values in this object are untrusted and should be validated 16 before trusting. For example, `req.body.foo.toString()` may fail in multiple 17 ways, for example the `foo` property may not be there or may not be a string, 18 and `toString` may not be a function and instead a string or other user input. 19 20 [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). 21 22 _This does not handle multipart bodies_, due to their complex and typically 23 large nature. For multipart bodies, you may be interested in the following 24 modules: 25 26 * [busboy](https://www.npmjs.org/package/busboy#readme) and 27 [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) 28 * [multiparty](https://www.npmjs.org/package/multiparty#readme) and 29 [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) 30 * [formidable](https://www.npmjs.org/package/formidable#readme) 31 * [multer](https://www.npmjs.org/package/multer#readme) 32 33 This module provides the following parsers: 34 35 * [JSON body parser](#bodyparserjsonoptions) 36 * [Raw body parser](#bodyparserrawoptions) 37 * [Text body parser](#bodyparsertextoptions) 38 * [URL-encoded form body parser](#bodyparserurlencodedoptions) 39 40 Other body parsers you might be interested in: 41 42 - [body](https://www.npmjs.org/package/body#readme) 43 - [co-body](https://www.npmjs.org/package/co-body#readme) 44 45 ## Installation 46 47 ```sh 48 $ npm install body-parser 49 ``` 50 51 ## API 52 53 ```js 54 const bodyParser = require('body-parser') 55 ``` 56 57 The `bodyParser` object exposes various factories to create middlewares. All 58 middlewares will populate the `req.body` property with the parsed body when 59 the `Content-Type` request header matches the `type` option. 60 61 The various errors returned by this module are described in the 62 [errors section](#errors). 63 64 ### bodyParser.json([options]) 65 66 Returns middleware that only parses `json` and only looks at requests where 67 the `Content-Type` header matches the `type` option. This parser accepts any 68 Unicode encoding of the body and supports automatic inflation of `gzip`, 69 `br` (brotli) and `deflate` encodings. 70 71 A new `body` object containing the parsed data is populated on the `request` 72 object after the middleware (i.e. `req.body`). 73 74 #### Options 75 76 The `json` function takes an optional `options` object that may contain any of 77 the following keys: 78 79 ##### inflate 80 81 When set to `true`, then deflated (compressed) bodies will be inflated; when 82 `false`, deflated bodies are rejected. Defaults to `true`. 83 84 ##### limit 85 86 Controls the maximum request body size. If this is a number, then the value 87 specifies the number of bytes; if it is a string, the value is passed to the 88 [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults 89 to `'100kb'`. 90 91 ##### reviver 92 93 The `reviver` option is passed directly to `JSON.parse` as the second 94 argument. You can find more information on this argument 95 [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). 96 97 ##### strict 98 99 When set to `true`, will only accept arrays and objects; when `false` will 100 accept anything `JSON.parse` accepts. Defaults to `true`. 101 102 ##### type 103 104 The `type` option is used to determine what media type the middleware will 105 parse. This option can be a string, array of strings, or a function. If not a 106 function, `type` option is passed directly to the 107 [type-is](https://www.npmjs.org/package/type-is#readme) library and this can 108 be an extension name (like `json`), a mime type (like `application/json`), or 109 a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` 110 option is called as `fn(req)` and the request is parsed if it returns a truthy 111 value. Defaults to `application/json`. 112 113 ##### verify 114 115 The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, 116 where `buf` is a `Buffer` of the raw request body and `encoding` is the 117 encoding of the request. The parsing can be aborted by throwing an error. 118 119 ### bodyParser.raw([options]) 120 121 Returns middleware that parses all bodies as a `Buffer` and only looks at 122 requests where the `Content-Type` header matches the `type` option. This 123 parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` 124 encodings. 125 126 A new `body` object containing the parsed data is populated on the `request` 127 object after the middleware (i.e. `req.body`). This will be a `Buffer` object 128 of the body. 129 130 #### Options 131 132 The `raw` function takes an optional `options` object that may contain any of 133 the following keys: 134 135 ##### inflate 136 137 When set to `true`, then deflated (compressed) bodies will be inflated; when 138 `false`, deflated bodies are rejected. Defaults to `true`. 139 140 ##### limit 141 142 Controls the maximum request body size. If this is a number, then the value 143 specifies the number of bytes; if it is a string, the value is passed to the 144 [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults 145 to `'100kb'`. 146 147 ##### type 148 149 The `type` option is used to determine what media type the middleware will 150 parse. This option can be a string, array of strings, or a function. 151 If not a function, `type` option is passed directly to the 152 [type-is](https://www.npmjs.org/package/type-is#readme) library and this 153 can be an extension name (like `bin`), a mime type (like 154 `application/octet-stream`), or a mime type with a wildcard (like `*/*` or 155 `application/*`). If a function, the `type` option is called as `fn(req)` 156 and the request is parsed if it returns a truthy value. Defaults to 157 `application/octet-stream`. 158 159 ##### verify 160 161 The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, 162 where `buf` is a `Buffer` of the raw request body and `encoding` is the 163 encoding of the request. The parsing can be aborted by throwing an error. 164 165 ### bodyParser.text([options]) 166 167 Returns middleware that parses all bodies as a string and only looks at 168 requests where the `Content-Type` header matches the `type` option. This 169 parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` 170 encodings. 171 172 A new `body` string containing the parsed data is populated on the `request` 173 object after the middleware (i.e. `req.body`). This will be a string of the 174 body. 175 176 #### Options 177 178 The `text` function takes an optional `options` object that may contain any of 179 the following keys: 180 181 ##### defaultCharset 182 183 Specify the default character set for the text content if the charset is not 184 specified in the `Content-Type` header of the request. Defaults to `utf-8`. 185 186 ##### inflate 187 188 When set to `true`, then deflated (compressed) bodies will be inflated; when 189 `false`, deflated bodies are rejected. Defaults to `true`. 190 191 ##### limit 192 193 Controls the maximum request body size. If this is a number, then the value 194 specifies the number of bytes; if it is a string, the value is passed to the 195 [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults 196 to `'100kb'`. 197 198 ##### type 199 200 The `type` option is used to determine what media type the middleware will 201 parse. This option can be a string, array of strings, or a function. If not 202 a function, `type` option is passed directly to the 203 [type-is](https://www.npmjs.org/package/type-is#readme) library and this can 204 be an extension name (like `txt`), a mime type (like `text/plain`), or a mime 205 type with a wildcard (like `*/*` or `text/*`). If a function, the `type` 206 option is called as `fn(req)` and the request is parsed if it returns a 207 truthy value. Defaults to `text/plain`. 208 209 ##### verify 210 211 The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, 212 where `buf` is a `Buffer` of the raw request body and `encoding` is the 213 encoding of the request. The parsing can be aborted by throwing an error. 214 215 ### bodyParser.urlencoded([options]) 216 217 Returns middleware that only parses `urlencoded` bodies and only looks at 218 requests where the `Content-Type` header matches the `type` option. This 219 parser accepts only UTF-8 encoding of the body and supports automatic 220 inflation of `gzip`, `br` (brotli) and `deflate` encodings. 221 222 A new `body` object containing the parsed data is populated on the `request` 223 object after the middleware (i.e. `req.body`). This object will contain 224 key-value pairs, where the value can be a string or array (when `extended` is 225 `false`), or any type (when `extended` is `true`). 226 227 #### Options 228 229 The `urlencoded` function takes an optional `options` object that may contain 230 any of the following keys: 231 232 ##### extended 233 234 The "extended" syntax allows for rich objects and arrays to be encoded into the 235 URL-encoded format, allowing for a JSON-like experience with URL-encoded. For 236 more information, please [see the qs 237 library](https://www.npmjs.org/package/qs#readme). 238 239 Defaults to `false`. 240 241 ##### inflate 242 243 When set to `true`, then deflated (compressed) bodies will be inflated; when 244 `false`, deflated bodies are rejected. Defaults to `true`. 245 246 ##### limit 247 248 Controls the maximum request body size. If this is a number, then the value 249 specifies the number of bytes; if it is a string, the value is passed to the 250 [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults 251 to `'100kb'`. 252 253 ##### parameterLimit 254 255 The `parameterLimit` option controls the maximum number of parameters that 256 are allowed in the URL-encoded data. If a request contains more parameters 257 than this value, a 413 will be returned to the client. Defaults to `1000`. 258 259 ##### type 260 261 The `type` option is used to determine what media type the middleware will 262 parse. This option can be a string, array of strings, or a function. If not 263 a function, `type` option is passed directly to the 264 [type-is](https://www.npmjs.org/package/type-is#readme) library and this can 265 be an extension name (like `urlencoded`), a mime type (like 266 `application/x-www-form-urlencoded`), or a mime type with a wildcard (like 267 `*/x-www-form-urlencoded`). If a function, the `type` option is called as 268 `fn(req)` and the request is parsed if it returns a truthy value. Defaults 269 to `application/x-www-form-urlencoded`. 270 271 ##### verify 272 273 The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, 274 where `buf` is a `Buffer` of the raw request body and `encoding` is the 275 encoding of the request. The parsing can be aborted by throwing an error. 276 277 ##### defaultCharset 278 279 The default charset to parse as, if not specified in content-type. Must be 280 either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. 281 282 ##### charsetSentinel 283 284 Whether to let the value of the `utf8` parameter take precedence as the charset 285 selector. It requires the form to contain a parameter named `utf8` with a value 286 of `✓`. Defaults to `false`. 287 288 ##### interpretNumericEntities 289 290 Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 291 form. Defaults to `false`. 292 293 294 #### depth 295 296 The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. 297 298 ## Errors 299 300 The middlewares provided by this module create errors using the 301 [`http-errors` module](https://www.npmjs.com/package/http-errors). The errors 302 will typically have a `status`/`statusCode` property that contains the suggested 303 HTTP response code, an `expose` property to determine if the `message` property 304 should be displayed to the client, a `type` property to determine the type of 305 error without matching against the `message`, and a `body` property containing 306 the read body, if available. 307 308 The following are the common errors created, though any error can come through 309 for various reasons. 310 311 ### content encoding unsupported 312 313 This error will occur when the request had a `Content-Encoding` header that 314 contained an encoding but the "inflation" option was set to `false`. The 315 `status` property is set to `415`, the `type` property is set to 316 `'encoding.unsupported'`, and the `charset` property will be set to the 317 encoding that is unsupported. 318 319 ### entity parse failed 320 321 This error will occur when the request contained an entity that could not be 322 parsed by the middleware. The `status` property is set to `400`, the `type` 323 property is set to `'entity.parse.failed'`, and the `body` property is set to 324 the entity value that failed parsing. 325 326 ### entity verify failed 327 328 This error will occur when the request contained an entity that could not be 329 failed verification by the defined `verify` option. The `status` property is 330 set to `403`, the `type` property is set to `'entity.verify.failed'`, and the 331 `body` property is set to the entity value that failed verification. 332 333 ### request aborted 334 335 This error will occur when the request is aborted by the client before reading 336 the body has finished. The `received` property will be set to the number of 337 bytes received before the request was aborted and the `expected` property is 338 set to the number of expected bytes. The `status` property is set to `400` 339 and `type` property is set to `'request.aborted'`. 340 341 ### request entity too large 342 343 This error will occur when the request body's size is larger than the "limit" 344 option. The `limit` property will be set to the byte limit and the `length` 345 property will be set to the request body's length. The `status` property is 346 set to `413` and the `type` property is set to `'entity.too.large'`. 347 348 ### request size did not match content length 349 350 This error will occur when the request's length did not match the length from 351 the `Content-Length` header. This typically occurs when the request is malformed, 352 typically when the `Content-Length` header was calculated based on characters 353 instead of bytes. The `status` property is set to `400` and the `type` property 354 is set to `'request.size.invalid'`. 355 356 ### stream encoding should not be set 357 358 This error will occur when something called the `req.setEncoding` method prior 359 to this middleware. This module operates directly on bytes only and you cannot 360 call `req.setEncoding` when using this module. The `status` property is set to 361 `500` and the `type` property is set to `'stream.encoding.set'`. 362 363 ### stream is not readable 364 365 This error will occur when the request is no longer readable when this middleware 366 attempts to read it. This typically means something other than a middleware from 367 this module read the request body already and the middleware was also configured to 368 read the same request. The `status` property is set to `500` and the `type` 369 property is set to `'stream.not.readable'`. 370 371 ### too many parameters 372 373 This error will occur when the content of the request exceeds the configured 374 `parameterLimit` for the `urlencoded` parser. The `status` property is set to 375 `413` and the `type` property is set to `'parameters.too.many'`. 376 377 ### unsupported charset "BOGUS" 378 379 This error will occur when the request had a charset parameter in the 380 `Content-Type` header, but the `iconv-lite` module does not support it OR the 381 parser does not support it. The charset is contained in the message as well 382 as in the `charset` property. The `status` property is set to `415`, the 383 `type` property is set to `'charset.unsupported'`, and the `charset` property 384 is set to the charset that is unsupported. 385 386 ### unsupported content encoding "bogus" 387 388 This error will occur when the request had a `Content-Encoding` header that 389 contained an unsupported encoding. The encoding is contained in the message 390 as well as in the `encoding` property. The `status` property is set to `415`, 391 the `type` property is set to `'encoding.unsupported'`, and the `encoding` 392 property is set to the encoding that is unsupported. 393 394 ### The input exceeded the depth 395 396 This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown. 397 398 ## Examples 399 400 ### Express/Connect top-level generic 401 402 This example demonstrates adding a generic JSON and URL-encoded parser as a 403 top-level middleware, which will parse the bodies of all incoming requests. 404 This is the simplest setup. 405 406 ```js 407 const express = require('express') 408 const bodyParser = require('body-parser') 409 410 const app = express() 411 412 // parse application/x-www-form-urlencoded 413 app.use(bodyParser.urlencoded()) 414 415 // parse application/json 416 app.use(bodyParser.json()) 417 418 app.use(function (req, res) { 419 res.setHeader('Content-Type', 'text/plain') 420 res.write('you posted:\n') 421 res.end(String(JSON.stringify(req.body, null, 2))) 422 }) 423 ``` 424 425 ### Express route-specific 426 427 This example demonstrates adding body parsers specifically to the routes that 428 need them. In general, this is the most recommended way to use body-parser with 429 Express. 430 431 ```js 432 const express = require('express') 433 const bodyParser = require('body-parser') 434 435 const app = express() 436 437 // create application/json parser 438 const jsonParser = bodyParser.json() 439 440 // create application/x-www-form-urlencoded parser 441 const urlencodedParser = bodyParser.urlencoded() 442 443 // POST /login gets urlencoded bodies 444 app.post('/login', urlencodedParser, function (req, res) { 445 if (!req.body || !req.body.username) res.sendStatus(400) 446 res.send('welcome, ' + req.body.username) 447 }) 448 449 // POST /api/users gets JSON bodies 450 app.post('/api/users', jsonParser, function (req, res) { 451 if (!req.body) res.sendStatus(400) 452 // create user in req.body 453 }) 454 ``` 455 456 ### Change accepted type for parsers 457 458 All the parsers accept a `type` option which allows you to change the 459 `Content-Type` that the middleware will parse. 460 461 ```js 462 const express = require('express') 463 const bodyParser = require('body-parser') 464 465 const app = express() 466 467 // parse various different custom JSON types as JSON 468 app.use(bodyParser.json({ type: 'application/*+json' })) 469 470 // parse some custom thing into a Buffer 471 app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) 472 473 // parse an HTML body into a string 474 app.use(bodyParser.text({ type: 'text/html' })) 475 ``` 476 477 ## License 478 479 [MIT](LICENSE) 480 481 [ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci 482 [ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml 483 [coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master 484 [coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master 485 [node-version-image]: https://badgen.net/npm/node/body-parser 486 [node-version-url]: https://nodejs.org/en/download 487 [npm-downloads-image]: https://badgen.net/npm/dm/body-parser 488 [npm-url]: https://npmjs.org/package/body-parser 489 [npm-version-image]: https://badgen.net/npm/v/body-parser 490 [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge 491 [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser