Fixing Node.js & Express Error: Request Entity Too Large

Updated: December 28, 2023 By: Guest Contributor Post a comment

When developing with Node.js and Express, you might encounter an error stating ‘request entity too large’. This error occurs when a client sends a request to the server with a body payload that exceeds the maximum limit the server is willing to accept.

Understanding the Error

This limit is in place to protect your server against potential denial-of-service (DoS) attacks, which could be caused by very large payloads. By default, Express uses a middleware called body-parser with a limit of 100kb. If the size of the request body exceeds this, the error is issued.

How to Fix the Error

1. Increasing the Payload Size Limit

To fix this error, you can increase the payload size limit using the body-parser middleware:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Increase the payload size limit, e.g., to 50mb
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ 
    limit: '50mb', 
    extended: true 
}));

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

2. Using Express’s Built-In Middleware

In newer versions of Express (`^4.16.0`), you can directly set the limit using the built-in middleware without separately including body-parser:

const express = require('express');
const app = express();

// Set limit to 50mb for JSON and URL-encoded bodies
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ 
    limit: '50mb', 
    extended: true 
}));

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

3. Handling the Error Gracefully

If you prefer not to increase the payload limit for security reasons, you can handle the error more gracefully and provide a meaningful response to the client:

const express = require('express');
const app = express();

// Set JSON payload limit to 100kb
app.use(express.json({ limit: '100kb' }));

// Error handling middleware
app.use((err, req, res, next) => {
    if (err.status === 413) {
        return res.status(413).json({ message: 'Payload too large' });
    }
    next(err);
});

// Start the server
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

These fixes should help resolve the ‘request entity too large’ error in a Node.js and Express application, improving your system’s robustness and the user experience.