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:
utf8: Standard multi-byte encoded Unicode characters (default).ascii: 7-bit ASCII data.latin1/binary: One-byte encoding for ISO-8859-1 character sets.base64: Base64 string encoding.base64url: URL-safe Base64 encoding.hex: Converts each byte into two hexadecimal characters.utf16le/ucs2: 2 or 4 bytes, little-endian encoded Unicode characters.
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:
responseType: Defines the data structure Axios returns (e.g.,'json','text','stream','arraybuffer','blob'). It works in both the browser and Node.js.responseEncoding: Defines the character set used to parse the stream into text. It is specifically relevant to Node.js environments when dealing with text-based data or buffer transformations.
If responseType is set to 'arraybuffer' or
'stream', Axios will bypass the string decoding process,
making responseEncoding inactive.