Skip to content

fix: enhance cache key management in useQuery - #3230

Merged
eduardoformiga merged 4 commits into
devfrom
fix/SFS-3037-cache-busting-use-query-1
Mar 24, 2026
Merged

eduardoformiga merged 4 commits into
devfrom
fix/SFS-3037-cache-busting-use-query-1

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Feb 25, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

This PR aims to improve cache data from queries between logged-in and anonymous users.

How it works?

  • Introduced a session-based cache key suffix in useQuery to differentiate between logged-in and anonymous users.
  • This change prevents stale product data from being served when users switch session states, improving data accuracy in the application.

Problem
The SWR cache key in useQuery was only operationName + variables. Because ProductShelf variables (term, sort, selectedFacets, etc.) are the same for logged-in and logged-out users, SWR reused the same cache and showed data from the previous session (e.g. wrong prices or availability after login/logout).

Solution
The cache key now includes the authentication state:
getSessionCacheKeySuffix()
Uses the same logic as the request: getClientCacheBustingValue() from cookieCacheBusting.ts.

Resulting keys:
operationName::variables::anonymous for logged-out users
operationName::variables:: for logged-in users

When the user logs in or out, the key changes so SWR treats it as a different cache entry: it fetches again and does not reuse data from the other session.

How to test it?

Starters Deploy Preview

References

Checklist

You may erase this after checking them all 😉

PR Title and Commit Messages

  • PR title and commit messages follow the Conventional Commits specification
    • Available prefixes: feat, fix, chore, docs, style, refactor, ci and test

PR Description

  • Added a label according to the PR goal - breaking change, bug, contributing, performance, documentation..

Dependencies

  • Committed the pnpm-lock.yaml file when there were changes to the packages

Documentation

  • PR description
  • For documentation changes, ping @Mariana-Caetano to review and update (Or submit a doc request)

Summary by CodeRabbit

  • Bug Fixes
    • Improved logout flow with more comprehensive client-side storage and database cleanup to ensure complete sign-out.
    • Ensures response processing during logout so cookies are fully applied before redirecting.
    • Automatic full-page refresh after logout to load fresh session data.
    • Prevents stale data by separating cached data for anonymous vs. authenticated sessions.

- Modified the comment in the checkAndReloadIfReturnedFromLogout function to include a period for improved readability and consistency.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner February 25, 2026 21:18
@eduardoformiga
eduardoformiga requested review from emersonlaurentino and lemagnetic and removed request for a team February 25, 2026 21:18
@coderabbitai

coderabbitai Bot commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR replaces cookie-based cache-busting with session person ID tracking, adds a hook to force a cache-busting reload after logout, expands logout cleanup to remove sessionStorage and IndexedDB entries (via idb-keyval), and separates SWR caches per session state to avoid stale data across login/logout transitions.

Changes

Cohort / File(s) Summary
Dependency Addition
packages/core/package.json
Added idb-keyval ^5.1.3 for IndexedDB operations during logout cleanup.
Logout & Reload Flow
packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsx, packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts, packages/core/src/pages/_app.tsx
Added useReloadAfterLogoutReturn hook and setReloadAfterLogoutReturn call during logout. Logout now awaits res.json() to allow Set-Cookie processing, clears sessionStorage key faststore_person_id, and dynamically imports idb-keyval to delete fs::session and keyval-store with try/catch guards. Hook mounted in _app to detect return and force cache-busting full reload.
Session-based Cache Busting
packages/core/src/utils/cookieCacheBusting.ts, packages/core/src/sdk/graphql/useQuery.ts, packages/core/src/sdk/graphql/request.ts
Reworked cache-busting to derive value from session person ID instead of an httpOnly cookie. Renamed storage keys/functions (e.g., STORAGE_KEY_PERSON_ID, getPersonId, storePersonId), updated logic to detect person ID changes, and appended a session-derived suffix to SWR keys to separate caches per session. Minor comment update in request.ts.
Tests
packages/core/test/utils/cookieCacheBusting.test.ts
Updated tests to mock the session module, use session-based helpers (setSessionPerson/clearSessionPerson), and assert storage under STORAGE_KEY_PERSON_ID and cache-bust behavior for timestamp::personId composite values.

Sequence Diagram

sequenceDiagram
    participant User
    participant Drawer as OrganizationDrawer
    participant API as Logout API
    participant Storage as Browser Storage
    participant App as App Component / Hook
    participant Page as Browser Navigation

    User->>Drawer: Click "Logout"
    Drawer->>API: POST /logout
    API-->>Drawer: Response (with Set-Cookie)
    Drawer->>Drawer: await res.json() to let Set-Cookie apply
    Drawer->>Storage: remove sessionStorage keys (faststore_person_id, etc)
    Drawer->>Storage: (dynamic) import idb-keyval -> delete 'fs::session' and 'keyval-store'
    Drawer->>App: call setReloadAfterLogoutReturn()
    Drawer->>Page: redirect to logout/landing page
    Page->>App: App mounts (user returns)
    App->>Storage: check RELOAD_AFTER_LOGOUT_KEY
    alt Flag present
        App->>Storage: clear flag
        App->>Page: window.location.replace(url?t=timestamp) (cache-bypass)
        Page->>Page: full reload with fresh HTML/API responses
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • chore: version 2026 21 1144 #3182: Overlaps logout/storage cleanup and session cache-busting changes touching OrganizationDrawer and logout flow; likely directly related.

Poem

🍃 Session cleared, a clean restart,

Cookies give way to person_id's art,
IndexedDB swept, a reload takes flight,
SWR splits caches, making states right,
A fresher page greets the returning sight.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main focus of the changeset: improving cache key management in useQuery by adding session-based cache key separation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/SFS-3037-cache-busting-use-query-1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@eduardoformiga eduardoformiga changed the title fix: update comment for clarity in logout reload logic fix: enhance cache key management in useQuery Feb 25, 2026
@codesandbox-ci

codesandbox-ci Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
packages/core/src/utils/cookieCacheBusting.ts (1)

104-111: clearStorage() is called on every render via the SWR key function — worth noting it's a no-op after the first call but adds repeated storage access.

getClientCacheBustingValue is invoked by getSessionCacheKeySuffix in useQuery.ts, which runs on every SWR key evaluation (i.e., every render). When the user is not logged in, clearStorage() is called each time. Since removeItem on a non-existent key is a no-op, this is functionally safe but generates unnecessary storage churn on every render.

Consider short-circuiting early if already cleared, or moving the cleanup to a one-time effect.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/utils/cookieCacheBusting.ts` around lines 104 - 111, The
function getClientCacheBustingValue currently calls clearStorage() on every
render when getPersonId() returns null; to avoid repeated storage access, add a
short-circuit (e.g., a module-level boolean like storageCleared) that is checked
before calling clearStorage() and set to true after the first call, or move the
cleanup to a one-time effect in the consumer (getSessionCacheKeySuffix /
useQuery.ts); update getClientCacheBustingValue to check the flag before calling
clearStorage() so subsequent calls are no-ops without touching storage
repeatedly.
packages/core/src/sdk/graphql/useQuery.ts (1)

22-28: getSessionCacheKeySuffix calls getClientCacheBustingValue, which has storage side effects on every SWR key evaluation.

When the user is logged out, each SWR key evaluation triggers clearStorage() inside getClientCacheBustingValue. While benign (removeItem is idempotent), it's worth knowing this runs on every render cycle for every useQuery call. The impact is low but consider memoizing or using a lightweight flag to avoid redundant storage access in the hot path.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/graphql/useQuery.ts` around lines 22 - 28,
getSessionCacheKeySuffix currently calls getClientCacheBustingValue on every
evaluation causing repeated storage side-effects; change
getSessionCacheKeySuffix to cache the computed suffix in a module-level variable
(or a memo flag) so that after the first browser-side call it returns the cached
suffix ('', value, or 'anonymous') thereafter, still preserving the server check
(typeof window === 'undefined') and the fallback logic; reference
getSessionCacheKeySuffix and getClientCacheBustingValue when implementing the
cache to avoid repeated clearStorage/removeItem calls in hot paths.
packages/core/src/sdk/sessionAuthState.ts (1)

6-6: Consider exporting PersonIdGetter for type-safe call sites.

Callers passing a function to setCacheBustingSource have to manually match the signature or rely on inference. Exporting the type makes the contract explicit and improves DX.

-type PersonIdGetter = () => string | null
+export type PersonIdGetter = () => string | null
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/sessionAuthState.ts` at line 6, Export the
PersonIdGetter type so callers can import it and get a typed signature for
functions passed to setCacheBustingSource: change the local alias declaration to
an exported type (e.g. "export type PersonIdGetter = () => string | null") and
ensure any module-level exports (e.g. index/barrel) include PersonIdGetter so
consumer code can import it and annotate the parameter for
setCacheBustingSource.
packages/core/src/pages/_app.tsx (1)

9-9: useReloadAfterLogoutReturn is now a global app concern — consider relocating it out of OrganizationDrawer.

The hook is imported from deep inside OrganizationDrawer/, but it's wired at the top-level _app.tsx. This placement suggests it belongs in a more general location, e.g., src/sdk/ or src/hooks/, to reflect its app-wide scope and avoid misleading coupling to the drawer component.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/pages/_app.tsx` at line 9, The hook
useReloadAfterLogoutReturn is imported into the top-level _app.tsx but
implemented deep in OrganizationDrawer, so move it to a global location (e.g.,
src/hooks/useReloadAfterLogoutReturn.ts or
src/sdk/useReloadAfterLogoutReturn.ts) and update exports/imports accordingly;
specifically, extract the implementation from OrganizationDrawer's folder into
the new file, export the hook from there, update _app.tsx to import from the new
module name, and update OrganizationDrawer (and any other files) to import the
hook from the new global path to avoid misleading coupling.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsx`:
- Around line 60-75: The outer try is swallowing errors from the first cleanup
step and preventing the subsequent IndexedDB deletion (new Promise deleting
'keyval-store') from running; split the logic into two guarded blocks so each
step runs and failures are handled independently: wrap the idb-keyval import and
await del('fs::session') in its own try/catch (referencing the dynamic import
and del call), then always run the IndexedDB deletion logic (referencing
window.indexedDB, idb.deleteDatabase('keyval-store') and the
onsuccess/onerror/onblocked resolve handlers) in a separate try/catch so that an
error in the first step won’t skip deleting 'keyval-store'.

In `@packages/core/src/pages/_app.tsx`:
- Around line 28-29: The conditional call to the hook useScrollRestoration (via
storeConfig.experimental?.scrollRestoration && useScrollRestoration()) violates
the Rules of Hooks; change the call site to call useScrollRestoration
unconditionally next to useReloadAfterLogoutReturn(), and move the feature flag
check into the hook implementation of useScrollRestoration so the hook returns
early when storeConfig.experimental?.scrollRestoration is falsy. Ensure
useScrollRestoration contains the guard (early return) and any side-effects only
run when the flag is enabled.

In `@packages/core/src/sdk/graphql/request.ts`:
- Line 32: Fix the typo in the comment that reads "Get cache busting value based
person?.id from session" by inserting the missing preposition to read "Get cache
busting value based on person?.id from session" so the comment referencing
person?.id and session in request.ts is grammatically correct.

---

Nitpick comments:
In `@packages/core/src/pages/_app.tsx`:
- Line 9: The hook useReloadAfterLogoutReturn is imported into the top-level
_app.tsx but implemented deep in OrganizationDrawer, so move it to a global
location (e.g., src/hooks/useReloadAfterLogoutReturn.ts or
src/sdk/useReloadAfterLogoutReturn.ts) and update exports/imports accordingly;
specifically, extract the implementation from OrganizationDrawer's folder into
the new file, export the hook from there, update _app.tsx to import from the new
module name, and update OrganizationDrawer (and any other files) to import the
hook from the new global path to avoid misleading coupling.

In `@packages/core/src/sdk/graphql/useQuery.ts`:
- Around line 22-28: getSessionCacheKeySuffix currently calls
getClientCacheBustingValue on every evaluation causing repeated storage
side-effects; change getSessionCacheKeySuffix to cache the computed suffix in a
module-level variable (or a memo flag) so that after the first browser-side call
it returns the cached suffix ('', value, or 'anonymous') thereafter, still
preserving the server check (typeof window === 'undefined') and the fallback
logic; reference getSessionCacheKeySuffix and getClientCacheBustingValue when
implementing the cache to avoid repeated clearStorage/removeItem calls in hot
paths.

In `@packages/core/src/sdk/sessionAuthState.ts`:
- Line 6: Export the PersonIdGetter type so callers can import it and get a
typed signature for functions passed to setCacheBustingSource: change the local
alias declaration to an exported type (e.g. "export type PersonIdGetter = () =>
string | null") and ensure any module-level exports (e.g. index/barrel) include
PersonIdGetter so consumer code can import it and annotate the parameter for
setCacheBustingSource.

In `@packages/core/src/utils/cookieCacheBusting.ts`:
- Around line 104-111: The function getClientCacheBustingValue currently calls
clearStorage() on every render when getPersonId() returns null; to avoid
repeated storage access, add a short-circuit (e.g., a module-level boolean like
storageCleared) that is checked before calling clearStorage() and set to true
after the first call, or move the cleanup to a one-time effect in the consumer
(getSessionCacheKeySuffix / useQuery.ts); update getClientCacheBustingValue to
check the flag before calling clearStorage() so subsequent calls are no-ops
without touching storage repeatedly.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8318044 and 648c34a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (10)
  • packages/core/package.json
  • packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsx
  • packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts
  • packages/core/src/pages/_app.tsx
  • packages/core/src/sdk/graphql/request.ts
  • packages/core/src/sdk/graphql/useQuery.ts
  • packages/core/src/sdk/session/index.ts
  • packages/core/src/sdk/sessionAuthState.ts
  • packages/core/src/utils/cookieCacheBusting.ts
  • packages/core/test/utils/cookieCacheBusting.test.ts

Comment on lines +60 to +75
try {
if ('indexedDB' in window) {
const { del } = await import('idb-keyval')
await del('fs::session').catch(() => {})
}

const idb = window.indexedDB
if (idb) {
await new Promise<void>((resolve) => {
const req = idb.deleteDatabase('keyval-store')
req.onsuccess = () => resolve()
req.onerror = () => resolve()
req.onblocked = () => resolve()
})
}
} catch {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Separate the guarded cleanup steps so DB deletion always runs.

With one outer try, any failure in the first step skips deleteDatabase('keyval-store'), which can leave stale IndexedDB state after logout.

💡 Proposed fix
-  try {
-    if ('indexedDB' in window) {
-      const { del } = await import('idb-keyval')
-      await del('fs::session').catch(() => {})
-    }
-
-    const idb = window.indexedDB
-    if (idb) {
-      await new Promise<void>((resolve) => {
-        const req = idb.deleteDatabase('keyval-store')
-        req.onsuccess = () => resolve()
-        req.onerror = () => resolve()
-        req.onblocked = () => resolve()
-      })
-    }
-  } catch {}
+  if ('indexedDB' in window) {
+    try {
+      const { del } = await import('idb-keyval')
+      await del('fs::session')
+    } catch {}
+
+    try {
+      const idb = window.indexedDB
+      if (idb) {
+        await new Promise<void>((resolve) => {
+          const req = idb.deleteDatabase('keyval-store')
+          req.onsuccess = () => resolve()
+          req.onerror = () => resolve()
+          req.onblocked = () => resolve()
+        })
+      }
+    } catch {}
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
if ('indexedDB' in window) {
const { del } = await import('idb-keyval')
await del('fs::session').catch(() => {})
}
const idb = window.indexedDB
if (idb) {
await new Promise<void>((resolve) => {
const req = idb.deleteDatabase('keyval-store')
req.onsuccess = () => resolve()
req.onerror = () => resolve()
req.onblocked = () => resolve()
})
}
} catch {}
if ('indexedDB' in window) {
try {
const { del } = await import('idb-keyval')
await del('fs::session')
} catch {}
try {
const idb = window.indexedDB
if (idb) {
await new Promise<void>((resolve) => {
const req = idb.deleteDatabase('keyval-store')
req.onsuccess = () => resolve()
req.onerror = () => resolve()
req.onblocked = () => resolve()
})
}
} catch {}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsx`
around lines 60 - 75, The outer try is swallowing errors from the first cleanup
step and preventing the subsequent IndexedDB deletion (new Promise deleting
'keyval-store') from running; split the logic into two guarded blocks so each
step runs and failures are handled independently: wrap the idb-keyval import and
await del('fs::session') in its own try/catch (referencing the dynamic import
and del call), then always run the IndexedDB deletion logic (referencing
window.indexedDB, idb.deleteDatabase('keyval-store') and the
onsuccess/onerror/onblocked resolve handlers) in a separate try/catch so that an
error in the first step won’t skip deleting 'keyval-store'.

Comment on lines +28 to 29
useReloadAfterLogoutReturn()
storeConfig.experimental?.scrollRestoration && useScrollRestoration()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

useScrollRestoration is called conditionally — pre-existing Rules of Hooks violation.

Line 29 (storeConfig.experimental?.scrollRestoration && useScrollRestoration()) conditionally calls a hook, which violates the Rules of Hooks. While this is pre-existing and not introduced by this PR, the new useReloadAfterLogoutReturn() call on line 28 is correctly unconditional. Consider fixing the adjacent violation to avoid subtle bugs during React reconciliation.

🛠️ Suggested fix for the conditional hook call

Move the condition inside the hook itself, or call unconditionally:

-  storeConfig.experimental?.scrollRestoration && useScrollRestoration()
+  useScrollRestoration()

Then guard inside useScrollRestoration:

// inside useScrollRestoration
if (!storeConfig.experimental?.scrollRestoration) return
// ... rest of the hook
🧰 Tools
🪛 Biome (2.4.4)

[error] 29-29: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

(lint/correctness/useHookAtTopLevel)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/pages/_app.tsx` around lines 28 - 29, The conditional call
to the hook useScrollRestoration (via
storeConfig.experimental?.scrollRestoration && useScrollRestoration()) violates
the Rules of Hooks; change the call site to call useScrollRestoration
unconditionally next to useReloadAfterLogoutReturn(), and move the feature flag
check into the hook implementation of useScrollRestoration so the hook returns
early when storeConfig.experimental?.scrollRestoration is falsy. Ensure
useScrollRestoration contains the guard (early return) and any side-effects only
run when the flag is enabled.

options?: RequestOptions
) => {
// Get cache busting value based on cookie changes
// Get cache busting value based person?.id from session

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Typo in comment — missing "on".

-  // Get cache busting value based person?.id from session
+  // Get cache busting value based on person?.id from session
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Get cache busting value based person?.id from session
// Get cache busting value based on person?.id from session
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/graphql/request.ts` at line 32, Fix the typo in the
comment that reads "Get cache busting value based person?.id from session" by
inserting the missing preposition to read "Get cache busting value based on
person?.id from session" so the comment referencing person?.id and session in
request.ts is grammatically correct.

@eduardoformiga
eduardoformiga force-pushed the fix/SFS-3037-cache-busting-use-query-1 branch from 2eaf5b6 to 648c34a Compare February 25, 2026 22:28
- Deleted the sessionAuthState module, which provided a getter for the current session's person ID.
- Updated imports in useQuery and cookieCacheBusting to utilize sessionStore directly for accessing session data.
- Adjusted logic in cookieCacheBusting to read person ID from sessionStore, ensuring compatibility with the new structure.
- Updated the RELOAD_DELAY_MS constant from 1000ms to 2000ms to provide a smoother transition after logout, allowing for better handling of navigation and state management.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts (1)

21-28: Consider consistent environment guard pattern.

Line 22 checks typeof sessionStorage === 'undefined' while line 59 checks typeof window === 'undefined'. For consistency and broader compatibility (some browsers throw on sessionStorage access in private mode even when it exists), consider unifying to check window first:

 export const setReloadAfterLogoutReturn = (): void => {
-  if (typeof sessionStorage === 'undefined') return
+  if (typeof window === 'undefined') return
   try {
     sessionStorage.setItem(RELOAD_AFTER_LOGOUT_KEY, '1')

The try/catch already handles access errors, so this is a minor readability alignment.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts`
around lines 21 - 28, The guard in setReloadAfterLogoutReturn currently checks
typeof sessionStorage but should match the module's consistent pattern and first
verify the environment by checking typeof window === 'undefined' before touching
storage; update setReloadAfterLogoutReturn to return early when typeof window
=== 'undefined' (leave the existing try/catch around
sessionStorage.setItem(RELOAD_AFTER_LOGOUT_KEY, '1') to handle private-mode or
access errors) so behavior and readability align with the other checks in this
file.
packages/core/test/utils/cookieCacheBusting.test.ts (1)

32-37: Consider adding an edge case test for readInitial fallback.

The implementation uses sessionStore.read() ?? sessionStore.readInitial(). Current tests always set both mocks to the same value. Adding a test where read() returns null but readInitial() returns a session would verify the fallback path.

📝 Example additional test
it('should fallback to readInitial when read returns null', () => {
  mockRead.mockReturnValue(null)
  mockReadInitial.mockReturnValue({ person: { id: 'initial-user' } })
  
  jest.spyOn(Date, 'now').mockReturnValue(1700000000000)
  
  const result = getClientCacheBustingValue()
  
  expect(result).toBe('1700000000000::initial-user')
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/test/utils/cookieCacheBusting.test.ts` around lines 32 - 37,
Add a unit test that verifies the fallback path where sessionStore.read()
returns null and sessionStore.readInitial() returns a session: mockRead to
return null and mockReadInitial to return a session object (e.g., { person: {
id: 'initial-user' } }), spy Date.now() to a fixed timestamp, call
getClientCacheBustingValue(), and assert the returned string combines the
timestamp and the initial-user id; reference the existing mocks
mockRead/mockReadInitial and the functions
read/readInitial/getClientCacheBustingValue when adding this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts`:
- Around line 30-51: The PR promised immediate cache-busting navigation but the
constant RELOAD_DELAY_MS and the setTimeout call inside
checkAndReloadIfReturnedFromLogout still introduce a 2s delay; remove the
RELOAD_DELAY_MS constant and replace the setTimeout(forceRefreshWithoutCache,
RELOAD_DELAY_MS) call in checkAndReloadIfReturnedFromLogout with a direct call
to forceRefreshWithoutCache() so the cache-busting navigation occurs immediately
(retain forceRefreshWithoutCache as-is).

---

Nitpick comments:
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts`:
- Around line 21-28: The guard in setReloadAfterLogoutReturn currently checks
typeof sessionStorage but should match the module's consistent pattern and first
verify the environment by checking typeof window === 'undefined' before touching
storage; update setReloadAfterLogoutReturn to return early when typeof window
=== 'undefined' (leave the existing try/catch around
sessionStorage.setItem(RELOAD_AFTER_LOGOUT_KEY, '1') to handle private-mode or
access errors) so behavior and readability align with the other checks in this
file.

In `@packages/core/test/utils/cookieCacheBusting.test.ts`:
- Around line 32-37: Add a unit test that verifies the fallback path where
sessionStore.read() returns null and sessionStore.readInitial() returns a
session: mockRead to return null and mockReadInitial to return a session object
(e.g., { person: { id: 'initial-user' } }), spy Date.now() to a fixed timestamp,
call getClientCacheBustingValue(), and assert the returned string combines the
timestamp and the initial-user id; reference the existing mocks
mockRead/mockReadInitial and the functions
read/readInitial/getClientCacheBustingValue when adding this test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c84fc3d8-563c-407b-9dde-2f3cf968211e

📥 Commits

Reviewing files that changed from the base of the PR and between 2eaf5b6 and 73799e3.

📒 Files selected for processing (4)
  • packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts
  • packages/core/src/sdk/graphql/useQuery.ts
  • packages/core/src/utils/cookieCacheBusting.ts
  • packages/core/test/utils/cookieCacheBusting.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/sdk/graphql/useQuery.ts

- Updated the RELOAD_DELAY_MS constant from 2000ms to 1000ms to enhance the user experience by providing a quicker transition after logout.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts (1)

30-46: ⚠️ Potential issue | 🟠 Major

Trigger the refresh immediately once the logout flag is found.

Line 46 still delays the cache-busting navigation by 1 second. That leaves a stale post-logout window where the user can briefly see or interact with pre-refresh state before the hard reload kicks in.

🔧 Suggested change
-const RELOAD_DELAY_MS = 1000
-
 const checkAndReloadIfReturnedFromLogout = (): void => {
   try {
     if (sessionStorage.getItem(RELOAD_AFTER_LOGOUT_KEY)) {
       sessionStorage.removeItem(RELOAD_AFTER_LOGOUT_KEY)
-      setTimeout(forceRefreshWithoutCache, RELOAD_DELAY_MS)
+      forceRefreshWithoutCache()
     }
   } catch {
     // Ignore.
   }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts`
around lines 30 - 46, The code currently waits RELOAD_DELAY_MS before calling
forceRefreshWithoutCache inside checkAndReloadIfReturnedFromLogout, which allows
a stale post-logout state; change checkAndReloadIfReturnedFromLogout to call
forceRefreshWithoutCache() immediately (remove the setTimeout call and the
RELOAD_DELAY_MS delay usage), and remove the now-unused RELOAD_DELAY_MS constant
if desired; references: checkAndReloadIfReturnedFromLogout,
forceRefreshWithoutCache, RELOAD_AFTER_LOGOUT_KEY, RELOAD_DELAY_MS.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts`:
- Around line 21-24: The code in setReloadAfterLogoutReturn assumes
sessionStorage access won't throw, but reading it can raise a SecurityError;
wrap the access and setItem call in a try/catch so any exceptions are swallowed
(no-op) and do not break execution; specifically, update
setReloadAfterLogoutReturn to try to read/write sessionStorage using
RELOAD_AFTER_LOGOUT_KEY inside a try block and catch errors (ignoring or
optionally logging) so restricted contexts (sandboxed/opaque origins) won't
throw.

---

Duplicate comments:
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts`:
- Around line 30-46: The code currently waits RELOAD_DELAY_MS before calling
forceRefreshWithoutCache inside checkAndReloadIfReturnedFromLogout, which allows
a stale post-logout state; change checkAndReloadIfReturnedFromLogout to call
forceRefreshWithoutCache() immediately (remove the setTimeout call and the
RELOAD_DELAY_MS delay usage), and remove the now-unused RELOAD_DELAY_MS constant
if desired; references: checkAndReloadIfReturnedFromLogout,
forceRefreshWithoutCache, RELOAD_AFTER_LOGOUT_KEY, RELOAD_DELAY_MS.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2b005912-cf3b-4813-a303-dbaf6c902584

📥 Commits

Reviewing files that changed from the base of the PR and between 73799e3 and 595fbd6.

📒 Files selected for processing (1)
  • packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/useReloadAfterLogoutReturn.ts

@eduardoformiga
eduardoformiga merged commit 3f28502 into dev Mar 24, 2026
3 checks passed
@eduardoformiga
eduardoformiga deleted the fix/SFS-3037-cache-busting-use-query-1 branch March 24, 2026 19:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants