Integrating API (Application interface protocol) with frontend applications which makes the software industry run today. And integrating API is by far the easiest job on this planet until you realize that the code you are writing is not for you. Lets start very simple, as such no prerequisite needed if you understand JavaScript that will be more than enough.
So let's dive deep, we will be using Axios for handling all HTTP requests. If you don’t know what Axios is ? It's almost the same with fetch which is natively provided in browsers. Being a 3rd party, Axios provides advanced request handling, parsing, request interception, etc.
This is how a normal api request looks like using Axios.
import axios from "axios";
async function getUserList() {
try {
const response = await axios.get("https://example.com/v1/users");
console.log(response);
} catch (error) {
console.log(error);
}
}
You can set custom headers according to your need
import axios from "axios";
const options = {
method: "POST",
headers: { Authorization: `Bearer ${data.token}` },
};
async function getUserList() {
try {
const response = await axios.get("https://example.com/v1/users", options);
console.log(response);
} catch (error) {
console.log(error);
}
}
If your frontend application handles 2-4 API endpoint connections then the above method is the best in case you want to save your time. What if your application is going to handle more than a couple hundred requests in that case Axios Interceptor comes into picture, it's gonna save you a lot of time and you’re gonna thank me later. It’s almost used everywhere in industry in enterprise scale applications.
Key Highlights:
- Consistent error handling throughout all the api requests.
- Attaching an auth token to every request without repeating code for every request.
- Global response formatting.
- Cancelling initiated request.
Let’s see how the basic implementation of interceptor will look like
Create one file lets say interceptor.ts
import axios from "axios";
Create an instance from axios
const api = axios.create({
baseURL: "https://example.com/", // replace with your API
timeout: 5000,
});
After an instance is initiated, we are ready to intercept the requests going through this instance. Now we want to send authorization headers with Bearer token
with every request from the frontend. Axios has internal methods built in to intercept ongoing requests before it happens and send custom headers. This is how it will look like
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem("token"); // get token from storage
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// Do something before request is sent
return Promise.reject(error);
}
);
Now we have successfully intercepted ongoing requests using Axios. Lets use it for unwrap response structure globally rather than doing it on every single request. This is how it will look like, We are getting response
from server and response.data
is the useful part so we will return response.data
api.interceptors.response.use(
(response) => {
// You can modify response globally
return response.data; // now you get res.data directly
},
(error) => {
if (error.response?.status === 401) {
console.error("Unauthorized! Redirecting to login...");
window.location.href = "/login"; // redirect user
}
return Promise.reject(error);
}
);
Now export the instance
export default api;
This is how actually usage will look like
import api from "./interceptor";
async function getUserList() {
try {
const response = await api.get("/users");
console.log(response);
} catch (error) {
console.log(error);
}
}
Now lets look into how to cancel an ongoing request using Axios interceptor. To cancel an ongoing request Axios provides AbortController
terminates ongoing request instantly, and this is how it will look like
api.interceptors.request.use((config) => {
if (config.cancel === true) {
const controller = new AbortController();
controller.abort(); // cancel immediately
config.signal = controller.signal;
}
return config;
});
Usage
import api from "./axios";
// Normal request (works fine)
api
.get("/users")
.then((res) => console.log("✅ Success:", res.data))
.catch((err) => console.error(err));
// Cancelled request
api
.get("/users", { cancel: true })
.then((res) => console.log(res))
.catch((err) => console.error("❌ Cancelled:", err.message));
Top comments (0)