-
Notifications
You must be signed in to change notification settings - Fork 371
chore(clerk-js): Trigger Next.js hooks on session status transition to pending
#6511
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
base: main
Are you sure you want to change the base?
Conversation
🦋 Changeset detectedLatest commit: a4c36cc The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 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 Git ↗︎
|
96741e1
to
b6c741c
Compare
b6c741c
to
7a001b3
Compare
7a001b3
to
199771f
Compare
📝 WalkthroughWalkthroughA changeset file was added to document a patch update for the Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. 🪧 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 comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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: 2
🧹 Nitpick comments (2)
packages/clerk-js/src/core/clerk.ts (1)
2261-2276
: Optional: callonAfterSetActive
post-accessor/token update for consistencyElsewhere (
setActive
,#handlePendingSession
) we awaitonBeforeSetActive
, then update internal state and cookies, then awaitonAfterSetActive
. Here, hooks are fired before#setAccessors(session)
andevents.TokenUpdate
. If Next.js revalidation relies on cookies (__session
,__client_uat
), consider moving theonAfterSetActive
call to run after#setAccessors
and token emission for consistent semantics.If you want to keep it non-blocking but adjust sequencing:
- fire
onBeforeSetActive
first,- after
#setAccessors
andeventBus.emit(...)
, chainonAfterSetActive
.Happy to propose a refactor if desired.
.changeset/mean-jobs-stare.md (1)
1-5
: Changeset looks goodPatch classification and message are appropriate. Consider adding a brief note that the hook invocation is non-blocking and ordered (before→after) to aid release notes readers.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
.changeset/mean-jobs-stare.md
(1 hunks)packages/clerk-js/src/core/__tests__/clerk.test.ts
(1 hunks)packages/clerk-js/src/core/clerk.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
.changeset/**
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/mean-jobs-stare.md
**/*.{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/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.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/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.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/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.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
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/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.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/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/__tests__/clerk.test.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/core/__tests__/clerk.test.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/core/__tests__/clerk.test.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/core/__tests__/clerk.test.ts
🧬 Code Graph Analysis (2)
packages/clerk-js/src/core/clerk.ts (1)
packages/shared/src/utils/index.ts (1)
noop
(5-5)
packages/clerk-js/src/core/__tests__/clerk.test.ts (1)
packages/clerk-js/src/core/clerk.ts (1)
Clerk
(195-2889)
|
||
describe('updateClient', () => { | ||
afterEach(() => { | ||
// cleanup global window pollution | ||
(window as any).__unstable__onBeforeSetActive = null; | ||
(window as any).__unstable__onAfterSetActive = null; | ||
}); | ||
|
||
it('runs server revalidation hooks when session transitions from `active` to `pending`', async () => { | ||
const mockOnBeforeSetActive = jest.fn().mockReturnValue(Promise.resolve()); | ||
const mockOnAfterSetActive = jest.fn().mockReturnValue(Promise.resolve()); | ||
(window as any).__unstable__onBeforeSetActive = mockOnBeforeSetActive; | ||
(window as any).__unstable__onAfterSetActive = mockOnAfterSetActive; | ||
|
||
const mockActiveSession = { | ||
id: 'session_1', | ||
status: 'active', | ||
user: { id: 'user_1' }, | ||
lastActiveToken: { getRawString: () => 'token_1' }, | ||
}; | ||
|
||
const mockPendingSession = { | ||
id: 'session_1', | ||
status: 'pending', | ||
user: { id: 'user_1' }, | ||
lastActiveToken: { getRawString: () => 'token_1' }, | ||
}; | ||
|
||
const mockInitialClient = { | ||
sessions: [mockActiveSession], | ||
signedInSessions: [mockActiveSession], | ||
lastActiveSessionId: 'session_1', | ||
}; | ||
|
||
const mockUpdatedClient = { | ||
sessions: [mockPendingSession], | ||
signedInSessions: [mockPendingSession], | ||
lastActiveSessionId: 'session_1', | ||
}; | ||
|
||
const sut = new Clerk(productionPublishableKey); | ||
|
||
// Manually set the initial client and session state to simulate active session | ||
// without going through load() or setActive() | ||
sut.updateClient(mockInitialClient as any); | ||
|
||
// Verify we start with an active session | ||
expect(sut.session?.status).toBe('active'); | ||
|
||
// Call updateClient with the new client that has pending session | ||
sut.updateClient(mockUpdatedClient as any); | ||
|
||
// Verify hooks were called | ||
await waitFor(() => { | ||
expect(mockOnBeforeSetActive).toHaveBeenCalledTimes(1); | ||
expect(mockOnAfterSetActive).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
// Verify that onAfterSetActive was called after onBeforeSetActive | ||
const beforeCallTime = mockOnBeforeSetActive.mock.invocationCallOrder[0]; | ||
const afterCallTime = mockOnAfterSetActive.mock.invocationCallOrder[0]; | ||
expect(afterCallTime).toBeGreaterThan(beforeCallTime); | ||
}); | ||
}); |
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.
🛠️ Refactor suggestion
Add coverage for sync onBeforeSetActive
and no-transition scenarios
The test covers the Promise-returning case well. Please add:
- A test where
__unstable__onBeforeSetActive
returnsvoid
(sync), asserting__unstable__onAfterSetActive
still runs once. This will catch regressions and pairs with the proposed code fix. - A negative test asserting hooks are not called when the session remains
active
or transitionspending
→active
.
I can draft these tests if helpful.
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/__tests__/clerk.test.ts around lines 2546 to 2609,
add two new tests inside the 'updateClient' describe block: one where
__unstable__onBeforeSetActive is a synchronous function returning void and
verify __unstable__onAfterSetActive is still called once, and another negative
test where the session status remains 'active' or changes from 'pending' to
'active' and assert that neither hook is called. This will ensure coverage for
synchronous hooks and no-transition scenarios as requested.
const hasTransitionedToPendingStatus = this.session.status === 'active' && session?.status === 'pending'; | ||
if (hasTransitionedToPendingStatus) { | ||
const onBeforeSetActive: SetActiveHook = | ||
typeof window !== 'undefined' && typeof window.__unstable__onBeforeSetActive === 'function' | ||
? window.__unstable__onBeforeSetActive | ||
: noop; | ||
|
||
const onAfterSetActive: SetActiveHook = | ||
typeof window !== 'undefined' && typeof window.__unstable__onAfterSetActive === 'function' | ||
? window.__unstable__onAfterSetActive | ||
: noop; | ||
|
||
// Execute hooks to update server authentication context and trigger | ||
// page protections in clerkMiddleware or server components | ||
void onBeforeSetActive()?.then?.(() => void onAfterSetActive()); | ||
} |
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.
Ensure onAfterSetActive
always runs and avoid unhandled rejections; improve robustness of hook chaining
Current chaining calls onAfterSetActive
only when onBeforeSetActive
returns a thenable. If onBeforeSetActive
is synchronous (returns void), onAfterSetActive
will never execute. Also, rejections are not caught, risking unhandled promise rejections without any logging.
Use a Promise-resolved chain so:
onAfterSetActive
runs afteronBeforeSetActive
for both sync and async hooks- errors are caught and logged (without breaking
updateClient
flow)
Suggested diff:
- // Execute hooks to update server authentication context and trigger
- // page protections in clerkMiddleware or server components
- void onBeforeSetActive()?.then?.(() => void onAfterSetActive());
+ // Execute hooks to update server authentication context and trigger
+ // page protections in clerkMiddleware or server components
+ void Promise.resolve(onBeforeSetActive())
+ .then(() => onAfterSetActive())
+ .catch(err => {
+ logger.warnOnce(
+ `Clerk: Failed to run __unstable__onBeforeSetActive/__unstable__onAfterSetActive during active->pending transition: ${String(
+ err,
+ )}`,
+ );
+ });
This keeps behavior non-blocking while ensuring ordering and resilience.
📝 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.
const hasTransitionedToPendingStatus = this.session.status === 'active' && session?.status === 'pending'; | |
if (hasTransitionedToPendingStatus) { | |
const onBeforeSetActive: SetActiveHook = | |
typeof window !== 'undefined' && typeof window.__unstable__onBeforeSetActive === 'function' | |
? window.__unstable__onBeforeSetActive | |
: noop; | |
const onAfterSetActive: SetActiveHook = | |
typeof window !== 'undefined' && typeof window.__unstable__onAfterSetActive === 'function' | |
? window.__unstable__onAfterSetActive | |
: noop; | |
// Execute hooks to update server authentication context and trigger | |
// page protections in clerkMiddleware or server components | |
void onBeforeSetActive()?.then?.(() => void onAfterSetActive()); | |
} | |
const hasTransitionedToPendingStatus = this.session.status === 'active' && session?.status === 'pending'; | |
if (hasTransitionedToPendingStatus) { | |
const onBeforeSetActive: SetActiveHook = | |
typeof window !== 'undefined' && typeof window.__unstable__onBeforeSetActive === 'function' | |
? window.__unstable__onBeforeSetActive | |
: noop; | |
const onAfterSetActive: SetActiveHook = | |
typeof window !== 'undefined' && typeof window.__unstable__onAfterSetActive === 'function' | |
? window.__unstable__onAfterSetActive | |
: noop; | |
// Execute hooks to update server authentication context and trigger | |
// page protections in clerkMiddleware or server components | |
void Promise.resolve(onBeforeSetActive()) | |
.then(() => onAfterSetActive()) | |
.catch(err => { | |
logger.warnOnce( | |
`Clerk: Failed to run __unstable__onBeforeSetActive/__unstable__onAfterSetActive during active->pending transition: ${String( | |
err, | |
)}`, | |
); | |
}); | |
} |
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts between lines 2261 and 2276, the current
code calls onAfterSetActive only if onBeforeSetActive returns a thenable, which
means onAfterSetActive is skipped if onBeforeSetActive is synchronous. To fix
this, wrap the call to onBeforeSetActive in Promise.resolve() to ensure
onAfterSetActive always runs after it, regardless of sync or async nature.
Additionally, add a catch block to log any errors from either hook to prevent
unhandled promise rejections, while keeping the flow non-blocking.
Description
This PR introduces a conditional on client update, to detect a session transition from
active
topending
, that occurs when a instance task gets "unsatisfied" - this could happen, for the "Allow personal workspace" setting, when an app owner removes a user from an organization, or due to deprovisioning event on an SSO Identity Provider.Once the transition gets detected, then hooks are executed to revalidate the server auth state. This makes sure that existing page protections on
clerkMiddleware
get triggered, such in the example below:CleanShot.2025-08-10.at.19.21.01.mp4
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Tests