DEV Community

Cover image for Funny mistake when I was using Axios Interceptor.
Sahanon Phisetpakasit
Sahanon Phisetpakasit

Posted on

Funny mistake when I was using Axios Interceptor.

This story just happened today when I was working with my previous project, which I intended to enhance some features, according to the feedback. Normally, I use the Axios Interceptor to intercept my request and response from the API server.
Additionally, I'd already set based urls and headers for fetching a request.



import axios from 'axios';

function getAccessToken() {
  return localStorage.getItem('access_token');
}
const axiosPublic = axios.create({
  baseURL: import.meta.env.VITE_SERVER,
  headers: {
    'Content-Type': 'application/json',
  },
});

axiosPublic.interceptors.request.use(
  async (config) => {
    if (getAccessToken()) {
      config.headers['Authorization'] = `Bearer ${getAccessToken()}`;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

axiosPublic.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        window.alert('Session Expired');
        window.localStorage.clear();
        window.location.reload();
      }
    }
  },
);

export default axiosPublic;


Enter fullscreen mode Exit fullscreen mode

This code snippet was meant to:

  1. Set based url -> so we can make url much shorter when fetching request.
  2. Set request header -> so we can call an API with authorization.
  3. Handle token expired -> so when the token expired the user will be forced to log out.

Due to my lack of testing and error handling, I never discovered this misbehavior before. When I'm trying to catch some errors that were thrown from the server's response, I couldn't catch it.

You guys might wonder, "Isn't it obvious? The answer was lied in your interceptor. I bet all experienced developers can fix this at first glance." Honestly, I can't argue with that πŸ˜…, but it made me have more understanding in what interceptor does.

As you guys can see, the interceptor caught an error when the server threw back with 401. What about the others? It did nothing when other errors were thrown. Therefore, it couldn't catch anything.

To fix this problem, I came up with this solution.



axiosPublic.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        window.alert('Session Expired');
        window.localStorage.clear();
        window.location.reload();
      }
      else {
        throw error;
      }
    }
  },
);


Enter fullscreen mode Exit fullscreen mode

Instead of sitting still and doing nothing with the other errors, just throw them. This way, when we call an API and get an error other than 401, we can catch it.
Meme

Or you might want to handle another error in an interceptor.



axiosPublic.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        // I used SweetAlert to present the message
        // Very neat and nice modal.
        return Swal.fire({
          title: 'Error',
          text: 'Session Expired',
          icon: 'error',
        }).then(() => {
          window.localStorage.clear();
          window.location.reload();
        })
      }
      if (error.response.status === 400) {
        return Swal.fire({
          title: 'Error',
          text: 'Bad Request',
          icon: 'error',
        }).then(() => {
          window.location.reload();
        })
      }
      else {
        throw error;
      }
    }
  },
);


Enter fullscreen mode Exit fullscreen mode

And again, hope you enjoy the story. Please feel free to leave any comment or thoughts. I really appreciate your time for reading my blog πŸ˜„.

Top comments (0)