Last updated: Apr 4, 2024
Reading timeยท4 min
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
.
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 key part of the code sample is specifying the auth
object.
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.
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.
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.
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); });
Notice that we passed an empty object as the second parameter to the
axios.post()
method.
const response = await axios.post( 'https://jsonplaceholder.typicode.com/users', // ๐๏ธ pass empty object here {}, { auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', }, }, );
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.
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.
axios
with the httpbin
APILet'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.
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.
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.
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); });
Note that the path components must correspond to the values of the username
and password
properties.
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.
{ authenticated: true, user: 'my-user' }
If the specified username or password is incorrect, the server responds with a status code of 401 Unauthorized.
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); });
Notice that the username and password values in the URL don't match the supplied
values in the auth
object.
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
.
// โ 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.
// โ 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', } })
Notice that we set the auth
property in the request configuration object and
not in the request body object.
You can learn more about the related topics by checking out the following tutorials: