Axios Interceptors with TypeScript

Axios Interceptors with TypeScript

ยท

4 min read

What is Axios Interceptors?

I asked ChatGPT what Axios Interceptors are.

I asked ChatGPT what Axios Interceptors are.

Axios Interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses in your application.

By using TypeScript to define the types of your request and response objects, you can ensure that your API calls are more efficient and secure.

With the examples provided in this post, you can get started using Axios Interceptors with TypeScript in your applications.

Request Interceptors

Axios request interceptors are commonly used for the following purposes:

  1. Authentication: You can use request interceptors to add authentication headers or tokens to requests before they are sent to the server. For example, you could use an interceptor to add an Authorization header with a bearer token or API key.

  2. Request transformation: You can use request interceptors to modify the request payload or URL. For example, you could use an interceptor to add query parameters to a GET request or to encode the request body in a specific format.

  3. Error handling: You can use request interceptors to handle errors that occur during the request process. For example, you could use an interceptor to handle network errors, server errors, or timeouts.

  4. Caching: You can use request interceptors to implement caching of requests, such as by adding a Cache-Control header to the request or by intercepting the response and storing it in a cache.

  5. Logging: You can use request interceptors to log requests and responses for debugging purposes. For example, you could use an interceptor to log the request method, URL, headers, and body, as well as the response status, headers, and body.

Response Interceptors

Axios response interceptors are functions that allow you to intercept and manipulate HTTP responses returned by Axios. Response interceptors are often used to handle common response formats, transform responses, or handle errors.

Here are some common use cases for response interceptors:

  1. Common response formats: You can use response interceptors to handle responses that have a common format, such as responses that include a status code and message. By intercepting the response and extracting the relevant data, you can simplify your code and make it more consistent.

  2. Response transformation: You can use response interceptors to transform the response data before it is passed to your application. For example, you could use an interceptor to parse a JSON response or extract a specific value from a response.

  3. Error handling: You can use response interceptors to handle errors that occur during the request process. For example, you could use an interceptor to check the response status code and throw an error if it indicates a problem, such as a 404 or 500 error.

  4. Caching: You can use response interceptors to implement caching of responses, such as by intercepting the response and storing it in a cache for future use.

  5. Logging: You can use response interceptors to log responses for debugging purposes. For example, you could use an interceptor to log the response status, headers, and body.

How Can I Use it?

Default Setting

import {
  AxiosError,
  AxiosInstance,
  // AxiosRequestConfig, // Change to InternalAxiosRequestConfig
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";


// For Make Log on Develop Mode
const logOnDev = (message: string) => {
  if (import.meta.env.MODE === "development") {
    console.log(message);
  }
};

Request Interceptor

// Request Interceptor
const onRequest = (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
  const { method, url } = config;
  // Set Headers Here
  // Check Authentication Here
  // Set Loading Start Here
  logOnDev(`๐Ÿš€ [API] ${method?.toUpperCase()} ${url} | Request`);

  if (method === "get") {
    config.timeout = 15000;
  }
  return config;
};

Response Interceptor

const onResponse = (response: AxiosResponse): AxiosResponse => {
  const { method, url } = response.config;
  const { status } = response;
  // Set Loading End Here
  // Handle Response Data Here
  // Error Handling When Return Success with Error Code Here
  logOnDev(`๐Ÿš€ [API] ${method?.toUpperCase()} ${url} | Response ${status}`);

  return response;
};

Error Response Interceptor

const onErrorResponse = (error: AxiosError | Error): Promise<AxiosError> => {
  if (axios.isAxiosError(error)) {
    const { message } = error;
    const { method, url } = error.config as AxiosRequestConfig;
    const { statusText, status } = error.response as AxiosResponse ?? {};

    logOnDev(
      `๐Ÿšจ [API] ${method?.toUpperCase()} ${url} | Error ${status} ${message}`
    );

    switch (status) {
      case 401: {
        // "Login required"
        break;
      }
      case 403: {
        // "Permission denied"
        break;
      }
      case 404: {
        // "Invalid request"
        break;
      }
      case 500: {
        // "Server error"
        break;
      }
      default: {
        // "Unknown error occurred"
        break;
      }
    }

    if (status === 401) {
      // Delete Token & Go To Login Page if you required.
      sessionStorage.removeItem("token");
    }
  } else {
    logOnDev(`๐Ÿšจ [API] | Error ${error.message}`);
  }

  return Promise.reject(error);
};

Setup All Interceptors

const setupInterceptors = (instance: AxiosInstance): AxiosInstance => {
  instance.interceptors.request.use(onRequest, onErrorResponse);
  instance.interceptors.response.use(onResponse, onErrorResponse);

  return instance;
};

Conclusion

Overall, using interceptors with Axios can help you write cleaner, more maintainable code and create a better experience for your users.

Did you find this article valuable?

Support JaeChan Lee by becoming a sponsor. Any amount is appreciated!

ย