Payload limit behavior of express.json middleware in Express 4 vs 5
0 reputation · 14 Feb 2024, 08:31 UTC
0 reputation · 14 Feb 2024, 08:31 UTC
Goal: Clarify whether exceeding the limit set on express.json results in a synchronous error that skips async error-handling middleware, and if this behavior differs between Express 4 and Express 5 given the latter's revised promise error propagation.
Constraints: The limit option causes the parser to respond with 413 Payload Too Large before any route is invoked, but documentation does not specify whether the error is passed to next(err) synchronously or asynchronously. Because Express 5 changes how errors from asynchronous route handlers are processed, it is uncertain whether the limit-induced error follows the same path in both versions, potentially affecting where custom error handlers can intercept it.
Questions: Does express.json emit a synchronous next(err) when the payload exceeds the configured limit in Express 4? Does Express 5 treat this error as an asynchronous rejection that goes through its new error-handling flow? Can a single error-handling middleware reliably catch limit errors across both major releases?
29275 reputation · 14 Feb 2024, 11:06 UTC
When express.json receives a body larger than the configured limit, it immediately calls next(err) inside the middleware itself. That call is synchronous in both Express 4 and Express 5. The error object has type entity.too.large and status 413.
The body‑parser implementation that powers express.json performs the size check during the request‑body stream parsing. As soon as the size threshold is crossed, the parser emits an entity.too.large error and synchronously hands it to Express via next(err). Express then skips the rest of the normal middleware stack and looks for the next error‑handling middleware.
Express 5’s major change is automatic handling of rejected promises in route handlers. Middleware errors, including the size‑limit error described above, are still propagated synchronously. The new promise plumbing does not touch the synchronous next(err) path, so the 413 error follows the same route as in Express 4.
const express = require('express');const app = express();app.use(express.json({ limit: '10kb' }));app.use((err, req, res, next) => {if (err.type === 'entity.too.large') {return res.status(413).json({ error: 'Payload too large' });next(err);app.post('/upload', (req, res) => res.send('OK'));app.listen(3000);Sending a body larger than 10 KB will trigger the error handler and return a 413 response in both Express 4 and Express 5.
If the error handler never runs, check that it is defined *after* the express.json middleware and that no earlier middleware consumes the request body or calls next() without forwarding the error. If those conditions are met and the handler still misses the error, the issue is likely elsewhere in the stack.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.