diff --git a/src/lib/api.ts b/src/lib/api.ts index c2f7a33..7e0ccf0 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -2,6 +2,8 @@ import axios from "axios"; import { config } from "@config/config"; import { useProjectStore } from "@/store/projectStore"; import { getAccessToken } from "@/lib/authToken"; +import { signOut } from "next-auth/react"; +import { useAuthStore } from "@/store/authStore"; export const API_URL = process.env.NEXT_PUBLIC_API_URL || config.BACKEND_URL; @@ -9,6 +11,8 @@ export const api = axios.create({ baseURL: API_URL, }); +let isSigningOut = false; + const isMetaProjectsRequest = (request: { baseURL?: string; url?: string; @@ -32,3 +36,17 @@ api.interceptors.request.use(async (request) => { return request; }); + +api.interceptors.response.use( + (response) => response, + async (error) => { + if (error?.response?.status === 401 && typeof window !== "undefined") { + useAuthStore.getState().setAccessToken(null); + if (!isSigningOut) { + isSigningOut = true; + await signOut({ redirect: true, callbackUrl: "/login" }); + } + } + return Promise.reject(error); + }, +);