Skip to content

fix(clerk-js): Update server-side revalidation hooks for session status transition #6572

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

Merged
merged 5 commits into from
Aug 19, 2025

Conversation

LauraBeatris
Copy link
Member

@LauraBeatris LauraBeatris commented Aug 18, 2025

Description

Fixes an issue where auth.protect() does not redirect when the Next.js app is deployed on Vercel.

onBeforeSetActive was leading to a 405 request re-write on Vercel. onAfterSetActive should suffice to trigger router.refresh.

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

    • Fixed server-side cache revalidation in Next.js when a session moves from active to pending.
    • Reduced delays during sign-out and when sessions become pending by streamlining session-state transitions.
  • Enhancements

    • Post-activation navigation for organization selection and creation now uses the app router callback, improving navigation flow.
  • Tests

    • Updated tests to reflect the new session transition behavior and adjusted activation-hook assertions.
  • Chores

    • Bumped @clerk/clerk-js to a patch release and updated release metadata.

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

changeset-bot bot commented Aug 18, 2025

🦋 Changeset detected

Latest commit: 16a87e0

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 18, 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 Aug 19, 2025 1:55pm

@LauraBeatris LauraBeatris changed the title fix(clerk-js): Update server-side revalidation hooks for session status transition fix(clerk-js): Update server-side revalidation hooks for session status transition Aug 18, 2025
@LauraBeatris LauraBeatris marked this pull request as ready for review August 18, 2025 21:16
@LauraBeatris LauraBeatris force-pushed the laura/update-nextjs-status-transition-hooks branch from ca18c17 to 3c78bae Compare August 18, 2025 21:17
@LauraBeatris
Copy link
Member Author

!snapshot

@LauraBeatris LauraBeatris force-pushed the laura/update-nextjs-status-transition-hooks branch from 3c78bae to 58ccb45 Compare August 18, 2025 21:18
Copy link
Contributor

coderabbitai bot commented Aug 18, 2025

📝 Walkthrough

Walkthrough

  • Adds a patch-level changeset entry for @clerk/clerk-js documenting a fix for server-side cache revalidation in Next.js when a session transitions from active to pending; the changeset file contains no runtime code changes.
  • Updates packages/clerk-js/src/core/clerk.ts: Clerk.signOut and Clerk.updateClient no longer retrieve or await an onBeforeSetActive hook; they now directly invoke onAfterSetActive (sourced from window.__unstable__onAfterSetActive when present).
  • Updates packages/clerk-js/src/core/tests/clerk.test.ts: removed assertions that onBeforeSetActive was called and removed invocation-order checks; tests now assert onAfterSetActive behavior.
  • Updates UI components packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx and CreateOrganizationScreen.tsx to use the app router: they import useRouter, obtain navigate, and replace setActive calls that previously passed redirectUrl: string with navigate: async () => { await navigate(redirectUrlComplete); } callbacks (with a TODO to handle next tasks).
  • The diff introduces a public-usage change where setActive is now invoked with a navigate callback instead of a redirectUrl string in at least one UI file.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 3f2207f and 16a87e0.

📒 Files selected for processing (2)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
⏰ 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

🪧 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 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

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.

@clerk-cookie
Copy link
Collaborator

Hey @LauraBeatris - the snapshot version command generated the following package versions:

Package Version
@clerk/agent-toolkit 0.1.24-snapshot.v20250818211845
@clerk/astro 2.11.5-snapshot.v20250818211845
@clerk/backend 2.9.3-snapshot.v20250818211845
@clerk/chrome-extension 2.5.23-snapshot.v20250818211845
@clerk/clerk-js 5.87.0-snapshot.v20250818211845
@clerk/elements 0.23.56-snapshot.v20250818211845
@clerk/clerk-expo 2.14.22-snapshot.v20250818211845
@clerk/expo-passkeys 0.3.33-snapshot.v20250818211845
@clerk/express 1.7.23-snapshot.v20250818211845
@clerk/fastify 2.4.23-snapshot.v20250818211845
@clerk/localizations 3.21.4-snapshot.v20250818211845
@clerk/nextjs 6.31.3-snapshot.v20250818211845
@clerk/nuxt 1.8.9-snapshot.v20250818211845
@clerk/clerk-react 5.43.0-snapshot.v20250818211845
@clerk/react-router 1.9.3-snapshot.v20250818211845
@clerk/remix 4.11.3-snapshot.v20250818211845
@clerk/shared 3.21.2-snapshot.v20250818211845
@clerk/tanstack-react-start 0.22.3-snapshot.v20250818211845
@clerk/testing 1.11.2-snapshot.v20250818211845
@clerk/themes 2.4.12-snapshot.v20250818211845
@clerk/types 4.80.0-snapshot.v20250818211845
@clerk/vue 1.11.3-snapshot.v20250818211845

Tip: Use the snippet copy button below to quickly install the required packages.
@clerk/agent-toolkit

npm i @clerk/agent-toolkit@0.1.24-snapshot.v20250818211845 --save-exact

@clerk/astro

npm i @clerk/astro@2.11.5-snapshot.v20250818211845 --save-exact

@clerk/backend

npm i @clerk/backend@2.9.3-snapshot.v20250818211845 --save-exact

@clerk/chrome-extension

npm i @clerk/chrome-extension@2.5.23-snapshot.v20250818211845 --save-exact

@clerk/clerk-js

npm i @clerk/clerk-js@5.87.0-snapshot.v20250818211845 --save-exact

@clerk/elements

npm i @clerk/elements@0.23.56-snapshot.v20250818211845 --save-exact

@clerk/clerk-expo

npm i @clerk/clerk-expo@2.14.22-snapshot.v20250818211845 --save-exact

@clerk/expo-passkeys

npm i @clerk/expo-passkeys@0.3.33-snapshot.v20250818211845 --save-exact

@clerk/express

npm i @clerk/express@1.7.23-snapshot.v20250818211845 --save-exact

@clerk/fastify

npm i @clerk/fastify@2.4.23-snapshot.v20250818211845 --save-exact

@clerk/localizations

npm i @clerk/localizations@3.21.4-snapshot.v20250818211845 --save-exact

@clerk/nextjs

npm i @clerk/nextjs@6.31.3-snapshot.v20250818211845 --save-exact

@clerk/nuxt

npm i @clerk/nuxt@1.8.9-snapshot.v20250818211845 --save-exact

@clerk/clerk-react

npm i @clerk/clerk-react@5.43.0-snapshot.v20250818211845 --save-exact

@clerk/react-router

npm i @clerk/react-router@1.9.3-snapshot.v20250818211845 --save-exact

@clerk/remix

npm i @clerk/remix@4.11.3-snapshot.v20250818211845 --save-exact

@clerk/shared

npm i @clerk/shared@3.21.2-snapshot.v20250818211845 --save-exact

@clerk/tanstack-react-start

npm i @clerk/tanstack-react-start@0.22.3-snapshot.v20250818211845 --save-exact

@clerk/testing

npm i @clerk/testing@1.11.2-snapshot.v20250818211845 --save-exact

@clerk/themes

npm i @clerk/themes@2.4.12-snapshot.v20250818211845 --save-exact

@clerk/types

npm i @clerk/types@4.80.0-snapshot.v20250818211845 --save-exact

@clerk/vue

npm i @clerk/vue@1.11.3-snapshot.v20250818211845 --save-exact

Copy link

pkg-pr-new bot commented Aug 18, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6572

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6572

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6572

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6572

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6572

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6572

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6572

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6572

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6572

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6572

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6572

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6572

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6572

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6572

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6572

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6572

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6572

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6572

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6572

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6572

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6572

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6572

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6572

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6572

commit: 16a87e0

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

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

2294-2304: Avoid unhandled promise rejections when firing onAfterSetActive during active→pending transition

The fire-and-forget invocation can surface unhandled promise rejections if the hook rejects. Wrap with Promise.resolve().catch(...) to log (or swallow) errors without blocking.

Apply this diff:

-        // Execute hooks to update server authentication context and trigger
-        // page protections in clerkMiddleware or server components
-        void onAfterSetActive();
+        // Execute hooks to update server authentication context and trigger
+        // page protections in clerkMiddleware or server components
+        void Promise.resolve(onAfterSetActive()).catch(err => {
+          debugLogger.error(
+            'onAfterSetActive() failed during active→pending transition',
+            { error: err },
+            'clerk',
+          );
+        });

Follow-up:

  • Consider adding an integration test asserting that:
    • onBeforeSetActive is not called for pending sessions.
    • onAfterSetActive is invoked exactly once on active→pending transitions via updateClient().

I can sketch a minimal Jest test that stubs window.__unstable__onBeforeSetActive/__unstable__onAfterSetActive and exercises setActive/updateClient if helpful.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 bcb905b and 58ccb45.

📒 Files selected for processing (2)
  • .changeset/plain-candies-fly.md (1 hunks)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/plain-candies-fly.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
**/*.{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/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • 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/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/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/core/clerk.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
⏰ 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). (22)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Static analysis
🔇 Additional comments (1)
.changeset/plain-candies-fly.md (1)

1-5: LGTM: concise and accurate changeset

Patch bump and description clearly communicate the behavioral fix for Next.js active→pending transitions.

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

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

2294-2304: Avoid unhandled promise rejections when firing onAfterSetActive non-blocking

Calling the hook with void onAfterSetActive() makes it fire-and-forget, but any rejection will surface as an unhandled promise rejection. Wrap it to swallow/log errors without blocking.

Apply this diff:

-        void onAfterSetActive();
+        // Fire-and-forget, but avoid unhandled rejections
+        void Promise.resolve(onAfterSetActive()).catch(error => {
+          debugLogger.warn('onAfterSetActive() hook rejected during active→pending transition', { error }, 'clerk');
+        });
.changeset/plain-candies-fly.md (1)

5-5: Clarify the release note to capture the Vercel rewrite context and the exact hook change

Helpful for consumers scanning the changelog to understand why this matters and what changed internally.

Apply this diff:

-Fix server-side cache revalidation for Next.js when transitioning from `active` to `pending` session
+Fix server-side cache revalidation in Next.js apps (notably on Vercel) when the session transitions from `active` to `pending`. We now trigger the server revalidation hook (`onAfterSetActive`) in a non-blocking way during client updates to avoid Vercel 405 rewrite issues.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 bcb905b and 58ccb45.

📒 Files selected for processing (2)
  • .changeset/plain-candies-fly.md (1 hunks)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/plain-candies-fly.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
**/*.{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/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • 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/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/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/core/clerk.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
⏰ 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: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
🔇 Additional comments (1)
packages/clerk-js/src/core/clerk.ts (1)

2294-2304: Good call to trigger server-side revalidation on active→pending without blocking

Non-blocking invocation here sidesteps the Vercel 405 rewrite issue while still nudging SSR protections and cache revalidation paths. The transition check is tight and scoped.

Comment on lines 2294 to 2304
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());
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.

💡 Verification agent

🧩 Analysis chain

Please add a regression test to cover the active→pending transition path

This behavior is critical for Next.js SSR protections. Add tests to assert:

  • updateClient triggers the onAfterSetActive hook exactly once when session transitions active→pending.
  • No hook call when status remains active or becomes active→active/pending→pending.
  • Hook is invoked non-blocking (no await).

You can search for other hook usages that might still be awaited (potentially causing similar issues) with this script:


🏁 Script executed:

#!/bin/bash
# Find direct uses of these hooks and how they are called
rg -n -C3 "__unstable__on(Before|After)SetActive|onBeforeSetActive|onAfterSetActive"
# Specifically look for awaited invocations of onAfterSetActive
rg -n -C2 -P '\bawait\s+onAfterSetActive\s*\('
# And fire-and-forget patterns
rg -n -C2 -P 'void\s+onAfterSetActive\s*\(|Promise\.resolve\s*\(\s*onAfterSetActive\s*\('

Length of output: 25498


Add regression tests for updateClient active→pending transition and review other hook usages

Please add a regression test in packages/clerk-js/src/core/__tests__/clerk.test.ts to cover the active→pending transition in updateClient:

  • Verify that onAfterSetActive is called exactly once when session.status changes from "active" to "pending".
  • Verify that no hook is called when the status remains "active" or transitions "pending""pending".
  • Verify that updateClient does not await the hook (i.e. it resolves before the hook’s returned promise).

Additionally, I spotted two awaited invocations of onAfterSetActive in packages/clerk-js/src/core/clerk.ts (around lines 532 and 1395). Please review those code paths to confirm whether they’re intentionally blocking or should also use a fire-and-forget pattern, and add tests or refactor as needed.

🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts around lines 2294–2304, add regression
tests in packages/clerk-js/src/core/__tests__/clerk.test.ts to cover the
updateClient active→pending transition: create a test that sets
window.__unstable__onAfterSetActive to a jest mock that returns a Promise and
assert it is called exactly once when session.status changes from "active" to
"pending", assert no hook is called when status stays "active" or transitions
"pending"→"pending", and assert updateClient does not await the hook by
resolving before the hook's promise settles (use a controllable promise and
check updateClient resolved prior to its resolution). Also review and adjust the
other two usages of onAfterSetActive in packages/clerk-js/src/core/clerk.ts
(around lines ~532 and ~1395): inspect whether they intentionally await the
hook; if they should be non-blocking, change those awaits to fire-and-forget
(call the hook without awaiting and handle errors via .catch logging) and add
tests demonstrating non-blocking behavior for those code paths.

@@ -119,7 +121,10 @@ const MembershipPreview = (props: { organization: OrganizationResource }) => {
try {
await setActive({
organization,
redirectUrl: redirectUrlComplete,
navigate: async () => {
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a small fix - atm the warnMissingPendingTaskHandlers utility is logging a warning when TaskChooseOrganization executes setActive with a pending session, but without using navigate

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/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

28-28: Adopted app-router navigation hook — LGTM and resolves the prior warning

Importing useRouter here aligns with the new post-activation navigation flow and should stop warnMissingPendingTaskHandlers for pending sessions.

🧹 Nitpick comments (2)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

124-127: Guard navigation target and replace TODO with a tracked follow-up

  • Add a null/empty guard for redirectUrlComplete to avoid invoking navigate with an undefined/empty value.
  • Replace bare TODO with a tracked follow-up reference (e.g., TODO(#issue-id)) to avoid lingering comments.
  • Minor duplication with CreateOrganizationScreen: consider extracting a small helper to build the post-activation navigate callback.

Apply this minimal guard within the callback:

-          navigate: async () => {
-            // TODO - Handle next tasks
-            await navigate(redirectUrlComplete);
-          },
+          navigate: async () => {
+            // TODO(#follow-up): Handle next tasks
+            if (redirectUrlComplete) {
+              await navigate(redirectUrlComplete);
+            }
+          },

Optional follow-up (outside this hunk): factor a shared helper to avoid duplication across screens, e.g., buildPostActivationNavigate(navigate, redirectUrlComplete).

packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (1)

52-55: Harden navigate callback and align with the other screen

Mirror the same guard and tracked TODO as suggested in ChooseOrganizationScreen to keep behavior consistent and avoid navigating to an undefined target.

-        navigate: async () => {
-          // TODO - Handle next tasks
-          await navigate(redirectUrlComplete);
-        },
+        navigate: async () => {
+          // TODO(#follow-up): Handle next tasks
+          if (redirectUrlComplete) {
+            await navigate(redirectUrlComplete);
+          }
+        },

Consider extracting a shared helper for this callback to prevent duplication and ensure any future changes (e.g., handling “next tasks”) stay in sync across both screens.

Also, if there are no tests covering the new navigate path in setActive, consider adding a lightweight test that:

  • Mocks useRouter().navigate
  • Asserts setActive receives a navigate function and that it’s invoked when setActive resolves
    This will protect against regressions when iterating on the TODO.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 fbe8b0e and 3f2207f.

📒 Files selected for processing (5)
  • .changeset/plain-candies-fly.md (1 hunks)
  • packages/clerk-js/src/core/__tests__/clerk.test.ts (0 hunks)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (3 hunks)
💤 Files with no reviewable changes (1)
  • packages/clerk-js/src/core/tests/clerk.test.ts
✅ Files skipped from review due to trivial changes (1)
  • .changeset/plain-candies-fly.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/core/clerk.ts
🧰 Additional context used
📓 Path-based instructions (10)
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/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
**/*.{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/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.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/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
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/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.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
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/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.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/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.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/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.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/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
**/*

⚙️ 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/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
⏰ 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). (25)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

110-110: useRouter usage looks correct

Destructuring navigate from the router is appropriate for passing into setActive’s navigate callback.

packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (2)

10-10: Importing useRouter to support app-router navigation — LGTM

Matches the updated activation flow and keeps navigation within our router abstraction.


23-23: Destructuring navigate — LGTM

Consistent with the ChooseOrganizationScreen usage.

@LauraBeatris LauraBeatris merged commit 81b2759 into main Aug 19, 2025
63 of 64 checks passed
@LauraBeatris LauraBeatris deleted the laura/update-nextjs-status-transition-hooks branch August 19, 2025 14:27
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