How to use axios interceptors
In this guide, we will show how to use interceptors with axios. We will show how we can intercept all our requests and apply common request configs, and also how to intercept the responses and apply common response data.
What are intercetors?
So an interceptor in axios does exactly what it says in the name, it intercepts the outgoing request or incoming response before it gets handled by then or catch. The idea with the interceptors is that we can apply common configs, error handling or common data in the response that we know our application expects from the response data. If you are familiar with for example express in Node.js, it is equivalent to middlewares.
Request interception
In this example, we will imagine that our API requires us to send an API key in all of our requests. And if we have many places where we are calling the API, an interceptor that adds the correct headers could be very handy.
In your index file for example, add following code:
import axios from "axios"; axios.interceptors.request.use((config) => { config.headers["X-Api-Key"] = "my-api-key"; return config; });
Now we should get a header called X-Api-Key with value my-api-key set on all our requests directly.
So if we are calling an API, for example our stock API, we should get the header added.
If we fire below request in a component for example
const response = await axios.get( "https://api.algobook.info/api/v1/stocks?tickers=AAPL" ); console.log(response.data);
And then inspect the call in the inspector, we should see something similar as below image.
Response interceptor
If we now imagine we are working on a bank application and are presenting our vistors with some stock prices, and we need the data to be mapped in a certain way that our API are not giving us, we can do so with our response interceptor.
So if we consider the data that our stock API is returning us:
[ { "ticker": "AAPL", "open": 181.5, "lastClose": 180.57, "lastPrice": 180.96, "percentage": 0.22, "currency": "USD", "companyName": "Apple Inc." } ]
We now want the companyName to change to name, lastClose to close and lastPrice to price for example.
Similar to the request interceptor, we can initialize it like following code and re-map the response data:
axios.interceptors.response.use((response) => { response.data = response.data.map((data: any) => ({ ticker: data.ticker, open: data.open, close: data.lastClose, price: data.lastPrice, percentage: data.percentage, currency: data.currency, name: data.companyName, })); return response; });
And if we call the API:
const response = await axios.get( "https://api.algobook.info/api/v1/stocks?tickers=AAPL" ); console.log(response.data);
the response will look like this:
[ { "close": 180.57, "currency": "USD", "name": "Apple Inc.", "open": 181.5, "percentage": 0.22, "price": 180.96, "ticker": "AAPL" } ]
And now we have formatted the response like we wanted it to be. Note that this will be done for all the responses, so it will perhaps not make sense if we would have more API integrations towards other services, but this was just to give an example on how we could change the response data before we access it in our component.
Summary
In this article we showed how to use interceptors in axios. Interceptors are great when we want the same functionality in many places, for example same headers or API keys etc, and don't need to worry if we set them or not. Same with response data, if we always need a certain entity added or structured in a certain way, the response interceptor works really well.
Just make sure that it can be easy to introduce errors if we manipulate the responses to much, especially if we have many API integrations.
Thanks for reading, and have a great day!