Understanding Axios maxBodyLength in Node.js

The maxBodyLength setting in Axios defines the maximum allowed size, in bytes, for an HTTP request body sent from a Node.js environment. This article explains the purpose of the maxBodyLength configuration, how it protects application resources, how it differs from similar settings like maxContentLength, and how to adjust or remove this limit when transmitting large payloads such as file uploads.

Purpose of maxBodyLength

When running in Node.js, Axios uses Node's native http and https modules to dispatch requests. The maxBodyLength option acts as a safeguard that restricts the size of the outgoing request payload.

By default, Axios sets maxBodyLength to 10MB (10 * 1024 * 1024 bytes). If an application attempts to send a request with a body exceeding this threshold, Axios intercepts the operation before the data is fully transmitted and throws an error:

AxiosError: Request body larger than maxBodyLength limit

Why the Limit Exists

The primary purpose of maxBodyLength is resource management and security:

maxBodyLength vs. maxContentLength

Axios provides two distinct configurations for controlling payload sizes in Node.js:

How to Configure maxBodyLength

You can modify maxBodyLength at the request level, globally, or when creating an Axios instance.

1. Increase the Limit for a Specific Request

To allow larger payloads for a single request, such as a 50MB file upload:

const axios = require('axios');
const fs = require('fs');

const fileStream = fs.createReadStream('large-video.mp4');

axios.post('https://example.com/upload', fileStream, {
  headers: {
    'Content-Type': 'video/mp4',
  },
  maxBodyLength: 50 * 1024 * 1024, // 50MB
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

2. Remove the Limit Entirely

If your application regularly streams files of unpredictable sizes, you can set the value to Infinity to bypass the check:

axios.post('https://example.com/upload', largeDataStream, {
  maxBodyLength: Infinity,
  maxContentLength: Infinity,
});

3. Set a Global or Instance-Level Limit

If all requests across an Axios instance require higher limits, specify it in axios.create():

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  maxBodyLength: Infinity,
  maxContentLength: Infinity,
});