WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    Function requestSizeLimiter

    • Request Size Limiting Middleware

      Validates incoming request size against configurable limits to prevent resource exhaustion attacks and ensure system stability. This middleware checks the Content-Length header before request processing to reject oversized requests early in the pipeline, preventing memory exhaustion and processing overhead.

      When requests exceed the size limit, the middleware responds with a standardized error format and logs the violation for security monitoring. The size limit is configurable via environment variables to accommodate different deployment needs.

      Applied before body parsing middleware to prevent large payloads from being processed and consuming server resources. Works in conjunction with Express body parser limits for comprehensive request size control.

      Parameters

      • req: Request

        Express request object to validate size

      • res: Response

        Express response object for error responses

      • next: NextFunction

        Express next function to continue middleware chain

      Returns void

      // Usage in main application middleware stack
      import { requestSizeLimiter } from '@/shared/middleware/security';

      app.use(requestSizeLimiter); // Apply before body parsing
      app.use(express.json({ limit: '10mb' }));
      app.use(express.urlencoded({ extended: true, limit: '10mb' }));
      // Environment variable configuration
      // .env file
      MAX_REQUEST_SIZE=10485760 # 10MB in bytes
      // Error response for oversized requests:
      // HTTP 422 Unprocessable Entity
      {
      "error": {
      "code": "VALIDATION_ERROR",
      "message": "Request size too large",
      "timestamp": "2024-01-20T10:30:00.000Z",
      "path": "/api/v1/upload"
      }
      }
      // Security benefits:
      // - Prevents DoS attacks via large payloads
      // - Protects against memory exhaustion
      // - Reduces processing overhead for invalid requests
      // - Provides early rejection of malicious requests
      // - Logs security violations for monitoring