-
Notifications
You must be signed in to change notification settings - Fork 405
fix(clerk-js): Allow clearing fetch cache on sign out #6688
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
WalkthroughAdds 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
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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changes
Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
| /** | ||
| * 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. | ||
| */ |
There was a problem hiding this comment.
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
There was a problem hiding this 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 throughwindow(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.
📒 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.tspackages/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.tspackages/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.tspackages/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.tspackages/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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.tspackages/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.tspackages/clerk-js/src/core/clerk.ts
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Description
Clear fetchCache after sign out
Fixes: USER-3157
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit