Axios is a popular http framework in Node.JS world. It provides abstrations atop of the underlying network mechniasm and let the developers focus on the business logic. I wrote a number of CICD tools for automating Apigee resources using its Management APIs in which axios plays an important role to invoke these APIs and I’ve gained some experience on using it.

Note, axios documentation is pretty good and has most of coverage on dayly use basis. It’s worth to have a quick go through if you are ever stuck on questions like: does axios support this?

Default and custom instance

Per the official documentation, when you import the axios, you get the default instance that is an axios instance with default settings. But in most of cases, you’ll need to customize it. For example, suppose you have a bunch of endpoints like this:

  • abc.com/api/v1/docs/xxx
  • abc.com/api/v1/users/xxx

You don’t want to send the entire url to the axios method each time because later on, if you want to change it, you will have a headache on changing it in a lot of places. A better approach is alwasy creating a custom instance with baseUrl defined like this:

const instance = axios.create({
  baseURL: 'https://api.example.com'
});

Plus, if your APIs requires authorization and it accepts bearer token, you can also add this token into your custom instance.

instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;

This is especially useful for you keep this common functionality in one place and later on, you can use singleton and factory pattern to pass to the consumers to use in your application. One of the benefit is that, if you application is a long running application (e.g more than 1 hour), you can easily re-create the token when it’s expiring without changing other places too much.

Interceptors for logging

Without logging, you are blind. You have no idea on what’s happening inside your application. It’s quite common to log sending out request and receiving response so that we can investigate later if there is a dramatic latency. Where would you like to do it in axios? You will need to use interceptors to do that.

Axios has provided an interface for intercepting request and response. Below is a code example:

// Add a request interceptor
instance.interceptors.request.use(function (config) {
    console.log("Sending out request");
    return config;
  }, function (error) {
    return Promise.reject(error);
  });

// Add a response interceptor
instance.interceptors.response.use(function (response) {
    console.log("Received response");
    return response;
  }, function (error) {
    console.log("Or get an error");
    return Promise.reject(error);
  });