Introduction
Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). It is widely used by web applications to do HTTP requests. The reason why it is so popular is because of its feature-rich library. One of its feature is Interceptors. In this blog, I will demonstrate simple usage of it with JWT authentication.
What is Axios Interceptors
Axios interceptors are the default configuration that are added automatically to every request or response that a user receives. In other words, you can define what you want to do before doing any requests or after response. Some use case of interceptors are to get JWT token and attach it to the request header, or checking status code of a response and do whatever suits your application.
Using Axios Interceptors
Before actually using the interceptors, we should create a custom axios instance
by calling create
as shown below.
Here I use baseURL
options, you can use
other options as well.
After creating the instance, use interceptors like this.
We pass the function that will be executed before any request. Here I am getting the JWT token and passing it in the request header. The function passed have config object in the parameter, we need to modify this.
Another example is when you want to get JWT access token when the token expired by using refresh token, we can use HTTP status code returned.
Remove an interceptors
If you need to remove an interceptor later you can do it like this.
Summary
So now you have learned how to use interceptors effectively. I suggest you to try experimenting with it, because experience is the best teacher, ah me so wise ._. The documentation is also very nice, you can check it out!