How to Validate Axios Response MIME Types

Validating the MIME type of an incoming HTTP response ensures your application processes only the expected data formats, preventing unexpected runtime errors and potential security issues. This guide demonstrates how to inspect the Content-Type header in Axios, handle parameter variations like character sets, and implement reusable validation using both direct checks and Axios interceptors.

Accessing the Response MIME Type

When Axios receives a response, it stores all HTTP headers in the response.headers object. The MIME type is defined by the content-type header.

Because HTTP headers are case-insensitive, Axios normalizes response header names to lowercase. You can access the MIME type using response.headers['content-type'].

const axios = require('axios');

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    const contentType = response.headers['content-type'];
    
    console.log(`Received MIME type: ${contentType}`);
  } catch (error) {
    console.error('Request failed:', error);
  }
}

Validating the MIME Type

The Content-Type header often includes additional parameters, such as character encoding (e.g., application/json; charset=utf-8). To validate accurately, extract the base MIME type before comparison:

function getBaseMimeType(contentTypeHeader) {
  if (!contentTypeHeader) return '';
  return contentTypeHeader.split(';')[0].trim().toLowerCase();
}

async function fetchJsonData(url) {
  const response = await axios.get(url);
  const mimeType = getBaseMimeType(response.headers['content-type']);
  const expectedType = 'application/json';

  if (mimeType !== expectedType) {
    throw new Error(
      `Invalid MIME type: Expected "${expectedType}" but received "${mimeType}"`
    );
  }

  return response.data;
}

Global Validation Using Axios Interceptors

To enforce MIME type validation across all outgoing requests automatically, configure a response interceptor on your Axios instance.

const axios = require('axios');

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
});

// Define allowed MIME types for the client
const allowedMimeTypes = ['application/json', 'application/problem+json'];

apiClient.interceptors.response.use(
  (response) => {
    const contentType = response.headers['content-type'];
    const baseMimeType = contentType ? contentType.split(';')[0].trim().toLowerCase() : '';

    if (!allowedMimeTypes.includes(baseMimeType)) {
      const error = new Error(`Unexpected MIME type: ${baseMimeType}`);
      error.response = response;
      return Promise.reject(error);
    }

    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

Validating Binary Data (Blobs and Buffers)

When downloading files or binary assets, specify the responseType and verify that the server returned the correct binary MIME type before saving or processing the file:

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

  const mimeType = response.headers['content-type']?.split(';')[0].trim().toLowerCase();

  if (mimeType !== 'application/pdf') {
    throw new Error(`Expected application/pdf, but received ${mimeType}`);
  }

  return response.data;
}