DEV Community

Cover image for API integration like Enterprise scale React based applications.
adwait12345
adwait12345

Posted on

API integration like Enterprise scale React based applications.

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

  1. Consistent error handling throughout all the api requests.
  2. Attaching an auth token to every request without repeating code for every request.
  3. Global response formatting.
  4. 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";
Enter fullscreen mode Exit fullscreen mode

Create an instance from axios

const api = axios.create({
 baseURL: "https://example.com/", // replace with your API
 timeout: 5000,
});
Enter fullscreen mode Exit fullscreen mode

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);
  }
);
Enter fullscreen mode Exit fullscreen mode

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);
  }
);
Enter fullscreen mode Exit fullscreen mode

Now export the instance

export default api;
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
});
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)