How to use Tokens and Cookies for Axios Authentication?

Fri Apr 14 2023

4 min read

Authentication is crucial to ensure that only authorized users can access sensitive information and functionality within web applications.

To achieve this, two popular methods are token-based and cookie-based authentication.

In this guide, we'll explore how to use these methods for secure authentication with Axios, a widely-used JavaScript library for making HTTP requests.

Token-based Authentication

Token-based authentication is a method of authenticating users by using a token or a unique identifier. The token is then sent with each request to the server to ensure the user can access the requested resource.

How to generate tokens for authentication

You can use a server-side library or a third-party authentication service to generate a token. For example, using the jsonwebtoken library in Node.js:

js
const jwt = require('jsonwebtoken');
const user = { id: 1234, name: 'John Doe' };
const secret = 'my_secret_key';
const token = jwt.sign(user, secret, { expiresIn: '1h' });
console.log(token);

Sending token with Axios requests

You can use the Authorization header to send a token with Axios requests. The token should be prefixed with the token type, such as "Bearer" or "Token." For example:

js
const axios = require('axios');
const token = 'my_token';
const config = {
headers: { Authorization: `Bearer ${token}` }
};
axios.get('/api/users', config)
.then(res => console.log(res.data))
.catch(err => console.error(err));

Example

In this example, we will use Rapid API client to test our request with the JSONPlaceholder API.

Loading component...

Create a new request inside Rapid API Client, add the API endpoint, change the HTTP method to GET, add “token” in the Auth Bearer section, and click the Send button.

Note that the JSONPlaceholder API does not require token-based authentication, so that you can use any string as your Bearer token.

Now let’s see how the complete code with look like when sending authentication token using Axios:

js
const axios = require('axios');
const BASE_URL = 'https://jsonplaceholder.typicode.com';
const TOKEN = '<your-bearer-token>'; // Replace with your Bearer token
// Set headers
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${TOKEN}`
};
// Make GET request
axios.get(`${BASE_URL}/todos/1`, { headers })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

We first set the BASE_URL and TOKEN constants to store the API base URL and Bearer token, respectively. Then we set the headers object with the required headers, including the Authorization header with the Bearer token.

Finally, we make a GET request to the API using Axios with the headers object included as the second argument to the axios.get() function. The response data is then logged to the console.

Cookie-based authentication is a method for validating users or applications. It involves storing a unique session ID in a cookie on the user's device, which is sent with each request to the server. This allows the server to verify the session ID and determine if the user has access to the requested data or resources.

To send cookies with Axios requests, we can use the withCredentials option. This tells Axios to include any cookies associated with the domain in the request. Here's an example:

js
axios.get('https://example.com/api/data', {
withCredentials: true
})

Here is an example code snippet to test Cookie-based Authentication with Axios:

js
axios.post('https://example.com/login', {
username: 'your_username',
password: 'your_password'
}, {
withCredentials: true
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});

In this example, we use the axios.post() method to send a login request to the server, passing in the username and password as parameters. We are also including the withCredentials option set to true, which tells Axios to send any cookies associated with the domain of the request.

The server will generate a session ID and store it in a cookie on the user's device. On subsequent requests, Axios will automatically include the cookie in the request headers, allowing the server to verify the user's session and grant access to the requested data or resources.

Wrap up

Axios is a powerful HTTP client library that makes sending requests and handling responses easy with modern web APIs. With its built-in support for token-based and cookie-based authentication, Axios provides a secure and flexible solution for authenticating users and applications.

Loading component...