Global HTTP request and response handling with the Axios interceptor
Published on March 26, 2019. Edited on July 12, 2019.
This is a short example of how to catch all Axios HTTP requests, responses, and errors. Catching is implemented with the Axios feature called interceptors. It's possible to catch all requests before they are sent and modify them. Also, responses and errors can be caught globally. For example, interceptors are useful when you want to modify request headers before a request is sent or you are implementing some kind of global error handling system.
Of course, for real use case, it might be too general to handle all requests and responses in the same way. That’s why we will also have a configuration option for each HTTP requests to disable global handling.
The demo is available at CodePen
In the demo, I have used VanillaToasts library to show a notification when a HTTP request is done.
Embedded content: https://codepen.io/teroauralinna/pen/vPvKWe
Installing Axios
Start by installing Axios by the instructions.
Create a new instance and add any global config options you might need to use.
const axiosInstance = axios.create({
baseURL: 'https://...'
})
Making HTTP request handler configurable
Add isHandlerEnabled
function which will check if the global handler should be used or not. Here it's also possible to implement additional custom logic. For example, enabling the handler only for the certain HTTP response codes.
const isHandlerEnabled = (config={}) => {
return config.hasOwnProperty('handlerEnabled') && !config.handlerEnabled ?
false : true
}
Now we are later able to disable handler for an individual HTTP call if we want to.
await axiosInstance.get('/v2/api-endpoint', { handlerEnabled: false })
Axios request interceptor
Add request handler
One common use case for a request handler is to modify or add new HTTP headers. For example, an authentication token could be injected into all requests.
const requestHandler = (request) => {
if (isHandlerEnabled(request)) {
// Modify request here
request.headers['X-CodePen'] = 'https://codepen.io/teroauralinna/full/vPvKWe'
}
return request
}
Enable request interceptor
axiosInstance.interceptors.request.use(
request => requestHandler(request)
)
Axios response and error interceptors
Add response handlers
const errorHandler = (error) => {
if (isHandlerEnabled(error.config)) {
// Handle errors
}
return Promise.reject({ ...error })
}
const successHandler = (response) => {
if (isHandlerEnabled(response.config)) {
// Handle responses
}
return response
}
Enable interceptors
axiosInstance.interceptors.response.use(
response => successHandler(response),
error => errorHandler(error)
)
And now every request made by Axios uses the handlers we have defined.
Latest blog posts
October 24, 2019
How to fetch your public photos from Instagram without the API
June 12, 2019
CodePen embeds with Contentful and Angular
December 2, 2018
Setting up webpack 4 for a project
November 10, 2018
How to create Material Design like form text fields with floating label and animated underline bar
May 2, 2018
How to build a complete form with Vue.js
April 4, 2018
How to transfer the Angular server-side state to the client-side
March 28, 2018
My web developer career story
March 5, 2018
All ngVikings 2018 conference presentation slides
Latest CodePens
July 9, 2019
Switch between the dark and light mode via CSS custom properties
June 12, 2019
Javascript URL handling
June 9, 2019
Material Design like form input text fields with CSS only
March 27, 2019
Global HTTP request and response handling with the Axios interceptors
March 23, 2019
Navigation wizard example with equal width steps and flexible width of last step
March 23, 2019
Javascript event delegation example
December 9, 2018
Responsive and animated D3.js bar chart with positive and negative values (TypeScript)
November 11, 2018