How to use Basic Auth with Axios in JavaScript

avatar
Borislav Hadzhiev

Last updated: Apr 4, 2024
4 min

banner

# How to use Basic Auth with Axios in JavaScript

Set the auth property in the request configuration object to use HTTP Basic auth with axios.

The auth property should be an object that contains the username and password properties.

Here is an example POST request that uses basic auth with axios.

index.js
import axios from 'axios'; async function logUserIn() { try { const requestBody = { id: 1, name: 'bobby hadz', salary: 100, }; const response = await axios.post( 'https://jsonplaceholder.typicode.com/users', requestBody, { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', }, headers: { 'Content-Type': 'application/json', }, }, ); return response.data; } catch (err) { console.log(err.message); console.log(err.response.status); } } logUserIn().then(data => { console.log(data); });
The code for this article is available on GitHub

The key part of the code sample is specifying the auth object.

index.js
const response = await axios.post( 'https://jsonplaceholder.typicode.com/users', requestBody, { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', }, headers: { 'Content-Type': 'application/json', }, }, );

The auth object is used to specify that HTTP Basic auth should be used.

The object should have the username and password properties that point to the user's credentials.

When the auth property is set, axios sets anAuthorization header and overwrites any custom Authorization headers you've previously set using the headers property.

The auth property should only be used to configure HTTP Basic auth.

If you need to set a Bearer JWT token, use the Authorization custom header instead.

index.js
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_JWT_TOKEN', },

If you need to issue a POST request when authenticating with Basic Auth but don't need to send any data, pass an empty object as the second parameter to the axios.post() method.

index.js
import axios from 'axios'; async function logUserIn() { try { const response = await axios.post( 'https://jsonplaceholder.typicode.com/users', // ๐Ÿ‘‡๏ธ pass empty object here {}, { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', }, }, ); return response.data; } catch (err) { console.log(err.message); console.log(err.response.status); } } logUserIn().then(data => { console.log(data); });
The code for this article is available on GitHub

Notice that we passed an empty object as the second parameter to the axios.post() method.

index.js
const response = await axios.post( 'https://jsonplaceholder.typicode.com/users', // ๐Ÿ‘‡๏ธ pass empty object here {}, { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', }, }, );
A common issue that causes basic auth not to work is when you set the auth property in the request body (the second parameter), instead of the request configuration object (the third parameter).

If you send the auth property with the request object, axios won't set the Authorization header correctly and Basic Auth won't work.

The examples above demonstrate how to set the auth property in an HTTP POST request.

The syntax for a POST request with axios is axios.post(URL, REQUEST_BODY, REQUEST_CONFIG_OBJECT).

The auth property should be set in the request config object.

If you need to make an HTTP GET request, make sure to remove the request body.

index.js
import axios from 'axios'; async function logUserIn() { try { const response = await axios.get( 'https://jsonplaceholder.typicode.com/users', { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', }, }, ); return response.data; } catch (err) { console.log(err.message); console.log(err.response.status); } } logUserIn().then(data => { console.log(data); });

The syntax for a GET request with axios is axios.get(URL, REQUEST_CONFIG_OBJECT).

Make sure to update the URL and the credentials in the auth object when issuing the request.

# Example of using Basic Auth with axios with the httpbin API

Let's look at an example of using basic auth with axios with the httpbin API.

The API exposes the following endpoint that enables you to test Basic Auth.

shell
https://httpbin.org/basic-auth/{username}/{password}

If you visit the URL in your browser, it will prompt you for a username and a password.

The expected values for the username and password fields are the same values you entered in the path components of the URL.

Here's an example.

shell
https://httpbin.org/basic-auth/my-user/my-password

In the URL above, the username is my-user and the password is my-password.

Here is an example that uses axios to authenticate by setting the auth property.

index.js
import axios from 'axios'; async function logUserIn() { try { const response = await axios.get( 'https://httpbin.org/basic-auth/my-user/my-password', { auth: { username: 'my-user', password: 'my-password', }, }, ); return response.data; } catch (err) { console.log(err.message); console.log(err.response.status); } } logUserIn().then(data => { console.log(data); });

using basic auth with axios

The code for this article is available on GitHub

Note that the path components must correspond to the values of the username and password properties.

index.js
const response = await axios.get( 'https://httpbin.org/basic-auth/my-user/my-password', { auth: { username: 'my-user', password: 'my-password', }, }, );

The server responds with the following object.

index.js
{ authenticated: true, user: 'my-user' }

If the specified username or password is incorrect, the server responds with a status code of 401 Unauthorized.

index.js
import axios from 'axios'; async function logUserIn() { try { const response = await axios.get( 'https://httpbin.org/basic-auth/my-user/my-password', { auth: { username: 'your-user', password: 'your-password', }, }, ); return response.data; } catch (err) { console.log(err.message); console.log(err.response.status); } } logUserIn().then(data => { console.log(data); });

http basic auth with axios incorrect credentials

The code for this article is available on GitHub

Notice that the username and password values in the URL don't match the supplied values in the auth object.

index.js
const response = await axios.get( 'https://httpbin.org/basic-auth/my-user/my-password', { auth: { username: 'your-user', password: 'your-password', }, }, );

Therefore the authentication request fails and the server responds with 401 unauthorized.

If you run into issues when using basic auth with axios, make sure you are setting the auth property in the request configuration object and not in the request body when issuing POST requests.

The following syntax is correct when issuing GET requests with axios.

index.js
// โœ… correct syntax for GET requests axios.get(YOUR_URL, { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', } })

And the following syntax is correct when issuing POST requests.

index.js
// โœ… correct syntax for POST requests axios.post(YOUR_URL, // ๐Ÿ‘‡๏ธ this is the request body object {}, // ๐Ÿ‘‡๏ธ this is the request configuration object { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', } })
The code for this article is available on GitHub

Notice that we set the auth property in the request configuration object and not in the request body object.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev