diff --git a/src/lib/auth-store.ts b/src/lib/auth-store.ts index 110a7b7..08db710 100644 --- a/src/lib/auth-store.ts +++ b/src/lib/auth-store.ts @@ -19,8 +19,18 @@ import type { AuthUser } from "./types/user"; export const TOKEN_KEY = "sarlink_token"; export const USER_KEY = "sarlink_user"; -export const tokenAtom = atomWithStorage(TOKEN_KEY, null); -export const userAtom = atomWithStorage(USER_KEY, null); +// `getOnInit: true` is REQUIRED here. Without it, jotai defers reading +// localStorage until the atom is mounted by a React component, so the +// synchronous `store.get()` calls in `getToken()` / `isAuthenticated()` +// (used by RouteGuard, RootRedirect, and the axios interceptor during the +// first render on a page refresh) would see the initial `null` instead of the +// persisted token — bouncing an already-authenticated user to signin on reload. +export const tokenAtom = atomWithStorage(TOKEN_KEY, null, undefined, { + getOnInit: true, +}); +export const userAtom = atomWithStorage(USER_KEY, null, undefined, { + getOnInit: true, +}); /** Read the raw token (used by the axios request interceptor). */ export function getToken(): string | null {