How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Express · JavaScript

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

PayloadTooLargeError: request entity too large at readStream (/app/node_modules/raw-body/index.js:155:17) at getRawBody (/app/node_modules/raw-body/index.js:108:12) at read (/app/node_modules/body-parser/lib/read.js:77:3) at jsonParser (/app/node_modules/body-parser/lib/types/json.js:135:5) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/app/node_modules/express/lib/router/index.js:328:13) at /app/node_modules/express/lib/router/index.js:284:15 at Function.process_params (/app/node_modules/express/lib/router/index.js:346:12) at next (/app/node_modules/express/lib/router/index.js:280:10) at expressInit (/app/node_modules/express/lib/middleware/init.js:40:5)

Here's what each line means:

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.

Before (broken)
const app = express();
app.use(express.json());

app.post('/api/import', (req, res) => {
  res.json({ imported: req.body.length });
});

app.listen(3000);
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the test suite locally to confirm payload limits work correctly for all routes.
  2. Open a pull request with the payload limit configuration changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.