In Express 5, what do the limit, type, strict and verify options of express.json control, and how does each one fail a request?
answer
- size, media type, shape, raw bytes
- skip versus error
- 100kb and application/json
- verify sees the Buffer
- error type strings for mapping
basics
~20 slimit caps body size (100kb default, 413 when exceeded), type picks which Content-Type is parsed (others are skipped), strict accepts only objects and arrays (else 400), and verify inspects the raw Buffer, failing with 403 when it throws.
solid answer
~40 s`express.json()` wraps the body-parser JSON parser. `limit` defaults to `'100kb'`; a larger body fails with a 413 error whose `type` is `'entity.too.large'`. `type` defaults to `'application/json'` and accepts a string, an array or a function; a request that does not match is not an error, it is skipped and `req.body` stays `undefined`. `strict`, on by default, accepts only objects and arrays, so a bare `"hello"` fails with 400 `'entity.parse.failed'`, as does malformed JSON. `verify(req, res, buf, encoding)` runs on the raw Buffer before parsing; throwing aborts with 403 `'entity.verify.failed'`, and it is the usual place to keep the raw bytes for a webhook signature. Every failure goes to `next(err)` as an error carrying `status` and `type`.
code
javascript · 22 linesconst express = require('express');
const app = express();
// Registered first, so this parser reads the stream and verify sees the bytes.
app.post(
'/webhooks/payments',
express.json({
limit: '1mb',
type: ['application/json', 'application/*+json'],
verify(req, res, buf) {
req.rawBody = buf; // keep the exact bytes for signature checking
},
}),
(req, res) => {
// compare an HMAC of req.rawBody with req.get('X-Signature') here
res.sendStatus(204);
},
);
app.use(express.json()); // routes registered below: 100kb, application/json only
app.listen(3000);go deeper
Know that express.json() has a 100kb default limit and only parses requests sent as application/json.
Explain each option's default and its failure: 413 for limit, a silent skip for type, 400 for strict, 403 when verify throws, all through next(err).
Scope limits per route, map errors by err.type, and wire verify for signed webhooks before the app-wide parser so it actually sees the bytes.
Set the house defaults for body size and accepted media types, and decide which routes may raise them and who reviews that exception.
## What `express.json()` is `express.json()` is Express's built-in JSON body parser, based on the body-parser package. It returns a middleware that reads the request stream, decodes it and sets `req.body`. Its options decide **which requests it reads**, **how much it reads**, and **what counts as acceptable**. The same option names, with different defaults, exist on `express.urlencoded()`, `express.text()` and `express.raw()`. ## The options and their defaults | Option | Default | Controls | When it trips | |---|---|---|---| | `limit` | `'100kb'` | maximum body size; a number of bytes or a string such as `'1mb'` | 413, `type: 'entity.too.large'` | | `type` | `'application/json'` | which `Content-Type` is parsed; string, array or `fn(req)` | never an error: the request is skipped | | `strict` | `true` | only objects and arrays at the top level | 400, `type: 'entity.parse.failed'` | | `verify` | none | a hook called with the raw `Buffer` before parsing | 403, `type: 'entity.verify.failed'` when it throws | | `inflate` | `true` | decompressing gzip, deflate and Brotli bodies | 415 for a compressed body when set to `false` | | `reviver` | none | passed to `JSON.parse` as its second argument | as `JSON.parse` behaves | Malformed JSON also fails with 400 `'entity.parse.failed'`, and the JSON parser rejects a declared charset that is not a UTF encoding with 415. ## How failures reach your code The parser never writes a response itself. It calls `next(err)` with an error object that carries `status` (and `statusCode`), a machine-readable `type` such as `'entity.too.large'`, and `expose`, which says whether the message is safe to show a client. Express's default error handler answers with that status. A custom error handler can switch on `err.type` instead of matching message text, which is the reason those strings exist. The one case that is **not** an error is a `Content-Type` mismatch. If a client sends JSON labelled `text/plain`, `express.json()` simply calls `next()` and the handler finds `req.body` undefined. Widen `type` deliberately, for example `['application/json', 'application/*+json']`, when a client legitimately sends a vendor JSON type. ## `limit`: per route, not just global The 100kb default is intentionally small; the body-parser documentation warns that limits well above it raise memory use and response times. Raise it on the one route that needs it rather than globally: - mount `express.json()` with the default for the app; - mount `express.json({ limit: '1mb' })` directly on the import route. Since Express 5.3.0 (which depends on body-parser `^2.3.0`), a `limit` string the bytes parser cannot read, such as `'abc'`, throws when the middleware is created. Before that fix, an invalid value silently disabled the size check, a fail-open bug published as a CVE. ## `verify`: the raw bytes `verify(req, res, buf, encoding)` receives the exact bytes the client sent. Webhook senders sign those bytes, and re-serialising `req.body` will not reproduce them, so the common pattern is: 1. mount a route-specific `express.json({ verify })` on the webhook path; 2. inside `verify`, copy `buf` onto the request (or check the signature and throw on a mismatch); 3. in the handler, compare an HMAC of the saved bytes with the signature header. **Order matters.** If an app-wide `express.json()` runs first, it consumes the stream; the route-level parser sees a body that was already read, skips, and its `verify` never runs. Register the webhook route, with its own parser, before the app-wide one. ## Mounting patterns that work - **One app-wide parser** near the top, `app.use(express.json())`, covers most JSON APIs with the defaults. - **Route-level parsers** carry the exceptions: a larger `limit` for an import endpoint, a wider `type` for a vendor media type, a `verify` hook for a webhook. - **Skip bodies you do not need.** A route that streams an upload to storage should not sit behind a parser that buffers the whole body into memory first. - **Map errors once.** A single error-handling middleware that reads `err.status` and `err.type` turns parser failures into the API's own error body, instead of the default handler's HTML page. A parser error never reaches the route handler: once `next(err)` is called, Express skips straight to error-handling middleware. ## The urlencoded counterpart `express.urlencoded()` shares `limit`, `type`, `verify` and `inflate`, and adds: - **`extended`**, which defaults to `false` in Express 5: Node's query-string parser, so `a[b]=1` stays a flat key. `true` switches to the `qs` library for nested objects. - **`parameterLimit`**, 1000 by default; more fields fail with 413 `'parameters.too.many'`. - **`depth`**, 32 by default, which caps nesting when `extended` is `true`.
- How would an error handler tell an oversized body apart from malformed JSON without parsing the message?Errors from the Express body parsers carry a `type` string. An oversized body has `type: 'entity.too.large'` and status 413; malformed or non-strict JSON has `type: 'entity.parse.failed'` and status 400. Switching on `err.type` and `err.status` is what those properties exist for; message text is not meant to be matched.
- Why does a webhook route's verify hook never run when express.json() is also mounted app-wide?If the app-wide parser runs first, it reads the whole stream and sets `req.body`. The route's parser then sees a request that has already been read and calls `next()` without parsing, so its `verify` is never called. Register the webhook route with its own parser before the app-wide `app.use(express.json())`.
- express.json() answers 415 when the Content-Type is not JSON
- The default limit is unlimited unless you set one
- strict: true means unknown fields in the object are rejected
- verify runs after parsing and receives req.body
- Raising the limit globally is the normal fix for one large route
Assumes Express 5.3.0 with body-parser 2.x: express.urlencoded's extended defaults to false and an invalid limit string now throws at creation.