Fix PayloadTooLargeError: request entity too large in Express
This error occurs when the request body exceeds the size limit configured in Express's body-parser or express.json() middleware. The default limit is 100kb. Fix it by increasing the limit for routes that need larger payloads, adding a custom error handler for 413 responses, and validating payload sizes on the client side.
Reading the Stack Trace
Here's what each line means:
- at readStream (/app/node_modules/raw-body/index.js:155:17): The raw-body module detected the incoming stream exceeds the configured byte limit and threw PayloadTooLargeError.
- at jsonParser (/app/node_modules/body-parser/lib/types/json.js:135:5): The JSON body-parser middleware triggered the read which detected the oversized payload.
- at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5): Express is executing the body-parser middleware layer which enforces the payload size limit.
Common Causes
1. Default 100kb limit too small
The default express.json() limit of 100kb is too small for endpoints that accept large payloads like file metadata or batch operations.
const app = express();
app.use(express.json()); // Default 100kb limit
app.post('/api/import', (req, res) => {
// Receives large JSON array with thousands of records
res.json({ imported: req.body.length });
});
2. Global limit applied to all routes
A single global limit is too restrictive for some endpoints and too permissive for others.
app.use(express.json({ limit: '100kb' })); // Same limit for all routes
app.post('/api/simple', handler); // 100kb is fine
app.post('/api/bulk-import', handler); // 100kb is too small
3. No error handling for 413 responses
The application does not handle PayloadTooLargeError, returning the default Express error page instead of a helpful JSON response.
app.use(express.json({ limit: '1mb' }));
app.post('/api/data', (req, res) => {
res.json({ received: true });
});
// No error handler for PayloadTooLargeError
The Fix
Set a reasonable default payload limit and override it per-route where larger payloads are expected. Add error-handling middleware that catches PayloadTooLargeError and returns a JSON response with the maximum allowed size.
const app = express();
app.use(express.json());
app.post('/api/import', (req, res) => {
res.json({ imported: req.body.length });
});
app.listen(3000);
const app = express();
// Default limit for most routes
app.use(express.json({ limit: '1mb' }));
// Higher limit for specific routes that need it
app.post('/api/import', express.json({ limit: '10mb' }), (req, res) => {
res.json({ imported: req.body.length });
});
// Error handler for oversized payloads
app.use((err, req, res, next) => {
if (err.type === 'entity.too.large') {
return res.status(413).json({
error: 'Payload too large',
maxSize: err.limit,
message: 'The request body exceeds the maximum allowed size.'
});
}
next(err);
});
app.listen(3000);
Testing the Fix
const request = require('supertest');
const express = require('express');
function createApp() {
const app = express();
app.use(express.json({ limit: '1kb' })); // Small limit for testing
app.post('/api/data', (req, res) => res.json({ received: true }));
app.use((err, req, res, next) => {
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: 'Payload too large' });
}
next(err);
});
return app;
}
describe('Payload size limits', () => {
it('accepts payloads under the limit', async () => {
const res = await request(createApp())
.post('/api/data')
.send({ small: 'data' });
expect(res.status).toBe(200);
expect(res.body.received).toBe(true);
});
it('returns 413 for payloads over the limit', async () => {
const largePayload = { data: 'x'.repeat(2000) };
const res = await request(createApp())
.post('/api/data')
.send(largePayload);
expect(res.status).toBe(413);
expect(res.body.error).toBe('Payload too large');
});
});
Run your tests:
npx jest --testPathPattern=payload
Pushing Through CI/CD
git checkout -b fix/express-payload-too-large,git add src/app.js src/__tests__/payload.test.js,git commit -m "fix: configure per-route payload limits and 413 error handler",git push origin fix/express-payload-too-large
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx jest --coverage
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm payload limits work correctly for all routes.
- Open a pull request with the payload limit configuration changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify large payloads are handled in staging before promoting to production.
Frequently Asked Questions
BugStack tests with payloads above and below each route's limit, verifies correct 413 and 200 responses, and confirms no existing functionality is broken before marking it safe.
Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.
It depends on your use case. For typical JSON APIs, 1-5MB is reasonable. For file uploads, use multer or streaming instead of express.json(). Never set unlimited payload sizes as this enables denial-of-service attacks.
Yes. Use express.json({ limit: '1mb' }) and express.urlencoded({ limit: '5mb' }) separately, or apply per-route middleware with different limits for specific endpoints.