0
0
Expressframework~5 mins

File size limits in Express

Choose your learning style9 modes available
Introduction

File size limits help keep your server safe and fast by stopping very large files from being uploaded.

When you want to stop users from uploading files that are too big.
When you want to save server space and avoid slow responses.
When you want to protect your app from accidental or harmful large uploads.
When you want to give clear feedback to users about upload limits.
Syntax
Express
app.use(express.json({ limit: '1mb' }))
app.use(express.urlencoded({ limit: '1mb', extended: true }))
The limit option sets the maximum size of the request body.
You can use units like 'kb', 'mb', or 'gb' as strings.
Examples
Limits JSON body size to 500 kilobytes.
Express
app.use(express.json({ limit: '500kb' }))
Limits URL-encoded form data to 2 megabytes.
Express
app.use(express.urlencoded({ limit: '2mb', extended: true }))
Allows larger JSON bodies up to 10 megabytes.
Express
app.use(express.json({ limit: '10mb' }))
Sample Program

This Express app limits JSON uploads to 1 megabyte. If a bigger file is sent, it returns a clear error message.

Express
import express from 'express';

const app = express();

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

app.post('/upload', (req, res) => {
  res.send(`Received data with size: ${JSON.stringify(req.body).length} bytes`);
});

app.use((err, req, res, next) => {
  if (err.type === 'entity.too.large') {
    res.status(413).send('File too large. Max size is 1mb.');
  } else {
    res.status(500).send('Server error');
  }
});

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

Always set file size limits to protect your server from overload.

Express throws an error if the limit is exceeded; handle it to give friendly messages.

Limits apply to the request body size, not the file system size.

Summary

File size limits keep your app safe and fast by stopping large uploads.

Use the limit option in Express body parsers to set size limits.

Handle errors to inform users when files are too big.