How to Use Basic Auth with Axios in JavaScript
HTTP Basic Authentication is a simple authentication scheme where a request is sent with an Authorization header containing a Base64-encoded string of username:password. While you could construct this header manually, the axios library provides a convenient, built-in auth property to handle it for you.
This guide will teach you how to correctly use the auth property in your axios request configuration for both GET and POST requests, and clarify the important difference between Basic Auth and Bearer Token authentication.
The Core Method: The auth Property
The key to using Basic Auth with axios is to include an auth object in the request configuration. This object must contain username and password properties.
{
auth: {
username: 'YOUR_USERNAME',
password: 'YOUR_PASSWORD'
}
}
When axios sees this property in the config, it automatically creates the Authorization: Basic ... header for you. It will override any custom Authorization header you may have set.
Using Basic Auth with a GET Request
For a GET request, the request configuration is the second argument passed to axios.get().
Syntax:
axios.get(url, config)
Solution:
import axios from 'axios';
async function fetchUserData() {
try {
const response = await axios.get(
'https://api.example.com/user',
{
// The config object is the second argument for a GET request
auth: {
username: 'my-user',
password: 'my-secret-password'
}
}
);
console.log('User data:', response.data);
return response.data;
} catch (error) {
console.error('Authentication failed:', error.response?.status);
}
}
fetchUserData();
Using Basic Auth with a POST Request
For a POST request, the request configuration is the third argument passed to axios.post(), after the URL and the request body.
Syntax:
axios.post(url, data, config)
Solution:
import axios from 'axios';
async function createPost() {
try {
const postData = { title: 'New Post', content: 'Hello World' };
const response = await axios.post(
'https://api.example.com/posts',
postData, // The request body is the second argument
{
// The config object is the third argument for a POST request
auth: {
username: 'my-user',
password: 'my-secret-password'
}
}
);
console.log('Created post:', response.data);
return response.data;
} catch (error) {
console.error('Post creation failed:', error.response?.status);
}
}
createPost();
Basic Auth vs. Bearer Token: A Critical Distinction
It is important not to confuse the auth property with other types of authentication, like Bearer Tokens (commonly used with JWTs).
- Use the
authproperty only for HTTP Basic Authentication. - For Bearer Tokens or other custom
Authorizationschemes, you must set the header manually.
Bearer Token Example (Do NOT use the auth property)
const jwtToken = 'your-jwt-token-here';
axios.get('https://api.example.com/secure-data', {
headers: {
'Authorization': `Bearer ${jwtToken}`
}
});
Common Pitfalls and How to Solve Them
Problem: Placing auth in the Wrong Object for POST Requests
The most common mistake when using Basic Auth with a POST request is to incorrectly place the auth object inside the request body (the second argument) instead of the configuration object (the third argument).
Example of code with errors:
// INCORRECT: auth is inside the request body
const response = await axios.post(
'https://api.example.com/posts',
{
title: 'New Post',
auth: { // This is WRONG! Axios will not see this.
username: 'my-user',
password: 'my-secret-password'
}
}
);
This will fail because axios only looks for the auth property in its dedicated configuration object.
Solution: Always ensure the auth object is in the correct argument: the second argument for GET requests and the third argument for POST requests. If your POST request has no body, you must pass an empty object ({}) as the second argument to serve as a placeholder.
// CORRECT: Passing an empty body for a POST request
await axios.post(
'https://api.example.com/login',
{}, // Empty request body
{ // Correct configuration object
auth: { username: 'my-user', password: 'my-secret-password' }
}
);
Conclusion
The auth property in axios provides a simple and secure way to handle HTTP Basic Authentication without manually constructing the Authorization header.
- To use it, provide an
authobject withusernameandpasswordproperties in the request configuration. - For
GETrequests, the config object is the second argument. - For
POSTrequests, the config object is the third argument. - Do not use the
authproperty for Bearer Token authentication; set theAuthorizationheader manually for that.