0
0
Expressframework~5 mins

Request size limits in Express

Choose your learning style9 modes available
Introduction

Request size limits help protect your server from very large requests that can slow it down or cause crashes.

When you want to stop users from sending huge files or data in one request.
When you want to keep your server fast and safe from overload.
When you expect only small amounts of data from clients and want to enforce that.
When you want to avoid accidental or malicious attacks that send too much data.
Syntax
Express
app.use(express.json({ limit: 'size' }))
app.use(express.urlencoded({ limit: 'size', extended: true }))

The limit option sets the maximum size of the request body.

You can use sizes like '100kb', '1mb', or just numbers for bytes.

Examples
Limits JSON request bodies to 100 kilobytes.
Express
app.use(express.json({ limit: '100kb' }))
Limits URL-encoded form data to 1 megabyte.
Express
app.use(express.urlencoded({ limit: '1mb', extended: true }))
Limits JSON request bodies to 50,000 bytes (about 50 KB).
Express
app.use(express.json({ limit: 50000 }))
Sample Program

This Express app limits incoming JSON data to 10 kilobytes. If a client sends more data, Express will reject it with an error.

When you send a POST request to /data with JSON data under 10kb, it responds with the keys received.

Express
import express from 'express';

const app = express();

// Limit JSON body size to 10kb
app.use(express.json({ limit: '10kb' }));

app.post('/data', (req, res) => {
  res.send(`Received data with keys: ${Object.keys(req.body).join(', ')}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

If a request exceeds the limit, Express sends a 413 Payload Too Large error.

You can set different limits for JSON and URL-encoded data separately.

Always set limits to protect your server from overload and attacks.

Summary

Request size limits stop very large requests from slowing or crashing your server.

Use the limit option in express.json() and express.urlencoded() middleware.

Set limits based on what your app expects to receive to keep it safe and fast.