-
Notifications
You must be signed in to change notification settings - Fork 382
fix(clerk-js, shared): Display empty data for authenticated billing hooks after sign out #6747
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
fix(clerk-js, shared): Display empty data for authenticated billing hooks after sign out #6747
Conversation
…ooks after sign out
🦋 Changeset detectedLatest commit: dd7b2e9 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds release metadata for a patch. Adjusts commerce and billing React hooks to defer fetching until Clerk is loaded and to handle signed-out state. Introduces isSignedIn into pagination config and flow. Updates SWR keys/fetchers to skip network calls when unauthenticated and to preserve previous data on sign-out. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor UI as Component
participant Hook as Feature Hook (e.g., usePlans/usePaymentAttempts)
participant Pager as usePagesOrInfinite
participant SWR as SWR Cache
participant Fetcher as Hook Fetcher
participant Clerk as Clerk SDK
UI->>Hook: call hook(options)
Hook->>Hook: if !clerk.loaded => fetcher = undefined
Hook->>Pager: usePagesOrInfinite({ isSignedIn, shouldFetch, fetcher })
Pager->>SWR: get(swrKey based on isSignedIn/shouldFetch)
alt isSignedIn === false or fetcher === undefined
SWR-->>UI: no fetch, return empty/prev data
else isSignedIn === true and fetcher defined
SWR->>Fetcher: invoke with args
Fetcher->>Clerk: billing API call
Clerk-->>SWR: data
SWR-->>UI: data
end
note over UI,SWR: On sign-out, isSignedIn false or userId missing skips fetch and shows empty/previous data
sequenceDiagram
autonumber
actor UI as Component
participant Sub as useSubscription
participant SWR as SWR
participant Clerk as Clerk SDK
UI->>Sub: useSubscription()
Sub->>SWR: key { billingEnabled, userId? }
alt userId missing
SWR->>Sub: call fetcher
Sub-->>SWR: return null (skip)
SWR-->>UI: keep previous data (no new fetch)
else userId present
SWR->>Sub: call fetcher
Sub->>Clerk: getSubscription(args)
Clerk-->>SWR: subscription
SWR-->>UI: subscription data
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Pre-merge checks (3 passed)✅ Passed checks (3 passed)
Poem
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information. Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal). Please share your feedback with us on this Discord post. ✨ Finishing Touches
🧪 Generate unit tests
Comment |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
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: 1
🧹 Nitpick comments (3)
packages/shared/src/react/types.ts (1)
121-127
: Make the new config flag explicitly immutable.Mark
isSignedIn
asreadonly
for clarity that callers shouldn’t mutate it post-construction.- isSignedIn?: boolean; + readonly isSignedIn?: boolean;packages/shared/src/react/hooks/useSubscription.tsx (1)
50-50
: Good: hide data on sign-out while preserving previous data semantics.Gating the fetcher on
userId
and returningnull
prevents stale exposure after sign-out and plays nicely withkeepPreviousData
.Consider explicitly typing the SWR data to ensure
null
is an accepted value for consumers and to reduce downstream narrowing:- const swr = useSWR( + const swr = useSWR< + Awaited<ReturnType<typeof clerk.billing.getSubscription>> | null + >(Also applies to: 53-53, 57-64
packages/shared/src/react/hooks/createCommerceHook.tsx (1)
48-49
: Solid: optionalfor
with sane default, tighter enablement, and sign-in signaling.
- Defaulting
for
to'user'
avoids boilerplate.isEnabled
correctly relies onclerk.loaded
and billing flags.- Passing
isSignedIn: Boolean(user)
integrates with the new gating downstream.Two minor nits:
- Memoize
fetchFn
since it’s a dependency-like value that can cause re-renders in children hooks:- const fetchFn = useFetcher(_for || 'user'); + const fetchFn = useMemo(() => useFetcher(_for || 'user'), [_for, useFetcher]);
- Consider documenting the unauthenticated escape hatch (
options.unauthenticated
) in JSDoc for the factory to guide future hook authors.Also applies to: 55-55, 58-58, 91-91, 100-100
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
.changeset/major-steaks-hug.md
(1 hunks)packages/shared/src/react/hooks/createCommerceHook.tsx
(3 hunks)packages/shared/src/react/hooks/usePagesOrInfinite.ts
(2 hunks)packages/shared/src/react/hooks/usePaymentAttempts.tsx
(1 hunks)packages/shared/src/react/hooks/usePlans.tsx
(1 hunks)packages/shared/src/react/hooks/useStatements.tsx
(1 hunks)packages/shared/src/react/hooks/useSubscription.tsx
(1 hunks)packages/shared/src/react/types.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/types.ts
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/shared/src/react/hooks/createCommerceHook.tsx
**/*.{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/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/types.ts
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/shared/src/react/hooks/createCommerceHook.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/types.ts
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/shared/src/react/hooks/createCommerceHook.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/types.ts
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/shared/src/react/hooks/createCommerceHook.tsx
**/*.{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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/types.ts
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/shared/src/react/hooks/createCommerceHook.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/hooks/createCommerceHook.tsx
**/*.{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/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/types.ts
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/shared/src/react/hooks/createCommerceHook.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/shared/src/react/hooks/useStatements.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/shared/src/react/hooks/usePaymentAttempts.tsx
packages/shared/src/react/hooks/usePlans.tsx
packages/shared/src/react/hooks/createCommerceHook.tsx
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/major-steaks-hug.md
🧬 Code graph analysis (2)
packages/shared/src/react/hooks/useSubscription.tsx (1)
packages/react/src/isomorphicClerk.ts (1)
organization
(692-698)
packages/shared/src/react/hooks/createCommerceHook.tsx (2)
packages/types/src/commerce.ts (1)
ForPayerType
(121-121)packages/shared/src/react/types.ts (1)
PaginatedResources
(14-80)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
.changeset/major-steaks-hug.md (1)
5-5
: Include all impacted packages in the changeset (if applicable).PR title references “clerk-js, shared” but the changeset bumps only
@clerk/shared
. If any runtime/public API in other published packages is affected (e.g.,@clerk/clerk-js
,@clerk/react
), add them here to ensure a coherent release.If needed, update the changeset like:
--- -'@clerk/shared': patch +'@clerk/shared': patch +'@clerk/clerk-js': patch --- Display empty data for authenticated billing hooks after sign out.packages/shared/src/react/hooks/usePaymentAttempts.tsx (1)
14-17
: LGTM: fetcher is correctly gated onclerk.loaded
.This aligns with the new enablement logic in the factory and prevents premature fetches.
packages/shared/src/react/hooks/useStatements.tsx (1)
14-17
: LGTM: consistentclerk.loaded
gating.Matches the pattern used across billing hooks and avoids early fetches.
packages/shared/src/react/hooks/usePlans.tsx (1)
14-16
: LGTM: defers fetcher creation until Clerk is loaded.Behavior matches the unauthenticated nature of plans while still avoiding early access to
clerk.billing
.Confirm
getPlans
does not requireorgId
whenfor: 'organization'
. If it does, forward it:- return ({ orgId, ...rest }) => { - // Cleanup `orgId` from the params - return clerk.billing.getPlans({ ...rest, for: _for }); - }; + return ({ orgId, ...rest }) => { + // Cleanup `orgId` from the params but forward it if required by the API + return clerk.billing.getPlans({ ...rest, for: _for, ...(orgId ? { orgId } : {}) }); + };
const isSignedIn = config.isSignedIn; | ||
|
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.
💡 Verification agent
🧩 Analysis chain
Critical: unauthenticated gating is missing for the infinite mode path.
isSignedIn
gates the paginated path (via swrKey
and swrFetcher
) but not the useSWRInfinite
key/fetcher. On sign-out, infinite hooks can still revalidate/fetch, potentially leaking stale data.
Mirror the gating in the infinite path:
// Key selector
pageIndex => {
if (!triggerInfinite || !enabled || isSignedIn === false) {
return null;
}
return {
...params,
...cacheKeys,
initialPage: initialPageRef.current + pageIndex,
pageSize: pageSizeRef.current,
};
},
// Fetcher
cacheKeyParams => {
if (isSignedIn === false) {
return null;
}
// @ts-ignore
const requestParams = getDifferentKeys(cacheKeyParams, cacheKeys);
// @ts-ignore
return fetcher?.(requestParams);
},
To ensure no remaining infinite consumers bypass the sign-in gating, run:
Also applies to: 163-169
🏁 Script executed:
#!/bin/bash
# Find infinite-mode hooks and call sites
rg -nP "infinite\s*:\s*true" -C3
rg -nP "useSWRInfinite\(" -C3 packages/shared/src
Length of output: 16520
🏁 Script executed:
#!/bin/bash
sed -n '140,260p' packages/shared/src/react/hooks/usePagesOrInfinite.ts
Length of output: 3705
Guard infinite-mode SWR hooks behind isSignedIn
In packages/shared/src/react/hooks/usePagesOrInfinite.ts (around lines 192–198), update both the useSWRInfinite key selector and fetcher to return null when isSignedIn is false:
pageIndex => {
if (!triggerInfinite || !enabled || isSignedIn === false) {
return null;
}
…
},
cacheKeyParams => {
if (isSignedIn === false) {
return null;
}
…
},
🤖 Prompt for AI Agents
packages/shared/src/react/hooks/usePagesOrInfinite.ts around lines 192-198, the
SWR infinite key selector and fetcher need to be guarded by the isSignedIn flag;
modify the useSWRInfinite key selector to return null when !triggerInfinite ||
!enabled || isSignedIn === false, and modify the fetcher/cacheKeyParams path to
return null immediately when isSignedIn === false so both the key and fetcher
short-circuit when the user is not signed in.
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.
makes sense to me
Description
This PR ensures:
This happens when the billing hooks use
keepPreviousData: true
(default behaviour of AIOs). We want to keep using that to avoid CLS and content flashing on revalidations, but at the same time we don't want to display the previous "stale" data after the user has signed out.Before
Screen.Recording.2025-09-10.at.3.50.38.PM.mov
After
Screen.Recording.2025-09-10.at.3.49.24.PM.mov
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Chores