Axios request interceptors not being updated on time

For my nextJS APP i am configuring the headers using axios interceptors:

import axios, { AxiosInstance, AxiosResponse } from "axios";

const httpClient: AxiosInstance = axios.create();
export const X_WORKSPACE_ID = "x-workspace-id";
export const X_APP_ID = "x-app-id";

let requestInterceptorId: number | null = null;
let responseInterceptorId: number | null = null;

export const setHttpClient = (
  logout: () => void,
  onError: (message: string) => void,
  workspaceId?: string | string[],
  appId?: string | string[]
) => {
  console.log("REQUESTINTERCEPTOR: ", requestInterceptorId);
  
  if (requestInterceptorId !== null) {
    httpClient.interceptors.request.eject(requestInterceptorId);
    console.log("Ejecting request interceptor");
  }

  if (responseInterceptorId !== null) {
    httpClient.interceptors.response.eject(responseInterceptorId);
    console.log("Ejecting response interceptor");
  }

  responseInterceptorId = httpClient.interceptors.response.use(
    (response: AxiosResponse) => response,
    (error) => {
      if (error?.response?.status === 500) {
        const { data } = error.response;
        if (data) {
          onError(data.message);
          return Promise.reject(new Error(data.message));
        }
      }

      if (error?.response?.status === 401 || error?.response?.status === 403) {
        logout();
      }
      return Promise.reject(error);
    }
  );

  console.log("WORKSPACEID:", workspaceId);

  requestInterceptorId = httpClient.interceptors.request.use((config) => {
    console.log("changing headers: ", workspaceId, appId);
    config.headers = {
      [X_WORKSPACE_ID]: workspaceId as string,
      [X_APP_ID]: appId ? String(appId) : String(workspaceId),
    };
    console.log("CONFIG-HEADERS: ", config.headers);

    return config;
  });
};

export const appHttpService = httpClient;

I am then calling the setHttpClient with this hook:


import { useEffect } from "react";
import { useRouter } from "next/router";
import { useLogout } from "./useLogout";
import { setHttpClient } from "../../config/auth/appHttpService";
import { useAppDispatch } from "../../hooks/useAppDispatch";
import { setNotificationDescription } from "../notificationsSlice";
import { useAppId } from "../../hooks/useAppId";

export const useHttpClientSetup = () => {
  const { logout } = useLogout();
  const {
    query: { workspaceId },
  } = useRouter();
  const { appId } = useAppId();

  const dispatch = useAppDispatch();
  const onError = (errorMessage: string) => {
    if (errorMessage) {
      dispatch(setNotificationDescription(errorMessage));
    }
  };

  useEffect(() => {
    console.log("setting Http Client with: ", workspaceId);
    setHttpClient(logout, onError, workspaceId);
  }, [workspaceId]);
};

Here is where i call the useHttpClient hook:

const DashboardPage = (): ReactElement => {
  const dashboardData = useDashboardData();
  const { userSettings } = useUserSettingsData();
  const { period, onPeriodChanges, isLoading } = useDashboardPeriod();
  const { t } = useTranslation();
  const {
    query: { workspaceId },
  } = useRouter();

  useHttpClientSetup();

  useEffect(() => {
    if (workspaceId) {
      // Trigger data fetching or other actions based on workspaceId
      console.log("Workspace ID changed:", workspaceId);
    }
  }, [workspaceId]);

  const getBreadcrumbsPath = () =>
    new BreadcrumbsPath(t("translation:dashboard"), generatePath({ pathname: AppRoutes.DASHBOARD, workspaceId }));

  return (...rest of code)

The Issue:

The headers are getting configured correctly, but they are always one step late in the process. So when the app Id changes, the console -> console.log(“WORKSPACEID:”, workspaceId) is logging the correct values, but the next one inside the function body is always logging the previous one, and thus the config headers are always one step behind.

When the appId changes, the console logs the correct values for workspaceId and appId in the useEffect hook, but the values inside the interceptor function are always one step behind.

What I’ve Tried:

  • Ensured the interceptors are being correctly ejected and re-applied.

  • Logging to verify the values being passed to the interceptor setup function.

  • Read about using { synchronous: true }, but it seems to be no longer supported.

New contributor

Philippe Ducasse is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật