sajad torkamani

Let’s suppose you want to deal with 401 Unauthorized status codes by redirecting the user to the login screen. You can use an approach like this:

import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'
import authService from './services/authService'

const apiClient: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
})

apiClient.interceptors.request.use(addAuthorizationHeader)
apiClient.interceptors.response.use(undefined, handleError)

function addAuthorizationHeader(
  config: AxiosRequestConfig
): AxiosRequestConfig {
  if (authService.isAuthenticated()) {
    config.headers['Authorization'] = `Bearer ${authService.getToken()}`
  }

  return config
}

function handleError(error: AxiosError) {
  const response = error.response?.data

  // Wasn't able to get any response at all. Perhaps because of network errors.
  if (!response) {
    return Promise.reject(error)
  }

  if (
    response.code === 'UNAUTHENTICATED' &&
    response.message === 'Invalid token'
  ) {
    return authService.logout()
  }

  return Promise.reject(error)
}

export default apiClient

Sources

Leave a comment

Your email address will not be published. Required fields are marked *