bodyLimit function

Middleware bodyLimit({
  1. int maxBytes = 1024 * 1024,
})

Request body size limit middleware

Rejects requests with Content-Length exceeding maxBytes. Default limit is 1 MB.

Implementation

Middleware bodyLimit({int maxBytes = 1024 * 1024}) {
  return (Handler innerHandler) {
    return (Request request) async {
      final contentLength = request.contentLength;
      if (contentLength != null && contentLength > maxBytes) {
        return Response(
          413,
          body: jsonEncode({'error': 'Request body too large'}),
          headers: {'Content-Type': 'application/json'},
        );
      }
      return innerHandler(request);
    };
  };
}