Skip to content

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

LauraBeatris
Copy link
Member

@LauraBeatris LauraBeatris commented Aug 10, 2025

Description

This PR introduces a conditional on client update, to detect a session transition from active to pending, 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
export default clerkMiddleware(
  async (auth, req) => {
    if (isProtectedRoute(req)) {
     // Re-run for pending session, redirects to `/sign-in/tasks`
      await auth.protect();
    }

    return NextResponse.next();
  }
);

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

    • Improved session handling to ensure authentication context is updated when the session status changes from active to pending, enhancing reliability for Next.js integrations.
  • Tests

    • Added new tests to verify correct behavior when session status transitions, ensuring hooks are triggered as expected.

@LauraBeatris LauraBeatris self-assigned this Aug 10, 2025
Copy link

changeset-bot bot commented Aug 10, 2025

🦋 Changeset detected

Latest commit: a4c36cc

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch

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

Copy link

vercel bot commented Aug 10, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 10, 2025 10:20pm

@LauraBeatris LauraBeatris requested review from a team, nikosdouvlis and panteliselef August 10, 2025 22:22
@LauraBeatris LauraBeatris marked this pull request as ready for review August 10, 2025 22:25
Copy link
Contributor

coderabbitai bot commented Aug 10, 2025

📝 Walkthrough

Walkthrough

A changeset file was added to document a patch update for the @clerk/clerk-js package, specifically noting the addition of Next.js hook triggers when the session status changes from active to pending. In the core code, the updateClient method of the Clerk class was updated to detect this session status transition and invoke two global hooks (__unstable__onBeforeSetActive and __unstable__onAfterSetActive) if present. A new test suite was introduced to verify that these hooks are called as expected during the session status transition. No changes were made to exported or public API signatures.

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.


🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • 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.

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: 2

🧹 Nitpick comments (2)
packages/clerk-js/src/core/clerk.ts (1)

2261-2276: Optional: call onAfterSetActive post-accessor/token update for consistency

Elsewhere (setActive, #handlePendingSession) we await onBeforeSetActive, then update internal state and cookies, then await onAfterSetActive. Here, hooks are fired before #setAccessors(session) and events.TokenUpdate. If Next.js revalidation relies on cookies (__session, __client_uat), consider moving the onAfterSetActive 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 and eventBus.emit(...), chain onAfterSetActive.

Happy to propose a refactor if desired.

.changeset/mean-jobs-stare.md (1)

1-5: Changeset looks good

Patch 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6459f7d and a4c36cc.

📒 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
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/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)

Comment on lines +2546 to +2609

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);
});
});
Copy link
Contributor

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 returns void (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 transitions pendingactive.

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.

Comment on lines +2261 to +2276
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());
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

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 after onBeforeSetActive 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.

Suggested change
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.

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.

3 participants