Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix(auth): prevent transient session logout on rate limits and network errors (#3575)

Hoàng Anh Tuấn0847874d04f1
diff --git a/apps/web/src/libs/auth/session.test.ts b/apps/web/src/libs/auth/session.test.ts
new file mode 100644
index 000000000..13cbdc99c
--- /dev/null
+++ b/apps/web/src/libs/auth/session.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it, vi } from "vitest";
+import { getSession } from "./session";
+
+const getSessionMock = vi.hoisted(() => vi.fn());
+
+vi.mock("./client", () => ({
+ authClient: {
+ getSession: getSessionMock,
+ },
+}));
+
+describe("getSession", () => {
+ it("returns session data on successful fetch", async () => {
+ const mockSession = { user: { id: "user-1", name: "Alice" }, session: { id: "sess-1" } };
+ getSessionMock.mockResolvedValueOnce({ data: mockSession, error: null });
+
+ const result = await getSession();
+ expect(result).toEqual(mockSession);
+ });
+
+ it("returns null when no session is present (data is null)", async () => {
+ getSessionMock.mockResolvedValueOnce({ data: null, error: null });
+
+ const result = await getSession();
+ expect(result).toBeNull();
+ });
+
+ it("returns null when session is explicitly unauthorized (HTTP 401)", async () => {
+ getSessionMock.mockResolvedValueOnce({ data: null, error: { status: 401, message: "Unauthorized" } });
+
+ const result = await getSession();
+ expect(result).toBeNull();
+ });
+
+ it("throws on rate-limited responses (HTTP 429)", async () => {
+ getSessionMock.mockResolvedValueOnce({
+ data: null,
+ error: { status: 429, message: "Too many requests. Please try again later." },
+ });
+
+ await expect(getSession()).rejects.toThrow("Too many requests. Please try again later.");
+ });
+
+ it("throws on server errors (HTTP 500)", async () => {
+ getSessionMock.mockResolvedValueOnce({
+ data: null,
+ error: { status: 500, message: "Internal server error" },
+ });
+
+ await expect(getSession()).rejects.toThrow("Internal server error");
+ });
+
+ it("throws on transient network errors", async () => {
+ getSessionMock.mockResolvedValueOnce({
+ data: null,
+ error: { message: "Failed to fetch" },
+ });
+
+ await expect(getSession()).rejects.toThrow("Failed to fetch");
+ });
+});
diff --git a/apps/web/src/libs/auth/session.ts b/apps/web/src/libs/auth/session.ts
index fb5127b57..baa662add 100644
--- a/apps/web/src/libs/auth/session.ts
+++ b/apps/web/src/libs/auth/session.ts
@@ -5,6 +5,12 @@ import { authClient } from "./client";
export const getSession = async (): Promise<AuthSession | null> => {
const { data, error } = await authClient.getSession();
- if (error) return null;
- return data as AuthSession;
+ if (error) {
+ // HTTP 401 explicitly denotes an unauthenticated state or expired session.
+ if (error.status === 401) return null;
+ // For transient errors (e.g. 429 Too Many Requests, 5xx server/DB errors, network drops),
+ // throw so callers can differentiate between unauthenticated and transient failures.
+ throw new Error(error.message || `Session check failed with status ${error.status}`);
+ }
+ return (data as AuthSession) ?? null;
};
diff --git a/apps/web/src/libs/query/client.test.ts b/apps/web/src/libs/query/client.test.ts
new file mode 100644
index 000000000..596366165
--- /dev/null
+++ b/apps/web/src/libs/query/client.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { getQueryClient } from "./client";
+
+describe("getQueryClient mutationCache", () => {
+ it("invalidates data queries but excludes auth session and flags on mutation settled", async () => {
+ const queryClient = getQueryClient();
+
+ queryClient.setQueryData(["auth", "session"], { user: { id: "u-1" } });
+ queryClient.setQueryData(["flags"], { disableSignups: false });
+ queryClient.setQueryData(["resume", "list"], [{ id: "res-1" }]);
+
+ const authQuery = queryClient.getQueryCache().find({ queryKey: ["auth", "session"] });
+ const flagsQuery = queryClient.getQueryCache().find({ queryKey: ["flags"] });
+ const resumeQuery = queryClient.getQueryCache().find({ queryKey: ["resume", "list"] });
+
+ expect(authQuery?.isStale()).toBe(false);
+ expect(flagsQuery?.isStale()).toBe(false);
+ expect(resumeQuery?.isStale()).toBe(false);
+
+ // Trigger a mutation that settles
+ const mutation = queryClient.getMutationCache().build(queryClient, {
+ mutationFn: async () => "success",
+ });
+ await mutation.execute(undefined);
+
+ // Resume query is invalidated (stale)
+ expect(resumeQuery?.isStale()).toBe(true);
+
+ // Auth and flags are preserved (not stale)
+ expect(authQuery?.isStale()).toBe(false);
+ expect(flagsQuery?.isStale()).toBe(false);
+ });
+});
diff --git a/apps/web/src/libs/query/client.ts b/apps/web/src/libs/query/client.ts
index f00b1c007..592063176 100644
--- a/apps/web/src/libs/query/client.ts
+++ b/apps/web/src/libs/query/client.ts
@@ -18,7 +18,12 @@ export const getQueryClient = () => {
mutationCache: new MutationCache({
onSettled: (_1, _2, _3, _4, _5, context) => {
if (context?.meta?.noInvalidate) return;
- void queryClient.invalidateQueries();
+ void queryClient.invalidateQueries({
+ predicate: (query) => {
+ const key = query.queryKey[0];
+ return key !== "auth" && key !== "flags";
+ },
+ });
},
}),
});
diff --git a/apps/web/src/libs/root-context.test.ts b/apps/web/src/libs/root-context.test.ts
new file mode 100644
index 000000000..65258fed9
--- /dev/null
+++ b/apps/web/src/libs/root-context.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it, vi } from "vitest";
+import { QueryClient } from "@tanstack/react-query";
+import { loadRootContext, sessionQueryKey } from "./root-context";
+
+const getSessionMock = vi.hoisted(() => vi.fn());
+const flagsGetMock = vi.hoisted(() => vi.fn().mockResolvedValue({ disableSignups: false, disableEmailAuth: false }));
+
+vi.mock("./auth/session", () => ({
+ getSession: getSessionMock,
+}));
+
+vi.mock("./locale", () => ({
+ getLocale: () => "en-US",
+ loadLocale: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("./orpc/client", () => ({
+ client: {
+ flags: {
+ get: flagsGetMock,
+ },
+ },
+}));
+
+vi.mock("./theme", () => ({
+ getTheme: () => "system",
+}));
+
+describe("loadRootContext", () => {
+ it("loads root context with freshly fetched session", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const mockSession = {
+ user: { id: "user-1", name: "Alice" },
+ session: { id: "sess-1" },
+ };
+ getSessionMock.mockResolvedValueOnce(mockSession);
+
+ const context = await loadRootContext(queryClient);
+ expect(context.session).toEqual(mockSession);
+ });
+
+ it("retains cached session when getSession encounters a transient error on refresh", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const cachedSession = {
+ user: { id: "user-1", name: "Alice" },
+ session: { id: "sess-1" },
+ };
+ queryClient.setQueryData(sessionQueryKey, cachedSession);
+ // Mark stale/invalid so getSession is invoked
+ void queryClient.invalidateQueries({ queryKey: sessionQueryKey });
+
+ getSessionMock.mockRejectedValueOnce(new Error("Too many requests. Please try again later."));
+
+ const context = await loadRootContext(queryClient);
+ expect(context.session).toEqual(cachedSession);
+ });
+
+ it("re-throws error when getSession fails and there is no cached session", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ getSessionMock.mockRejectedValueOnce(new Error("Session check failed with status 500"));
+
+ await expect(loadRootContext(queryClient)).rejects.toThrow("Session check failed with status 500");
+ });
+});
diff --git a/apps/web/src/libs/root-context.ts b/apps/web/src/libs/root-context.ts
index 9a175ee1f..d4bf409e1 100644
--- a/apps/web/src/libs/root-context.ts
+++ b/apps/web/src/libs/root-context.ts
@@ -1,3 +1,4 @@
+import type { AuthSession } from "@reactive-resume/auth/types";
import type { QueryClient } from "@tanstack/react-query";
import { getSession } from "./auth/session";
import { getLocale, loadLocale } from "./locale";
@@ -15,12 +16,23 @@ export async function loadRootContext(queryClient: QueryClient) {
const theme = getTheme();
const locale = getLocale();
- const [session, flags] = await Promise.all([
- queryClient.query({
+ const sessionPromise = queryClient
+ .query({
queryKey: sessionQueryKey,
queryFn: getSession,
staleTime: (query) => (query.state.data ? 60_000 : 0),
- }),
+ })
+ .catch((error: unknown) => {
+ const cached = queryClient.getQueryData<AuthSession | null>(sessionQueryKey);
+ if (cached) {
+ console.warn("[session] Failed to refresh session, retaining cached session:", error);
+ return cached;
+ }
+ throw error;
+ });
+
+ const [session, flags] = await Promise.all([
+ sessionPromise,
queryClient.query({ queryKey: flagsQueryKey, queryFn: () => client.flags.get(), staleTime: 5 * 60_000 }),
loadLocale(locale),
]);