Limit payload size using a reverse-proxy or a middleware

One Paragraph Explainer

Parsing request bodies, for example JSON-encoded payloads, is a performance-heavy operation, especially with larger requests. When handling incoming requests in your web application, you should limit the size of their respective payloads. Incoming requests with unlimited body/payload sizes can lead to your application performing badly or crashing due to a denial-of-service outage or other unwanted side-effects. Many popular middleware-solutions for parsing request bodies, such as the already-included body-parser package for express, expose options to limit the sizes of request payloads, making it easy for developers to implement this functionality. You can also integrate a request body size limit in your reverse-proxy/web server software if supported. Below are examples for limiting request sizes using express and/or nginx.

Example code for express

  1. const express = require('express');
  2. const app = express();
  3. app.use(express.json({ limit: '300kb' })); // body-parser defaults to a body size limit of 100kb
  4. // Request with json body
  5. app.post('/json', (req, res) => {
  6. // Check if request payload content-type matches json, because body-parser does not check for content types
  7. if (!req.is('json')) {
  8. return res.sendStatus(415); // -> Unsupported media type if request doesn't have JSON body
  9. }
  10. res.send('Hooray, it worked!');
  11. });
  12. app.listen(3000, () => console.log('Example app listening on port 3000!'));

Express docs for express.json()

Example configuration for nginx

  1. http {
  2. ...
  3. # Limit the body size for ALL incoming requests to 1 MB
  4. client_max_body_size 1m;
  5. }
  6. server {
  7. ...
  8. # Limit the body size for incoming requests to this specific server block to 1 MB
  9. client_max_body_size 1m;
  10. }
  11. location /upload {
  12. ...
  13. # Limit the body size for incoming requests to this route to 1 MB
  14. client_max_body_size 1m;
  15. }

Nginx docs for client_max_body_size