Understanding responseEncoding in Axios

The responseEncoding configuration in Axios defines the character encoding used to decode incoming response streams into strings in Node.js environments. This article explains how the responseEncoding option works, its supported values, how it differs from responseType, and practical scenarios where changing this setting is necessary for proper data processing.

What is responseEncoding?

When Axios executes an HTTP request in a Node.js runtime, the server's response arrives as a raw binary stream. By default, Axios converts this binary data into a string using the utf8 character encoding.

The responseEncoding option allows developers to override this default behavior by explicitly defining which encoding should be used by Node.js when decoding the underlying Buffer.

const axios = require('axios');

axios.get('https://example.com/api/data', {
  responseEncoding: 'utf8' // Default value
})
.then(response => {
  console.log(response.data);
});

Supported Encodings

Because responseEncoding relies on Node.js buffer decoding, it supports standard Node.js string encodings, including:

Practical Use Cases

1. Direct Conversion to Base64

When downloading small images, PDF files, or binary assets that need to be embedded into HTML or JSON payloads, you can set responseEncoding to base64. This bypasses manual buffer conversion.

const axios = require('axios');

async function fetchImageAsBase64() {
  const response = await axios.get('https://example.com/logo.png', {
    responseEncoding: 'base64'
  });

  const base64Image = `data:image/png;base64,${response.data}`;
  console.log(base64Image);
}

2. Handling Legacy Charsets

Some legacy web services deliver responses encoded in latin1 rather than standard UTF-8. Setting responseEncoding: 'latin1' prevents character corruption (mojibake) during the decoding phase.

responseEncoding vs. responseType

It is important to distinguish between responseType and responseEncoding:

If responseType is set to 'arraybuffer' or 'stream', Axios will bypass the string decoding process, making responseEncoding inactive.