diff --git a/src/lib/apiFetch.ts b/src/lib/apiFetch.ts index c303987..08cdf49 100644 --- a/src/lib/apiFetch.ts +++ b/src/lib/apiFetch.ts @@ -1,5 +1,9 @@ import { useProjectStore } from "@/store/projectStore"; import { getAccessToken } from "@/lib/authToken"; +import { signOut } from "next-auth/react"; +import { useAuthStore } from "@/store/authStore"; + +let isSigningOut = false; const resolveUrl = (input: RequestInfo | URL) => { if (typeof input === "string") return input; @@ -24,5 +28,16 @@ export const apiFetch = async ( if (projectId && !isMetaProjectsRequest(input)) { headers.set("X-Project-Id", projectId); } - return fetch(input, { ...init, headers }); + + const response = await fetch(input, { ...init, headers }); + + if (response.status === 401 && typeof window !== "undefined") { + useAuthStore.getState().setAccessToken(null); + if (!isSigningOut) { + isSigningOut = true; + await signOut({ redirect: true, callbackUrl: "/login" }); + } + } + + return response; };