Skip to content

chore(nextjs, shared) adjust telemetry sampling for keyless #6488

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

Closed
wants to merge 6 commits into from

Conversation

mwickett
Copy link
Member

@mwickett mwickett commented Aug 7, 2025

Description

This adds a sampling rate override for telemetry on keyless applications to help us better troubleshoot keyless issues. It creates a global keyless flag which is then used to override the sample rate for the COMPONENT_MOUNTED event.

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: Telemetry adjustment

Summary by CodeRabbit

  • New Features
    • Improved telemetry handling for keyless mode in Next.js, including enhanced event sampling and tracking via a new telemetry enhancer component.
    • Telemetry events now include a keyless flag when applicable for better analytics.
  • Bug Fixes
    • Ensured correct sampling rates for telemetry events in keyless environments.
  • Tests
    • Added comprehensive tests for keyless telemetry behavior and event payloads.
  • Chores
    • Updated global type definitions to support keyless mode detection.
    • Added documentation for patch-level updates related to telemetry.

Copy link

changeset-bot bot commented Aug 7, 2025

🦋 Changeset detected

Latest commit: 1a19920

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

This PR includes changesets to release 19 packages
Name Type
@clerk/nextjs Patch
@clerk/shared Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue 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 7, 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 7, 2025 7:39pm

Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

📝 Walkthrough

Walkthrough

This change set introduces support for enhanced telemetry handling in keyless mode for a Next.js and Clerk integration. It adds a global flag __clerk_keyless to the browser's window object when running in keyless mode, and updates the telemetry event payloads to include a keyless property when this mode is active. A new NextJSTelemetryCollector class is implemented to boost the sampling rate of component-mounted events to 100% in keyless mode. A KeylessTelemetryEnhancer React component is introduced to wrap and restore the telemetry collector as needed. Multiple test suites are added or updated to verify the correct behavior of telemetry collection and keyless mode detection. Changeset and type declaration updates are also included.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Complexity: Moderate. The changes span multiple files and introduce new components, classes, and test suites, as well as updates to function signatures and type declarations. The logic for telemetry enhancement and keyless detection is non-trivial but localized.
  • Estimated review time: Approximately 20 minutes, considering the need to verify new telemetry logic, component integration, and comprehensive test coverage.

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

🧹 Nitpick comments (6)
.changeset/sad-pianos-pull.md (1)

1-7: LGTM! Consider more descriptive changeset message.

The changeset format is correct and properly identifies the affected packages with patch versions. The description could be more specific about the telemetry sampling rate override for keyless applications to better document the change.

packages/nextjs/src/app-router/client/ClerkProvider.tsx (1)

46-51: Consider type-safe approach for global flag setting.

The logic is correct, but using (window as any) bypasses TypeScript's type safety. Consider defining a proper interface extension or using a more type-safe approach.

Apply this diff to improve type safety:

+declare global {
+  interface Window {
+    __clerk_keyless?: boolean;
+  }
+}
+
 // Set global keyless flag for telemetry boosting
 useEffect(() => {
   if (canUseKeyless && typeof window !== 'undefined') {
-    (window as any).__clerk_keyless = true;
+    window.__clerk_keyless = true;
   }
 }, []);
packages/shared/src/telemetry/collector.ts (1)

289-289: Improve type safety consistency.

The keyless detection logic is correct, but consider using the same type-safe approach across the codebase instead of (window as any).

If you implement the global interface extension suggested in ClerkProvider.tsx, you can improve this line:

-const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true;
+const isKeyless = typeof window !== 'undefined' && window.__clerk_keyless === true;
packages/shared/src/telemetry/events/component-mounted.ts (3)

27-29: Consider extracting keyless detection logic.

The keyless detection and sampling rate calculation logic is duplicated between this function and eventComponentMounted. Consider extracting it to a utility function for better maintainability.

+function getEffectiveSamplingRate(samplingRateOverride?: number): number {
+  const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true;
+  return samplingRateOverride ?? (isKeyless ? 1.0 : EVENT_SAMPLING_RATE);
+}
+
 function createPrebuiltComponentEvent(event: typeof EVENT_COMPONENT_MOUNTED | typeof EVENT_COMPONENT_OPENED) {
   return function (
     component: string,
     props?: Record<string, any>,
     additionalPayload?: TelemetryEventRaw['payload'],
     samplingRateOverride?: number,
   ): TelemetryEventRaw<EventPrebuiltComponent> {
-    // Check for keyless mode and boost sampling rate if no override provided
-    const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true;
-    const effectiveSamplingRate = samplingRateOverride ?? (isKeyless ? 1.0 : EVENT_SAMPLING_RATE);
+    const effectiveSamplingRate = getEffectiveSamplingRate(samplingRateOverride);

113-115: Code duplication: Same keyless detection logic.

This is the same keyless detection logic as in createPrebuiltComponentEvent. The earlier suggestion to extract this to a utility function would eliminate this duplication.

Apply the same refactor here:

-  // Check for keyless mode and boost sampling rate if no override provided
-  const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true;
-  const effectiveSamplingRate = samplingRateOverride ?? (isKeyless ? 1.0 : EVENT_SAMPLING_RATE);
+  const effectiveSamplingRate = getEffectiveSamplingRate(samplingRateOverride);

28-28: Consider improving type safety for global window property.

The (window as any).__clerk_keyless access could be more type-safe. Consider adding a type declaration for the global property.

You could add a type declaration at the top of the file or in a types file:

declare global {
  interface Window {
    __clerk_keyless?: boolean;
  }
}

Then use:

-const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true;
+const isKeyless = typeof window !== 'undefined' && window.__clerk_keyless === true;

Also applies to: 114-114

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f318d22 and 335c889.

📒 Files selected for processing (7)
  • .changeset/sad-pianos-pull.md (1 hunks)
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx (1 hunks)
  • packages/nextjs/src/types.ts (1 hunks)
  • packages/shared/src/__tests__/component-mounted.test.ts (1 hunks)
  • packages/shared/src/__tests__/telemetry.test.ts (1 hunks)
  • packages/shared/src/telemetry/collector.ts (2 hunks)
  • packages/shared/src/telemetry/events/component-mounted.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.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/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/nextjs/src/app-router/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.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/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.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/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.ts
**/*.{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
**/*.{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/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.ts
**/*.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
**/*

⚙️ 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/client/ClerkProvider.tsx
  • packages/shared/src/telemetry/collector.ts
  • packages/shared/src/__tests__/telemetry.test.ts
  • packages/nextjs/src/types.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/sad-pianos-pull.md
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/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/component-mounted.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/shared/src/__tests__/telemetry.test.ts
  • packages/shared/src/__tests__/component-mounted.test.ts
🧬 Code Graph Analysis (3)
packages/nextjs/src/app-router/client/ClerkProvider.tsx (2)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/shared/src/telemetry/collector.ts (1)
  • window (179-213)
packages/nextjs/src/types.ts (1)
packages/types/src/utils.ts (1)
  • Without (105-107)
packages/shared/src/telemetry/events/component-mounted.ts (1)
packages/types/src/telemetry.ts (1)
  • TelemetryEventRaw (40-44)
🪛 ESLint
packages/shared/src/__tests__/component-mounted.test.ts

[error] 1-1: 'TelemetryEventRaw' is defined but never used. Allowed unused vars must match /^_/u.

(@typescript-eslint/no-unused-vars)


[error] 1-1: 'TelemetryEventRaw' is defined but never used.

(unused-imports/no-unused-imports)

⏰ 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). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
packages/shared/src/telemetry/collector.ts (1)

299-299: LGTM! Efficient conditional property inclusion.

The conditional spreading approach is clean and efficiently adds the keyless flag only when needed.

packages/nextjs/src/types.ts (1)

4-21: LGTM! Well-structured type definition.

The type definition properly excludes the original telemetry property and redefines it with Next.js-specific options. The JSDoc documentation clearly explains the purpose and behavior. The union type with false or an object with optional disabled/debug properties provides good flexibility.

packages/shared/src/__tests__/telemetry.test.ts (1)

321-402: LGTM! Comprehensive test coverage for keyless mode detection.

The test suite thoroughly covers all scenarios:

  • Keyless flag present and true
  • Keyless flag absent or false
  • Server environment (no window object)

The test structure is well-organized with proper setup/cleanup, and the mocking approach correctly simulates different environments. The use of debug mode to verify payload contents is a smart testing strategy.

packages/shared/src/__tests__/component-mounted.test.ts (3)

10-13: LGTM!

Good test cleanup pattern to ensure isolation between tests by removing any existing window mock.


15-61: Excellent test coverage for keyless mode detection.

The test suite comprehensively covers all scenarios:

  • Default behavior when not in keyless mode
  • Sampling rate boost in keyless mode
  • Explicit override precedence
  • Server environment handling
  • Invalid flag type handling

134-179: Comprehensive payload structure validation.

The tests properly verify:

  • Appearance property tracking with boolean flags
  • Handling of both present and absent appearance properties
  • Additional payload data inclusion
packages/shared/src/telemetry/events/component-mounted.ts (1)

25-26: LGTM! Consistent function signature updates.

The addition of the optional samplingRateOverride parameter is consistent across all functions and maintains backward compatibility. JSDoc comments are properly updated.

Also applies to: 52-52, 61-61, 77-77, 86-86, 103-103, 111-111

Copy link

pkg-pr-new bot commented Aug 7, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 1a19920

- Added `KeylessTelemetryEnhancer` component to boost telemetry sampling rates in keyless mode.
- Introduced `NextJSTelemetryCollector` to manage telemetry events with keyless support.
- Updated global `Window` interface to include `__clerk_keyless` flag.
- Created tests for keyless telemetry integration, ensuring proper functionality and error handling.
- Refactored existing telemetry event functions to respect explicit sampling rate overrides.
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 335c889 and 1a19920.

📒 Files selected for processing (8)
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts (1 hunks)
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx (2 hunks)
  • packages/nextjs/src/app-router/client/keyless-creator-reader.tsx (1 hunks)
  • packages/nextjs/src/global.d.ts (1 hunks)
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx (1 hunks)
  • packages/nextjs/src/utils/telemetry-collector.ts (1 hunks)
  • packages/shared/src/__tests__/component-mounted.test.ts (1 hunks)
  • packages/shared/src/telemetry/events/component-mounted.ts (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/nextjs/src/global.d.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx
  • packages/shared/src/tests/component-mounted.test.ts
  • packages/shared/src/telemetry/events/component-mounted.ts
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.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/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.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/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.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/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.ts
**/*.{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/keyless-creator-reader.tsx
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.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/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.ts
**/*.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/keyless-creator-reader.tsx
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.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/client/keyless-creator-reader.tsx
  • packages/nextjs/src/__tests__/telemetry-collector.test.ts
  • packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
  • packages/nextjs/src/utils/telemetry-collector.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/nextjs/src/__tests__/telemetry-collector.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/nextjs/src/__tests__/telemetry-collector.test.ts
🪛 ESLint
packages/nextjs/src/__tests__/telemetry-collector.test.ts

[error] 70-70: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)

⏰ 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). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
packages/nextjs/src/__tests__/telemetry-collector.test.ts (2)

9-19: LGTM! Comprehensive interface verification.

The test properly verifies that the NextJSTelemetryCollector implements the expected telemetry collector interface with all required methods and properties.


21-47: Good error handling test with proper cleanup.

The test correctly simulates keyless mode, verifies the collector handles events without throwing, and properly cleans up the global flag.

packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx (3)

16-50: Excellent implementation of telemetry enhancement logic.

The component properly:

  • Detects keyless runtime using the global flag
  • Prevents double wrapping with instanceof checks
  • Includes cleanup for HMR support
  • Uses appropriate exit conditions

52-52: LGTM! Proper null rendering for utility component.

Returning null is appropriate for a utility component that only provides side effects without rendering UI.


37-38: Ensure PACKAGE_NAME and PACKAGE_VERSION are defined and imported

I searched the repo but didn’t find any exports for these constants. To prevent runtime errors, please:

  • Define PACKAGE_NAME and PACKAGE_VERSION (e.g. in a new constants.ts alongside your util).
  • Import them at the top of packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx, for example:
    'use client';
    
    import { useEffect } from 'react';
    import { useClerk } from '../client-boundary/hooks';
    import { canUseKeyless } from './feature-flags';
    import { NextJSTelemetryCollector } from './telemetry-collector';
    + import { PACKAGE_NAME, PACKAGE_VERSION } from './constants';
  • Adjust the import path if your constants live elsewhere.
packages/nextjs/src/utils/telemetry-collector.ts (3)

9-14: LGTM! Proper TypeScript class structure.

Excellent use of private fields, interface implementation, and clean constructor pattern.


16-22: LGTM! Clean delegation pattern.

The getters properly delegate to the internal collector, maintaining the interface contract.


24-39: Excellent sampling rate boosting logic with comprehensive edge case handling.

The implementation correctly:

  • Detects keyless mode via global flag
  • Identifies COMPONENT_MOUNTED events
  • Respects existing 100% sampling rates
  • Only boosts when sampling is undefined or below 1.0
  • Creates new event object to avoid mutation

The logic handles all the necessary edge cases and maintains immutability by creating a new event object when boosting is needed.

Comment on lines +49 to +84
test('boosts sampling for component-mounted events in keyless mode', () => {
(window as any).__clerk_keyless = true;

// Spy on underlying collector
const records: any[] = [];
vi.doMock('@clerk/shared/telemetry', async () => {
const actual = await vi.importActual<any>('@clerk/shared/telemetry');
return {
...actual,
TelemetryCollector: class {
isEnabled = true;
isDebug = false;
record(ev: any) {
records.push(ev);
}
},
};
});

// Re-require after mock
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { NextJSTelemetryCollector: Collector } = require('../utils/telemetry-collector');
const collector = new Collector({ publishableKey: 'pk_test_123' });

collector.record({ event: 'COMPONENT_MOUNTED', payload: { component: 'SignIn' } });
collector.record({ event: 'COMPONENT_MOUNTED', payload: { component: 'SignUp' }, eventSamplingRate: 0.1 });
collector.record({ event: 'OTHER_EVENT', payload: {} });

expect(records[0].eventSamplingRate).toBe(1);
expect(records[1].eventSamplingRate).toBe(1);
expect(records[2].eventSamplingRate).toBeUndefined();

delete (window as any).__clerk_keyless;
vi.resetModules();
});
});
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

Address ESLint violation while maintaining test functionality.

The test logic for verifying sampling rate boosting is sound, but the require() usage violates the ESLint rule. Since this is needed for dynamic re-importing after mocking, consider using dynamic import with proper typing.

-    // Re-require after mock
-    // eslint-disable-next-line @typescript-eslint/no-require-imports
-    const { NextJSTelemetryCollector: Collector } = require('../utils/telemetry-collector');
+    // Re-import after mock
+    const { NextJSTelemetryCollector: Collector } = await import('../utils/telemetry-collector');

You'll need to make the test function async and add await before the import statement to maintain the same functionality while adhering to ESLint rules.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 ESLint

[error] 70-70: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)

🤖 Prompt for AI Agents
In packages/nextjs/src/__tests__/telemetry-collector.test.ts between lines 49
and 84, the test uses a synchronous require() call which violates ESLint rules.
To fix this, convert the test function to async and replace the require() call
with an awaited dynamic import statement, ensuring proper typing is used. This
change maintains the test functionality while adhering to ESLint standards.

Comment on lines +13 to +15
if (typeof window !== 'undefined') {
(window as any).__clerk_keyless = true;
}
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

Improve type safety for global keyless flag.

Instead of using (window as any), leverage the declared Window interface property to maintain type safety.

-    if (typeof window !== 'undefined') {
-      (window as any).__clerk_keyless = true;
-    }
+    if (typeof window !== 'undefined') {
+      window.__clerk_keyless = true;
+    }

This assumes the property is properly declared in the global.d.ts file as mentioned in the AI summary.

📝 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
if (typeof window !== 'undefined') {
(window as any).__clerk_keyless = true;
}
if (typeof window !== 'undefined') {
window.__clerk_keyless = true;
}
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/client/keyless-creator-reader.tsx around lines
13 to 15, replace the use of (window as any).__clerk_keyless with a properly
typed property on the Window interface. First, ensure that the global.d.ts file
declares __clerk_keyless on the Window interface. Then, access
window.__clerk_keyless directly without casting to any to maintain type safety.

@mwickett mwickett marked this pull request as draft August 8, 2025 12:55
@mwickett mwickett closed this Aug 8, 2025
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.

2 participants