How Axios Handles Brotli Decompression

Axios provides built-in support for handling Brotli-encoded HTTP responses automatically, ensuring developers can consume compressed payloads without manually writing decompression logic. In Node.js environments, Axios leverages native decompression streams to unpack br-encoded data, while in browser environments, it delegates decompression directly to the browser's underlying network stack. This article covers how Axios manages Brotli decompression across different runtime environments, how the default configuration works, and how to customize or disable the behavior.

Brotli Decompression in Node.js

In a Node.js runtime, Axios relies on its standard HTTP adapter (axios/lib/adapters/http.js) to send requests and parse responses.

When a request is initiated:

  1. Header Injection: By default, Axios includes br in the Accept-Encoding request header (typically gzip, compress, deflate, br), signaling to the server that the client supports Brotli compression.
  2. Header Detection: When the server responds with the header Content-Encoding: br, Axios detects the encoding format.
  3. Stream Decompression: Axios uses Node.js's built-in zlib module. If the response stream is Brotli-compressed, Axios pipes the incoming data through zlib.createBrotliDecompress().
  4. Data Transformation: The decompressed stream is then transformed based on the specified responseType (such as json, text, or stream) before resolving the response promise.

Note: Native Brotli support in Node.js requires Node.js v11.7.0 or higher, where zlib.createBrotliDecompress was introduced.

Brotli Decompression in the Browser

In browser environments, Axios uses the XMLHttpRequest adapter (or the fetch adapter in newer configurations).

Configuration and Control

Axios provides the decompress configuration option to control automatic decompression behavior in Node.js.

Default Behavior

By default, decompress is set to true:

const axios = require('axios');

axios.get('https://example.com/data', {
  decompress: true // Default behavior
})
.then(response => {
  console.log(response.data); // Automatically decompressed
});

Disabling Automatic Decompression

If you need to receive the raw, compressed binary stream (for example, to pipe it directly to disk or forward it to another service without re-compressing), set decompress to false:

const axios = require('axios');

axios.get('https://example.com/data', {
  decompress: false,
  responseType: 'arraybuffer'
})
.then(response => {
  // response.data contains the raw Brotli-compressed bytes
});

Common Considerations