How to Set Basic Auth in Axios Configuration

This guide explains how to set HTTP Basic Authentication credentials directly within the Axios HTTP client configuration. Axios provides a built-in auth option that automatically encodes your username and password into a standard Base64 Authorization header, eliminating the need to construct the header manually.

Using the auth Configuration Option in a Request

To supply Basic Auth credentials for a single request, pass an auth object containing username and password properties inside the request configuration.

const axios = require('axios');

axios.get('https://api.example.com/data', {
  auth: {
    username: 'your_username',
    password: 'your_password'
  }
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Request failed:', error);
});

Axios automatically converts these credentials into the header: Authorization: Basic <base64-encoded-credentials>


Setting Basic Auth on an Axios Instance

If multiple requests share the same credentials, create a reusable Axios instance using axios.create() and define the auth object in the instance configuration.

const axios = require('axios');

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

// All requests using apiClient will include the Basic Auth header
apiClient.get('/users')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Setting Global Defaults

To apply Basic Authentication across all Axios requests throughout your application, set the default auth property on the global axios object.

const axios = require('axios');

axios.defaults.auth = {
  username: 'your_username',
  password: 'your_password'
};

// Any standard axios call will now inherit these credentials
axios.get('https://api.example.com/profile');

Manual Header Configuration (Alternative)

If you prefer to generate the header manually without the auth property, use the standard headers configuration with a Base64-encoded string.

In Node.js:

const token = Buffer.from('your_username:your_password').toString('base64');

axios.get('https://api.example.com/data', {
  headers: {
    'Authorization': `Basic ${token}`
  }
});

In browser environments:

const token = btoa('your_username:your_password');

axios.get('https://api.example.com/data', {
  headers: {
    'Authorization': `Basic ${token}`
  }
});