Set Max Response Content Length in Axios

Managing response payload sizes is essential for preventing memory leaks, reducing bandwidth usage, and protecting applications against denial-of-service vulnerabilities. This article explains how to configure maximum content length limits for HTTP responses in the Axios client using the built-in maxContentLength configuration option across individual requests, custom instances, and global defaults.

Understanding the maxContentLength Option

Axios provides the maxContentLength property to define the maximum allowed size of the HTTP response body in bytes. If a response exceeds this threshold, Axios aborts the request and throws an error before consuming excessive memory.

By default, Axios sets maxContentLength to Infinity in Node.js (previously default was 10MB in older versions), meaning it will accept responses of any size unless explicitly configured.

Configuring Limit on a Single Request

You can define the maximum response size directly in the request configuration object. The value must be specified in bytes.

const axios = require('axios');

// Set a 2MB limit (2 * 1024 * 1024 bytes)
axios.get('https://api.example.com/data', {
  maxContentLength: 2097152
})
.then(response => {
  console.log('Data received:', response.data);
})
.catch(error => {
  console.error('Request failed:', error.message);
});

Configuring Limit on an Axios Instance

If your application interacts frequently with specific APIs, creating a pre-configured Axios instance ensures that every request enforces the specified payload limit.

const axios = require('axios');

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  maxContentLength: 5 * 1024 * 1024 // 5 MB limit
});

// All requests made with this instance inherit the 5MB limit
apiClient.get('/large-dataset')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Configuring Global Defaults

To apply a response size limit across all Axios requests within your application without creating a separate instance, set the value on the global defaults object:

const axios = require('axios');

// Apply a 10MB limit globally
axios.defaults.maxContentLength = 10 * 1024 * 1024;

Handling Exceeded Content Length Errors

When a response exceeds the defined maxContentLength, Axios throws an error. You can catch this error and verify whether it was caused by the size limit:

axios.get('https://api.example.com/download', {
  maxContentLength: 1024 // 1 KB limit
})
.catch(error => {
  if (error.code === 'ERR_BAD_RESPONSE' || error.message.includes('maxContentLength size')) {
    console.error('The server response exceeded the allowed size limit.');
  } else {
    console.error('An unexpected error occurred:', error.message);
  }
});

Environment Considerations