How to Configure Axios to Return ArrayBuffer

This guide explains how to configure the Axios HTTP client to process and return response payloads as raw ArrayBuffer instances instead of default JSON or text formats. By setting the responseType configuration property, you can easily retrieve binary data—such as images, PDF documents, audio files, and cryptographic keys—directly in both Node.js and browser environments.

Setting responseType on a Single Request

To receive an ArrayBuffer for a single HTTP request, pass an options object containing responseType: 'arraybuffer' as the config argument.

GET Request Example

import axios from 'axios';

async function downloadBinaryData(url) {
  try {
    const response = await axios.get(url, {
      responseType: 'arraybuffer'
    });

    // response.data is an ArrayBuffer
    const arrayBuffer = response.data;
    console.log(`Received ${arrayBuffer.byteLength} bytes.`);
    
    return arrayBuffer;
  } catch (error) {
    console.error('Error fetching binary data:', error);
    throw error;
  }
}

POST Request Example

For methods like POST or PUT, the configuration object is passed as the third parameter:

const response = await axios.post('/api/generate-pdf', payload, {
  responseType: 'arraybuffer'
});

Configuring a Global Axios Instance

If you are communicating with a service that exclusively delivers binary payloads, configure responseType at the instance level using axios.create().

import axios from 'axios';

const binaryApiClient = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  responseType: 'arraybuffer'
});

// All requests made from this instance return response.data as an ArrayBuffer
const response = await binaryApiClient.get('/files/sample.zip');

Processing the Returned ArrayBuffer

Once the payload is received as an ArrayBuffer, you can process it based on your execution environment.

In the Browser (TypedArrays & Blobs)

// Convert to a Uint8Array for byte manipulation
const uint8View = new Uint8Array(response.data);

// Create a Blob to trigger a browser download or create an Object URL
const blob = new Blob([response.data], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(blob);
window.open(fileURL);

In Node.js (Buffers)

import fs from 'fs/promises';

// Convert ArrayBuffer to a Node.js Buffer
const buffer = Buffer.from(response.data);

// Save the file to disk
await fs.writeFile('output.pdf', buffer);

Handling Errors with Binary Responses

When responseType: 'arraybuffer' is set, error responses returned by the server with non-2xx status codes will also be parsed as ArrayBuffer objects instead of JSON. To read error messages sent as JSON, decode the buffer using TextDecoder:

try {
  const response = await axios.get('/api/file', { responseType: 'arraybuffer' });
} catch (error) {
  if (error.response && error.response.data instanceof ArrayBuffer) {
    const decodedError = new TextDecoder().decode(error.response.data);
    try {
      const errorJson = JSON.parse(decodedError);
      console.error('Server error message:', errorJson);
    } catch {
      console.error('Raw server error:', decodedError);
    }
  }
}