Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Sep 2, 2025

Description

Clear fetchCache after sign out

Fixes: USER-3157

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes
    • Automatically clears client-side fetch cache after signing out in the browser, preventing stale or previous-user data from reappearing.
    • Improves reliability when switching accounts or returning to the app post sign-out by ensuring a clean state for subsequent requests.
    • Works transparently with existing integrations; no configuration or API changes required.

@changeset-bot
Copy link

changeset-bot bot commented Sep 2, 2025

⚠️ No Changeset found

Latest commit: e389b96

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

Walkthrough

Adds a browser-only post-sign-out hook in Clerk.signOut to clear a fetch cache via a global window function. Exposes the internal clearFetchCache as window.__clerkClearFetchCache in useFetch when in a browser. No exported API signatures change.

Changes

Cohort / File(s) Summary
Sign-out hook to clear fetch cache
packages/clerk-js/src/core/clerk.ts
After emitting UserSignOut, calls window.__clerkClearFetchCache() if present (browser-only), before transitive state updates. No signature or error handling changes.
Expose fetch cache clearer on window
packages/clerk-js/src/ui/hooks/useFetch.ts
Attaches internal clearFetchCache to window.__clerkClearFetchCache in browser-safe way. Internal cache logic unchanged; no exported API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant SignOut as Clerk.signOut()
  participant Browser as window
  participant Cache as useFetch cache

  User->>SignOut: Trigger signOut()
  SignOut->>SignOut: Emit UserSignOut event
  alt browser environment
    SignOut->>Browser: Check and call __clerkClearFetchCache()
    Browser->>Cache: clearFetchCache()
    Cache-->>Browser: requestCache reset
  else SSR / function absent
    SignOut-->>SignOut: Skip cache clear
  end
  SignOut->>SignOut: setTransitiveState(...)
  SignOut-->>User: Resolve
Loading
sequenceDiagram
  participant App as App init / useFetch module
  participant Browser as window
  participant Cache as clearFetchCache

  App->>App: Load useFetch
  alt browser environment
    App->>Browser: window.__clerkClearFetchCache = clearFetchCache
  else non-browser
    App-->>App: No-op
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Ensure prepare_first_factor is sent on repeated sign-in attempts after sign-out (USER-3157) Clearing fetch cache on sign-out may address stale state, but the diff doesn’t show explicit changes in SignIn flow or prepare call logic to confirm.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
None identified All observed changes relate to clearing client-side fetch cache during/after sign-out, which plausibly targets USER-3157’s stale state between sign-out/in cycles.

Poem

I hop through code with whiskers keen,
A cache now cleared, the sign-out clean.
With every leap, stale bits take flight,
Fresh fetches dawn in morning light.
Thump-thump—new flows align just right,
Carrots cached? Not tonight! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/clear-fetch-cache-on-sign-out

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel
Copy link

vercel bot commented Sep 2, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 2, 2025 7:04pm

Comment on lines +34 to +38
/**
* Global function to clear the fetch cache.
* This is exposed on the window object to allow core modules to clear the cache
* without importing from UI modules.
*/
Copy link
Member Author

Choose a reason for hiding this comment

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

I don't really like this solution long term, but for now it does the job

@jacekradko jacekradko changed the title fix: allow clearing fetch cache on sign out fix(clerk-js): Allow clearing fetch cache on sign out Sep 2, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/hooks/useFetch.ts (1)

34-42: Expose global with typing; prefer event-based coupling long-term; and notify subscribers on clear

  • Keep the stopgap global, but add typing and ensure clearing notifies subscribers so subscribers re-read the new empty cache immediately.
  • Longer-term, consider clearing via an event listener (e.g., subscribe to events.UserSignOut) to avoid UI→core coupling through window (aligns with previous concern).

Apply to notify subscribers and add explicit return type:

-export const clearFetchCache = () => {
-  requestCache = new Map<string, State>();
-};
+export const clearFetchCache = (): void => {
+  requestCache = new Map<string, State>();
+  // Inform all subscribers that cache snapshots changed
+  subscribers.forEach(callback => callback());
+};

Optionally add an ambient type (either here or shared types) so both sides compile without any-casts:

declare global {
  interface Window {
    __clerkClearFetchCache?: () => void;
  }
}
🧹 Nitpick comments (1)
packages/clerk-js/src/core/clerk.ts (1)

528-531: Type-safe global, simpler call, and ordering note

  • Type the window global to avoid any-casts and use optional chaining for brevity.
  • Consider moving the call after #setTransitiveState() if you observe UI flicker from subscriber notifications (see related suggestion in useFetch.ts). Otherwise, current placement is fine.

Apply:

-      if (typeof window !== 'undefined' && (window as any).__clerkClearFetchCache) {
-        (window as any).__clerkClearFetchCache();
-      }
+      if (typeof window !== 'undefined') {
+        window.__clerkClearFetchCache?.();
+      }

Also add typing to the existing Window augmentation in this file:

 declare global {
   interface Window {
     Clerk?: Clerk;
     __clerk_publishable_key?: string;
     __clerk_proxy_url?: ClerkInterface['proxyUrl'];
     __clerk_domain?: ClerkInterface['domain'];
+    __clerkClearFetchCache?: () => void;
   }
 }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ea65f20 and e389b96.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
  • packages/clerk-js/src/ui/hooks/useFetch.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/core/clerk.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/core/clerk.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/core/clerk.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/core/clerk.ts

Copy link
Member

@panteliselef panteliselef left a comment

Choose a reason for hiding this comment

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

As you mentioned this would not be a long term solution and neither #6690 seems to be, since we are focusing solely in the fact that a sign out is performed. The solution is much simpler and I opened a PR for it.

@jacekradko jacekradko closed this Sep 3, 2025
@jacekradko jacekradko deleted the fix/clear-fetch-cache-on-sign-out branch September 3, 2025 18:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants