How to create Axios Interceptor for Vue with TypeScript
In this article, I am going to demonstrate how you can create a global HTTP request and response handler with Axios Interceptor and used the same in Vue with TypeScript. Vue and TypeScrip both are very popular nowadays and many developers are using both wisely. Axios is a generic library and that can be used in any library like React, Vue, Laraval, Node, etc.
Axios, a client HTTP API based on the XMLHttpRequest interface provided by browsers, and examine the key features that has contributed to its rise in popularity among frontend developers.
Axios is promise-based. However, it provides a more powerful and flexible feature set. Advantages over the native Fetch API include:
- Request and response interception
- Streamlined error handling
- Protection against XSRF
- Support for upload progress
- Response timeout
- The ability to cancel requests
- Support for older browsers
- Automatic JSON data transformation
Axios can be installed in any of the following ways -
Request & Response with Axios Interceptor
This is very simple and it works great, but in the real-world scenario, we need to deal with many Authentication headers, API key headers,s and many more. Then we will definitely need the interceptor and helps us to inject headers to the HTTP request globally from a single piece of code. Also, it helps to handle the error scenarios as well.
I am using TypeScript to built the Axios Interceptor.
Step 1 - I am creating an Abstract class called HTTPBaseService and in constructor passing the base URL and if any token
Step 2: Now we are intercepting the HTTP Request And response
Step 3: As you can see, now we can inject any HTTP header while the application making any request. Also, we can handle errors as well. let's see how I am handling the 401 error and renewed the token.
Now Axios Interceptor has been created, let's invoke this from the application business logic file.
You need to extend the above abstract class and define your service endpoint there.
So the base service and business-specific service have been created, we are going to call the method from your Vue, React, or any component.
This code may not be perfect, there is a lot of space to improve the code. But still, it will work perfectly with any application.
Views 6,067 & counting...