Attach Authorization header for all axios requests

When making HTTP requests with JavaScript, the axios library is a popular choice among developers. It provides a simple and elegant API for sending requests and handling responses. One common requirement is to attach an Authorization header to all requests for authentication purposes. In this article, we will explore two solutions to achieve this.

Solution 1: Using Axios Interceptors

Axios allows us to intercept requests and responses by using interceptors. We can take advantage of this feature to attach the Authorization header to every request. Here’s how:

import axios from 'axios';

// Set the base URL for all requests
axios.defaults.baseURL = 'https://api.example.com';

// Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Get the token from wherever you store it (e.g., localStorage)
  const token = localStorage.getItem('token');
  
  // Attach the Authorization header to the request
  config.headers.Authorization = `Bearer ${token}`;
  
  return config;
}, function (error) {
  return Promise.reject(error);
});

// Make a request
axios.get('/users')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

In this solution, we set the base URL for all requests using axios.defaults.baseURL. Then, we add a request interceptor using axios.interceptors.request.use. Inside the interceptor, we retrieve the token from wherever it is stored (e.g., localStorage) and attach it to the Authorization header of the request. This way, every request made with Axios will automatically include the Authorization header.

Solution 2: Creating a Wrapper Function

If you prefer a more modular approach, you can create a wrapper function around Axios that handles the Authorization header. Here’s an example:

import axios from 'axios';

// Create a custom Axios instance
const axiosWithAuth = axios.create({
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json',
    // Get the token from wherever you store it (e.g., localStorage)
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  }
});

// Make a request
axiosWithAuth.get('/users')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

In this solution, we create a custom Axios instance using axios.create. Inside the instance configuration, we set the base URL and headers, including the Authorization header with the token. Now, whenever we use axiosWithAuth to make requests, the Authorization header will be automatically attached.

Both solutions achieve the same result of attaching the Authorization header to all Axios requests. Choose the one that best fits your project’s requirements and coding style.

That’s it! You now know how to attach an Authorization header for all Axios requests. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *