Skip to content

fix(nextjs): Keyless environment drift telemetry event works client-side and only in dev mode #6539

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

Conversation

heatlikeheatwave
Copy link
Contributor

@heatlikeheatwave heatlikeheatwave commented Aug 13, 2025

Description

  • Updated implementation of detectKeylessEnvDrift to function when <ClerkProvider /> is implemented in client component.
  • Added canUseKeyless check to detectKeylessEnvDrift to prevent telemetry event from running for production applications.
  • Moved options.telemetry spread in createClerkClient to enable override of the samplingRate property

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

Here are the updated release notes:

  • New Features

    • Added a telemetry sampling rate option to the Clerk client, allowing for more granular control over telemetry data collection.
  • Bug Fixes

    • Improved environment drift detection to ensure it only runs for development apps and supports client-side components.
  • Chores

    • Patch release to address the changes above.

Copy link

changeset-bot bot commented Aug 13, 2025

🦋 Changeset detected

Latest commit: e1d6823

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

This PR includes changesets to release 1 package
Name Type
@clerk/nextjs 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 13, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Preview Comment Aug 14, 2025 8:53pm

@heatlikeheatwave heatlikeheatwave changed the title fix(nextjs): Update environment drift telemetry event to work in client components and only apply to development instances fix(nextjs): Keyless environment drift telemetry event works client-side and only in dev mode Aug 13, 2025
Copy link

pkg-pr-new bot commented Aug 13, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: e1d6823

Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

📝 Walkthrough

Walkthrough

Adds client-side keyless drift detection: NextClientClerkProvider mounts and calls a new exported async action detectKeylessEnvDriftAction (app-router) which dynamically imports and invokes server detectKeylessEnvDrift and ignores errors. Server detectKeylessEnvDrift is gated by canUseKeyless and constructs a Clerk client for telemetry with samplingRate set. A changeset bumps a patch for @clerk/nextjs. Public API changes: createClerkClient signature now accepts telemetry samplingRate and ClerkOptions.telemetry type is extended to include samplingRate.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Suggested reviewers

  • panteliselef
  • brkalow

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.


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

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)
.changeset/fine-weeks-give.md (1)

5-6: Remove trailing stray character from the changeset body.

There's an extra "6" at the end of the file body that will show up in release notes.

Apply this diff:

-Updated implementation of detectKeylessEnvDrift to function when <ClerkProvider /> is implemented in client components. Added canUseKeyless check to detectKeylessEnvDrift to prevent telemetry event from running for production applications.
-6
+Updated implementation of detectKeylessEnvDrift to function when <ClerkProvider /> is implemented in client components. Added canUseKeyless check to detectKeylessEnvDrift to prevent telemetry event from running for production applications.
packages/nextjs/src/app-router/client/ClerkProvider.tsx (1)

18-18: Import looks correct and tree-shake friendly.

Importing the action from the server module is consistent with how Server Actions are consumed from Client Components in Next.js. See follow-up comment about guarding the call to avoid unnecessary RPCs in production.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15fe106 and 0c126e5.

📒 Files selected for processing (4)
  • .changeset/fine-weeks-give.md (1 hunks)
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx (2 hunks)
  • packages/nextjs/src/app-router/keyless-actions.ts (1 hunks)
  • packages/nextjs/src/server/keyless-telemetry.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/fine-weeks-give.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/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.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/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.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/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.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/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.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/nextjs/src/app-router/keyless-actions.ts
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/client/ClerkProvider.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/nextjs/src/app-router/client/ClerkProvider.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/nextjs/src/app-router/client/ClerkProvider.tsx
🧬 Code Graph Analysis (3)
packages/nextjs/src/app-router/keyless-actions.ts (1)
packages/nextjs/src/server/keyless-telemetry.ts (1)
  • detectKeylessEnvDrift (89-188)
packages/nextjs/src/server/keyless-telemetry.ts (1)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/nextjs/src/app-router/client/ClerkProvider.tsx (2)
packages/clerk-js/src/ui/Components.tsx (1)
  • useSafeLayoutEffect (54-54)
packages/nextjs/src/app-router/keyless-actions.ts (1)
  • detectKeylessEnvDriftAction (97-104)
🪛 Biome (2.1.2)
packages/nextjs/src/app-router/client/ClerkProvider.tsx

[error] 60-60: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)

⏰ 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). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/nextjs/src/server/keyless-telemetry.ts (2)

5-5: Feature-flag gating import is correct and localized.

Importing canUseKeyless here keeps the responsibility server-side and avoids leaking telemetry in production.


90-92: Early return on feature flag prevents production telemetry.

This aligns with the PR goal and minimizes overhead before any I/O or dynamic imports.

Please add or extend unit tests to cover:

  • detectKeylessEnvDrift returns early (no file reads, no telemetry) when canUseKeyless is false.
  • detectKeylessEnvDrift emits no event when there's no actual drift, and emits exactly once when drift exists (flag file prevents duplicates).

I can draft test scaffolding if you share the project’s preferred test runner and helpers in this package.

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)
.changeset/fine-weeks-give.md (1)

5-5: Polish wording for clarity and correct grammar (“on development” → “in development”).

Recommend a crisper, grammatically correct summary.

Apply this diff:

-Fix keyless drift logic to support client components and ensure only apps on development are included.
+Fix keyless drift telemetry to support client components and ensure it runs only in development environments.
📜 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 settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3adb99c and bf388af.

📒 Files selected for processing (1)
  • .changeset/fine-weeks-give.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/fine-weeks-give.md
🪛 LanguageTool
.changeset/fine-weeks-give.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...e only apps on development are included.

(QB_NEW_EN)

⏰ 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). (4)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
.changeset/fine-weeks-give.md (1)

1-4: Changeset is present and correctly scoped as a patch for @clerk/nextjs.

This aligns with the PR’s intent and adheres to our release process.

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 (5)
packages/backend/src/index.ts (5)

20-20: Public type extended with samplingRate — document it

Extending the public API is good, but please add JSDoc to explain the expected range (0..1), default (0.1), and behavior (overrides default sampling) to comply with the repo’s guideline “All public APIs must be documented with JSDoc.”

Suggested JSDoc (outside the selected lines, placed above the ClerkOptions export):

/**
 * Options for configuring the Clerk backend client.
 *
 * @public
 * @property telemetry Optional telemetry configuration.
 * @property telemetry.disabled If true, telemetry is not collected.
 * @property telemetry.debug If true, events are collected but only logged (not sent).
 * @property telemetry.samplingRate Sampling rate in [0..1]. Defaults to 0.1. Values outside the range are clamped.
 */

Also consider adding a short note in the package README or changelog about the new option.


34-39: Clamp and validate samplingRate to [0..1] to avoid misconfiguration

To harden against out-of-range (or NaN) values, clamp the final sampling rate while preserving the override semantics. This also provides a single source of truth for the default.

Apply this refactor:

   const telemetry = new TelemetryCollector({
     publishableKey: opts.publishableKey,
     secretKey: opts.secretKey,
-    samplingRate: 0.1,
     ...(opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}),
-    ...options.telemetry,
+    ...(opts.telemetry ?? {}),
+    // Final authority: clamp to [0..1] and default to 0.1
+    samplingRate:
+      typeof opts.telemetry?.samplingRate === 'number' && Number.isFinite(opts.telemetry.samplingRate)
+        ? Math.max(0, Math.min(1, opts.telemetry.samplingRate))
+        : 0.1,
   });

Optionally log a warning if clamping occurs to aid debugging.


20-20: Consider including perEventSampling in the public telemetry options in a follow-up

Not a blocker, but exposing perEventSampling (already supported by TelemetryCollectorOptions) could be useful for advanced consumers and aligns with existing telemetry capabilities.

If you decide to do this later, update the type as:

-  > & { sdkMetadata?: SDKMetadata; telemetry?: Pick<TelemetryCollectorOptions, 'disabled' | 'debug' | 'samplingRate'> };
+  > & {
+      sdkMetadata?: SDKMetadata;
+      telemetry?: Pick<TelemetryCollectorOptions, 'disabled' | 'debug' | 'samplingRate' | 'perEventSampling'>;
+    };

29-46: Add tests to lock in behavior and prevent regressions

Given the public API change and the critical spread fix, add a couple of focused tests:

  • createClerkClient() without telemetry does not throw and uses default samplingRate 0.1
  • createClerkClient({ telemetry: { samplingRate: 1 } }) results in samplingRate 1 in the TelemetryCollector
  • Out-of-range samplingRate (e.g., 2 or -1) is clamped to [0..1] if you adopt the clamping refactor

I can draft these tests in the appropriate package if you point me to the existing test harness for packages/backend.


33-39: Optional: keep usage consistent (opts vs options)

Minor consistency nit: the rest of the function uses opts. Prefer opts.telemetry over options.telemetry for coherence.

If you didn’t apply the clamping refactor above, at least make this change:

-    ...options.telemetry,
+    ...(opts.telemetry ?? {}),
📜 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 settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bf388af and ca64a2b.

📒 Files selected for processing (3)
  • .changeset/fine-weeks-give.md (1 hunks)
  • packages/backend/src/index.ts (2 hunks)
  • packages/nextjs/src/server/keyless-telemetry.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .changeset/fine-weeks-give.md
  • packages/nextjs/src/server/keyless-telemetry.ts
🧰 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/backend/src/index.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/backend/src/index.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/index.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/index.ts
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/backend/src/index.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/backend/src/index.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/backend/src/index.ts
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/backend/src/index.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/backend/src/index.ts
🧬 Code Graph Analysis (1)
packages/backend/src/index.ts (2)
packages/types/src/clerk.ts (1)
  • SDKMetadata (105-118)
packages/shared/src/telemetry/types.ts (1)
  • TelemetryCollectorOptions (1-44)
⏰ 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 (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • 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: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/backend/src/index.ts (2)

34-39: Order change correctly enables overriding samplingRate

Moving the telemetry spread after the defaults achieves the stated goal of allowing consumers to override the default sampling rate. This aligns with the PR objective.


33-39: TelemetryCollector correctly honors provided samplingRate
TelemetryCollector’s constructor uses options.samplingRate ?? DEFAULT_CONFIG.samplingRate, so the explicit samplingRate: 0.1 is preserved (and only changed if options.telemetry itself includes a different samplingRate). No changes required.

@heatlikeheatwave heatlikeheatwave force-pushed the heat/grow-672-convert-drift-detection-to-a-server-action branch from 1a6bc42 to e1d6823 Compare August 14, 2025 20:51
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/nextjs/src/app-router/keyless-actions.ts (1)

97-108: Add explicit return type, type the caught error, and log in dev (don’t swallow silently).

Exported server actions must declare an explicit return type. Also, prefer unknown for caught errors and emit a dev-only log to aid debugging while keeping prod quiet.

Apply this diff:

-export async function detectKeylessEnvDriftAction() {
+export async function detectKeylessEnvDriftAction(): Promise<void> {
   if (!canUseKeyless) {
     return;
   }

   try {
     const { detectKeylessEnvDrift } = await import('../server/keyless-telemetry.js');
     await detectKeylessEnvDrift();
-  } catch {
-    // ignore
+  } catch (err: unknown) {
+    if (process.env.NODE_ENV !== 'production') {
+      // Helps diagnose in dev without polluting prod logs
+      // eslint-disable-next-line no-console
+      console.warn('detectKeylessEnvDriftAction failed:', err);
+    }
   }
 }
🧹 Nitpick comments (2)
packages/nextjs/src/app-router/keyless-actions.ts (2)

96-97: Document this exported action with JSDoc.

Per repo guidelines, public APIs should be documented. Add a concise JSDoc describing behavior, environment constraints, and side effects.

+
+/**
+ * Triggers keyless environment drift detection as a Next.js Server Action.
+ * No-ops when keyless is disabled (e.g., production).
+ * Safe to call from client components; errors are ignored in production and logged in development.
+ * @returns Promise<void>
+ */
 export async function detectKeylessEnvDriftAction(): Promise<void> {

97-108: Add basic tests for gating and error handling.

Suggest adding tests to cover:

  • Early return when canUseKeyless is false (no import attempted).
  • Happy path: calls detectKeylessEnvDrift when enabled.
  • Error path in dev: error is logged; in prod: error is swallowed without logging.

I can help scaffold these with mocks for canUseKeyless and the dynamic import.

📜 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 settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ca64a2b and e1d6823.

📒 Files selected for processing (5)
  • .changeset/fine-weeks-give.md (1 hunks)
  • packages/backend/src/index.ts (2 hunks)
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx (2 hunks)
  • packages/nextjs/src/app-router/keyless-actions.ts (1 hunks)
  • packages/nextjs/src/server/keyless-telemetry.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • .changeset/fine-weeks-give.md
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/backend/src/index.ts
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/nextjs/src/app-router/keyless-actions.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/nextjs/src/app-router/keyless-actions.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/nextjs/src/app-router/keyless-actions.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/nextjs/src/app-router/keyless-actions.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/nextjs/src/app-router/keyless-actions.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/nextjs/src/app-router/keyless-actions.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/nextjs/src/app-router/keyless-actions.ts
🧬 Code Graph Analysis (1)
packages/nextjs/src/app-router/keyless-actions.ts (2)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/nextjs/src/server/keyless-telemetry.ts (1)
  • detectKeylessEnvDrift (89-191)
⏰ 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 (billing, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Static analysis
🔇 Additional comments (1)
packages/nextjs/src/app-router/keyless-actions.ts (1)

98-100: Good early-return gate with canUseKeyless.

Prevents unnecessary dynamic import and avoids running telemetry in production.

@heatlikeheatwave heatlikeheatwave merged commit 17def2b into main Aug 15, 2025
39 checks passed
@heatlikeheatwave heatlikeheatwave deleted the heat/grow-672-convert-drift-detection-to-a-server-action branch August 15, 2025 14:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants