Axios Self-Signed SSL Certificate Configuration

When making HTTPS requests to servers using self-signed SSL certificates, Node.js throws security errors like DEPTH_ZERO_SELF_SIGNED_CERT or UNABLE_TO_VERIFY_LEAF_SIGNATURE. This guide demonstrates how to configure the Axios HTTP client to handle self-signed certificates by using Node.js's built-in https agent, covering both the method to bypass certificate validation for local development and the secure method to trust specific certificates using a Certificate Authority (CA) bundle.


Method 1: Bypass Certificate Validation (Development Only)

For local development or testing environments, you can tell the HTTPS agent to ignore certificate validation errors by setting rejectUnauthorized to false.

Per-Request Configuration

Pass a custom httpsAgent directly inside the request configuration:

const axios = require('axios');
const https = require('https');

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

axios.get('https://localhost:8443/api/data', { httpsAgent })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Axios Instance Configuration

If you make multiple requests to the same service, create a reusable Axios instance:

const axios = require('axios');
const https = require('https');

const apiClient = axios.create({
  baseURL: 'https://localhost:8443',
  httpsAgent: new https.Agent({
    rejectUnauthorized: false,
  }),
});

apiClient.get('/api/users')
  .then(response => console.log(response.data));

Disabling certificate verification makes applications vulnerable to Man-in-the-Middle (MitM) attacks. A safer approach is providing the self-signed certificate (or the private root CA certificate) directly to the HTTPS agent using the ca option.

const axios = require('axios');
const https = require('https');
const fs = require('fs');
const path = require('path');

// Read the certificate file (.pem or .crt)
const rootCas = fs.readFileSync(path.resolve(__dirname, 'server-cert.pem'));

const httpsAgent = new https.Agent({
  ca: rootCas,
  rejectUnauthorized: true, // Remains secure while trusting your specific cert
});

const apiClient = axios.create({
  baseURL: 'https://internal.example.local',
  httpsAgent: httpsAgent,
});

apiClient.get('/api/secure-data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Important Considerations