Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Body Size Limiting

Limit request body size to prevent memory issues and protect against denial-of-service attacks.

Basic Body Size Limiting

MoroJS provides built-in body size limiting middleware to prevent memory exhaustion and protect against large payload attacks.

Global Body Size Limit

typescript

1import { bodySize } from '@morojs/moro';
2
3// Global body size limit
4app.use(bodySize({
5  limit: '10mb',
6  message: 'Request body too large'
7}));
8
9// All routes now have a 10MB limit
10app.post('/api/data', (req, res) => {
11  // Request body is automatically validated
12  return { success: true, data: req.body };
13});

Body Size Features

  • • Global and per-route body size limits
  • • Support for different content types
  • • Human-readable size formats (mb, kb, etc.)
  • • Custom error messages
  • • Automatic request rejection for oversized payloads

Per-Route Limits

Route-Specific Body Size Limits

typescript

1import { bodySize } from '@morojs/moro';
2
3// Per-route limits
4app.post('/api/upload')
5  .bodySize({ limit: '50mb' })
6  .handler((req, res) => {
7    // Handle large upload
8    return { success: true };
9  });
10
11// JSON-specific limit
12app.use(bodySize({
13  limit: '1mb',
14  jsonLimit: '100kb' // Stricter limit for JSON
15}));
16
17// Different limits for different content types
18app.use(bodySize({
19  limit: '10mb',
20  jsonLimit: '1mb',
21  textLimit: '5mb',
22  urlencodedLimit: '2mb'
23}));

Best Practices

Do

  • • Set appropriate limits for each route
  • • Use stricter limits for JSON endpoints
  • • Set higher limits for file upload endpoints
  • • Provide clear error messages
  • • Monitor body size violations
  • • Use different limits per content type

Don't

  • • Set unlimited body sizes
  • • Use the same limit for all routes
  • • Ignore body size limits
  • • Set limits too high for security
  • • Skip body size validation
  • • Allow very large JSON payloads

Related Features