Express applications that use the body-parser
middleware have a default limit to the request body size that the application will handle. This default limit is 100kb. So, if your application receives a request with a body that exceeds this limit, the application will throw a “Error: Request entity too large”. This is a feature that aims to protect your application from potential attacks where the client overloads your application with large requests.
Many resources online will tell you to increase this size to something as large as 25mb or 50mb. Also, you may find websites that tell you to change this limit to request body types that you do not need. My advice is to only change the limit to a size that is reasonable to your case, and only to request body types that you use.
Options
When you create an Express app, you might instantiate the express object with this code:
var app = express();
And, to add the body-parser middleware, you would add this line:
app.use(express.json());
Even if you use the body-parser
package, your code may look like this:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Either way, you are adding the body-parser middleware with the default request body size (100kb);
The Solution
If you know that all your requests will have a json encoded body, then the only change that you need to make is the following:
app.use(express.json({ limit: '200kb' }));
Or;
app.use(bodyParser.json({ limit: '200kb' }));
Notice how I chose a limit of only 200kb, instead of something that’s too large. The size of this limit depends on the type of application and the requests that you expect to handle.
If your requests use url-encoded body, then you will need to use this code:
app.use(express.urlencoded({ limit: '200kb' }));
Or;
app.use(bodyParser.urlencoded({ limit: '200kb' }));
Summary
Express applications that receive a request with a body larger than the set limit (default 100kb), will throw a “Error: Request entity too large”. To change this limit, use something that is reasonable, and not too large. And, finally, change the limit only to the type of requests that you expect.
If you have any questions, please feel free to comment here, or send me a message using the contact page.