Nelson Michael Nelson Michael is a frontend developer from Nigeria. When he's not meddling with CSS, he spends his time writing, sharing what he knows, and playing games.

Using Axios to set request headers

3 min read 1090

using Axios To Set Request Headers

Nearly everything that is visible in a user’s browser is transmitted over HTTP, so these network requests play an important role in internet communication. A key component of an HTTP request is the header. HTTP request headers are used to provide additional information about the request. For example, details about the requested information, the sender, and how the sender wishes to connect with the recipient.

Axios is a flexible and robust solution for making HTTP requests and for intercepting HTTP responses from both Node.js applications and the browser. But, Axios also does much more. Aside from the standard CRUD functionality you’d expect from an HTTP client, Axios offers a slew of other useful inbuilt features, such as configuration defaults, error handling, request canceling, and automatically serializing JavaScript objects to JSON.

In this article, we’ll explore different ways that Axios can be used to set request headers for API calls.

Installing Axios

For the examples used in this article, we’ll install Axios from a CDN. It may also be installed with npm, Yarn, or Bower.

Here’s the script or command for each method:

//via cdn
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

// via npm
$ npm install axios

// via yarn
$ yarn add axios

// via bower
$ bower install axios

Let’s explore the different ways we can use Axios to set request headers for API calls:

Passing an object argument

Axios methods such as post() and get() enable us to attach headers to requests by supplying a headers’ object as the second parameter for a GET request and the third argument for a POST request.

Let’s take a look at how this works for both individual and multiple requests:

Individual requests

The POST and GET requests are used to create or retrieve a resource, respectively. Here are some examples for one-time or individual requests.

First, we declare the config object, containing the headers object, which will be supplied as an argument when making requests. We also declare an api endpoint and a data object:

const config = {
  headers:{
    header1: value1,
    header2: value2
  }
};
const url = "api endpoint";

const data ={
  name: "Jake Taper",
  email: "[email protected]"
}

We can use a GET request to retrieve the config object from the API endpoint url:

axios.get(url, config)
  .then(res=> console.log(res))
  .catch(err=> console.log(err))

In this example, we pass in the API endpoint url as the first argument and the config object as the second argument.

We can use a POST request to pass the data object to the API endpoint url:

 axios.post(url, data, config)
  .then(res => console.log(res))
  .catch(err => console.log(err))

In this example, we pass in the API endpoint url as the first argument, a data object as the second argument, and the config object as the third argument.

Multiple requests

In some cases, headers may need to be set automatically for multiple or subsequent requests. We can address this by specifying configuration defaults.

This code sets authorization headers for all requests:

axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;

This code sets authorization headers for all post requests:

 
axios.defaults.headers.post['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;

Creating a specific Axios instance

We can also set request headers for API calls by creating a specific instance of Axios.

We can use require to create a new instance of Axios:

const axios = require('axios')

However, this option does not allow us to pass in the configs. To correctly set up the headers for each request, we can create an instance of Axios using axios.create and then set a custom configuration on that instance:

let reqInstance = axios.create({
  headers: {
    Authorization : `Bearer ${localStorage.getItem("access_token")}`
    }
  }
})

We can reuse this configuration each time we make a request using this particular instance.



When we use the reqInstance to make a request, the authorization header will be attached:

reqInstance.get(url);

Using Axios interceptors

We can also use Axios interceptors to set request headers for API calls. Axios interceptors are functions that are called by Axios. Interceptors may be used to alter a request before it is transmitted or to modify a response before it is delivered. Interceptors are essentially equivalent to middleware from Express or Mongoose.

I previously worked on a project that required an authorization header, containing the user access token, to be appended to every request. It was a financial application, and the system needed to verify user identity for every request. This is an example in which it would have been preferable to automatically attach the authorization header to every request, rather than having to set them individually.

Authentication is one of the most common applications for interceptors. A client app often verifies user identity to the server by submitting a secret access token in the authorization header.

We can use Axios interceptors to automatically set the Authorization header for all requests:

// Request interceptors for API calls
axios.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

In this example, we use the axios.interceptors.request.use method to update each request header and set the access token in the Authorization HTTP header.

We target the Authorization header from the config.headers object and set a Bearer token, which is stored in localStorage, as its value.

Axios interceptors are also useful for monitoring access tokens for impending expiration. A refreshToken() function may be used to update a token before it expires:

const refreshToken= ()=>{
  // gets new access token
}

We can also call the axios.interceptors.response.use() method to get a new access token whenever a response returns a 403 error, meaning the existing token has expired:

// Response interceptor for API calls
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if(error.response.status == 403){
            refreshToken()
        }
    }
);

In this example, the axios.interceptors.response.use method intercepts all incoming responses and then checks the status of the response. If the request that triggered the response is not authenticated, then the token is expired. In that case, we call for the refreshToken() function to obtain a new access token.

Wrapping up

In this article, we examined how to set HTTP request headers with Axios by passing an object, creating a specific Axios instance, and using Axios interceptors. For information about additional features of the Axios HTTP client, see its website or GitHub.

Are you adding new JS libraries to improve performance or build new features? What if they’re doing the opposite?

There’s no doubt that frontends are getting more complex. As you add new JavaScript libraries and other dependencies to your app, you’ll need more visibility to ensure your users don’t run into unknown issues.

LogRocket is a frontend application monitoring solution that lets you replay JavaScript errors as if they happened in your own browser so you can react to bugs more effectively.

https://logrocket.com/signup/

LogRocket works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.

Build confidently — .

Nelson Michael Nelson Michael is a frontend developer from Nigeria. When he's not meddling with CSS, he spends his time writing, sharing what he knows, and playing games.

2 Replies to “Using Axios to set request headers”

  1. You have syntax errors in your examples – misplaced } with ` within template strings in both examples: axios.create and axios.interceptors.request.use

Leave a Reply