MOHAN 136f41020f Deduplicate concurrent token refresh to fix login redirect loop
The dashboard fires several authenticated requests at once (summary,
cashflow, merchants, accounts, transactions, plus the app shell's own
profile fetch). Once the 60-second access-token cookie expires, all
of them 401 together, and apiFetch had each one independently call
/api/auth/refresh. Refresh tokens are single-use and rotate on the
backend, so only the first of these racing calls succeeded — the
rest sent an already-consumed refresh token, got rejected, cleared
auth cookies, and hard-redirected to /login. Symptom: land in the
app, then get bounced back to login almost immediately, repeatedly.

Fix: share one in-flight refresh promise across all callers so a
burst of concurrent 401s triggers exactly one refresh call.
2026-08-26 18:24:08 +05:30

111 lines
2.8 KiB
TypeScript

// Client-side fetch helper with automatic HttpOnly cookie refresh.
export interface ApiResponse<T = unknown> {
data: T;
meta: { timestamp: string; version: "v1" };
error: null | { message: string; code?: string };
}
const USER_KEY = "ledgerone_user";
export function getStoredToken(): string {
return "";
}
export function getStoredUser<T = unknown>(): T | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem(USER_KEY);
return raw ? (JSON.parse(raw) as T) : null;
} catch {
return null;
}
}
export function storeAuthTokens(data: {
accessToken?: string;
refreshToken?: string;
user: unknown;
}): void {
localStorage.setItem(USER_KEY, JSON.stringify(data.user));
}
export function clearAuth(): void {
localStorage.removeItem(USER_KEY);
}
// Shared in-flight refresh promise so concurrent 401s (e.g. several widgets
// loading at once) all await the same refresh call instead of each firing
// their own — refresh tokens are single-use, so racing calls would otherwise
// invalidate each other and force a false session-expired logout.
let refreshInFlight: Promise<boolean> | null = null;
async function tryRefresh(): Promise<boolean> {
if (refreshInFlight) return refreshInFlight;
refreshInFlight = (async () => {
try {
const res = await fetch("/api/auth/refresh", {
method: "POST",
headers: { "Content-Type": "application/json" },
});
if (!res.ok) {
clearAuth();
return false;
}
const payload = (await res.json()) as ApiResponse<unknown>;
if (payload.error) {
clearAuth();
return false;
}
return true;
} catch {
clearAuth();
return false;
}
})();
try {
return await refreshInFlight;
} finally {
refreshInFlight = null;
}
}
export async function apiFetch<T = unknown>(
path: string,
options: RequestInit = {}
): Promise<ApiResponse<T>> {
const headers: Record<string, string> = {
...(options.headers as Record<string, string>),
};
if (
options.body &&
typeof options.body === "string" &&
!headers["Content-Type"]
) {
headers["Content-Type"] = "application/json";
}
let res = await fetch(path, { ...options, headers });
// Auto-refresh on 401
if (res.status === 401) {
const refreshed = await tryRefresh();
if (refreshed) {
res = await fetch(path, { ...options, headers });
} else {
if (typeof window !== "undefined") {
window.location.href = "/login";
}
return {
data: null as T,
meta: { timestamp: new Date().toISOString(), version: "v1" },
error: { message: "Session expired. Please sign in again." },
};
}
}
return res.json() as Promise<ApiResponse<T>>;
}