Skip to content

Conversation

@panteliselef
Copy link
Member

@panteliselef panteliselef commented Oct 31, 2025

This PR also prevents keylessDriftDetection from firing as an action when the RSC variant is used.

Description

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

  • New Features

    • Added configuration option to disable keyless drift detection in Clerk Provider
  • Improvements

    • Enhanced support for Next.js cacheComponents feature
    • Improved performance with optimized suspense handling and lazy loading of drift detection

This PR also prevents keylessDriftDetection from firing as an action when the RSC variant is used.
@changeset-bot
Copy link

changeset-bot bot commented Oct 31, 2025

🦋 Changeset detected

Latest commit: f6c4a1c

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

@panteliselef panteliselef self-assigned this Oct 31, 2025
@vercel
Copy link

vercel bot commented Oct 31, 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 Oct 31, 2025 8:32pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 31, 2025

Walkthrough

This pull request introduces drift detection for keyless authentication and adds Next.js cacheComponents support through conditional Suspense wrapping. Two new components (KeylessDriftDetector and SuspenseWhenCached) are added, the ClerkProvider is extended with drift detection controls, and telemetry flag handling is refactored to track per-public-key state.

Changes

Cohort / File(s) Summary
Changeset
.changeset/quiet-rockets-invite.md
Adds changeset documenting patch release with improved cacheComponents support for @clerk/nextjs.
Client-side Keyless Drift Detection
packages/nextjs/src/app-router/client/ClerkProvider.tsx, packages/nextjs/src/app-router/client/keyless-drift-detector.tsx
Introduces lazy-loaded KeylessDriftDetector component and new disableKeylessDriftDetection prop to ClientClerkProvider. Drift detection reads layout segments and conditionally triggers detectKeylessEnvDriftAction when keyless is enabled.
Server-side Provider Orchestration
packages/nextjs/src/app-router/server/ClerkProvider.tsx, packages/nextjs/src/app-router/server/keyless-provider.tsx
Adds server-side drift detection via onlyTry, wraps providers in SuspenseWhenCached to support cacheComponents, extends getKeylessStatus to return runningWithDriftedKeys state, and propagates disableKeylessDriftDetection flag.
Suspense Utility
packages/nextjs/src/app-router/suspense-when-cached.tsx
New utility component that conditionally wraps children in React Suspense based on Next.js cache flag, with optional noopWhen prop to disable wrapping.
Telemetry Refactoring
packages/nextjs/src/server/keyless-telemetry.ts
Refactors telemetry flag mechanism to track per-public-key state using template-based file paths, removes client-side guard from drift detection logic, and simplifies flag file content.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant NextApp as Next.js App
    participant ClerkServerProvider as Server ClerkProvider
    participant KeylessProvider as KeylessProvider
    participant SuspenseWhenCached as SuspenseWhenCached
    participant ClientClerkProvider as Client ClerkProvider
    participant KeylessDriftDetector as KeylessDriftDetector
    participant DriftDetection as Drift Detection Logic

    User->>NextApp: Request
    NextApp->>ClerkServerProvider: Render
    ClerkServerProvider->>KeylessProvider: Get keyless status
    KeylessProvider->>DriftDetection: Detect drifted keys
    DriftDetection-->>KeylessProvider: runningWithDriftedKeys
    
    rect rgb(240, 248, 255)
    note over SuspenseWhenCached: Conditional Suspense wrapping<br/>based on cacheComponents flag
    ClerkServerProvider->>SuspenseWhenCached: Wrap KeylessProvider
    SuspenseWhenCached->>SuspenseWhenCached: Check cache flag
    alt Cache enabled
        SuspenseWhenCached->>SuspenseWhenCached: Add Suspense boundary
    else Cache disabled or noopWhen=true
        SuspenseWhenCached->>SuspenseWhenCached: Skip Suspense
    end
    SuspenseWhenCached-->>ClerkServerProvider: Wrapped content
    end
    
    ClerkServerProvider->>ClientClerkProvider: Render with disableKeylessDriftDetection
    
    rect rgb(230, 245, 230)
    note over KeylessDriftDetector: Client-side lazy drift detection
    ClientClerkProvider->>KeylessDriftDetector: Mount (lazy-loaded)
    KeylessDriftDetector->>KeylessDriftDetector: Read layout segments
    KeylessDriftDetector->>KeylessDriftDetector: Check canUseKeyless flag
    alt Keyless enabled & not _not-found
        KeylessDriftDetector->>DriftDetection: Trigger detectKeylessEnvDriftAction
        DriftDetection-->>KeylessDriftDetector: Detection complete
    else Skip detection
        KeylessDriftDetector->>KeylessDriftDetector: No-op
    end
    end
    
    ClientClerkProvider-->>NextApp: Rendered tree
    NextApp-->>User: Response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35–50 minutes

  • Drift detection logic interaction: Review the bidirectional drift detection (server-side in getKeylessStatus, client-side in KeylessDriftDetector) to ensure no race conditions or duplicate detections across component boundaries.
  • Suspense wrapping behavior: Verify that SuspenseWhenCached correctly honors the cache flag and that noopWhen={dynamic} prevents unnecessary suspense wrapping for dynamic routes.
  • Telemetry per-key mechanism: Validate the refactored per-public-key flag file approach, ensure directory creation is robust, and confirm telemetry events fire correctly with the new simplified content.
  • Component lazy-loading path: Confirm LazyKeylessDriftDetector is imported and mounted only when keyless is enabled and not disabled via the prop.
  • Public API changes: Ensure the new disableKeylessDriftDetection prop propagates correctly through the provider hierarchy and that backward compatibility is maintained.

Poem

🐰 Keys that drift through the caching night,
Now detected with suspenseful might!
Lazy components whisper their call,
While servers and clients sync it all.
Next.js components embrace the change—
A hop forward, no longer strange! 🌟

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix(nextjs): Improve support for cacheComponents" clearly and directly aligns with the main objective of the changeset. According to the PR objectives, this PR specifically updates Next.js-related code to improve support for cacheComponents, which is exactly what the title states. The changes across multiple files—including the addition of SuspenseWhenCached boundaries, keyless drift detection controls, and the new disableKeylessDriftDetection prop—all serve this primary goal of better supporting Next.js's cacheComponents feature. The title is concise, specific, and appropriately captures the high-level purpose without requiring detailed implementation specifics.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1388-improve-experience-with-cachecomponents-and-keyless

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 31, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: f6c4a1c

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

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

137-140: Consider extracting extended props to a proper type definition.

The props are extended inline with disableKeyless and disableKeylessDriftDetection. While functional, defining a dedicated type/interface would improve maintainability and provide better IDE support.

Consider creating a dedicated type:

type ClientClerkProviderProps = NextClerkProviderProps & {
  disableKeyless?: boolean;
  disableKeylessDriftDetection?: boolean;
};

export const ClientClerkProvider = (props: ClientClerkProviderProps) => {
  // ...
};
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 f47b5a3 and f6c4a1c.

📒 Files selected for processing (7)
  • .changeset/quiet-rockets-invite.md (1 hunks)
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx (2 hunks)
  • packages/nextjs/src/app-router/client/keyless-drift-detector.tsx (1 hunks)
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx (2 hunks)
  • packages/nextjs/src/app-router/server/keyless-provider.tsx (3 hunks)
  • packages/nextjs/src/app-router/suspense-when-cached.tsx (1 hunks)
  • packages/nextjs/src/server/keyless-telemetry.ts (5 hunks)
🧰 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/nextjs/src/app-router/client/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/client/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/client/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/client/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/client/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/server/keyless-telemetry.ts
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • 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/keyless-drift-detector.tsx
  • packages/nextjs/src/app-router/suspense-when-cached.tsx
  • packages/nextjs/src/app-router/server/ClerkProvider.tsx
  • packages/nextjs/src/app-router/server/keyless-provider.tsx
  • packages/nextjs/src/app-router/client/ClerkProvider.tsx
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/quiet-rockets-invite.md
🧬 Code graph analysis (6)
packages/nextjs/src/app-router/client/keyless-drift-detector.tsx (1)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/nextjs/src/app-router/suspense-when-cached.tsx (1)
scripts/notify.mjs (1)
  • process (6-6)
packages/nextjs/src/app-router/server/ClerkProvider.tsx (5)
packages/nextjs/src/app-router/server/keyless-provider.tsx (2)
  • getKeylessStatus (16-43)
  • KeylessProvider (52-165)
packages/nextjs/src/server/keyless-telemetry.ts (1)
  • detectKeylessEnvDrift (90-188)
packages/nextjs/src/app-router/suspense-when-cached.tsx (1)
  • SuspenseWhenCached (12-30)
packages/nextjs/src/server/content-security-policy.ts (1)
  • generateNonce (253-258)
packages/nextjs/src/app-router/client/ClerkProvider.tsx (1)
  • ClientClerkProvider (137-157)
packages/nextjs/src/server/keyless-telemetry.ts (2)
packages/nextjs/src/server/fs/utils.ts (2)
  • nodePathOrThrow (29-29)
  • nodeFsOrThrow (29-29)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/nextjs/src/app-router/server/keyless-provider.tsx (1)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/nextjs/src/app-router/client/ClerkProvider.tsx (2)
packages/nextjs/src/utils/mergeNextClerkPropsWithEnv.ts (1)
  • mergeNextClerkPropsWithEnv (7-36)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
⏰ 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). (30)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/nextjs/src/app-router/server/keyless-provider.tsx (2)

31-34: Drift detection logic looks correct.

The runningWithDriftedKeys calculation correctly identifies when a provided publishableKey differs from the locally stored one. The three conditions ensure both keys exist and are different, which is the proper definition of drift.


72-72: The drift detection handling is properly implemented across both render paths.

Both locations (lines 72 and 91) correctly pass disableKeylessDriftDetection to ClientClerkProvider. The prop is properly threaded through and conditionally gates the LazyKeylessDriftDetector render in ClientClerkProvider (line 146 in ClerkProvider.tsx): when the prop is true, drift detection is disabled for RSC contexts; when false or undefined, the detector renders normally in client contexts. The implementation correctly prevents drift detection in server-rendered fallback scenarios while maintaining its functionality where appropriate.

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

30-33: LGTM: Lazy loading pattern is consistent.

The dynamic import for LazyKeylessDriftDetector follows the same pattern as LazyCreateKeylessApplication, which is appropriate for optional feature loading.


144-149: No verification needed—the implementation is correct for Client Components.

The drift detector implementation aligns with Next.js best practices. LazyKeylessDriftDetector is properly defined as a dynamic import, and conditional rendering works correctly whether cacheComponents is enabled or not. Importantly, this is a Client Component (marked with 'use client'), so cacheComponents—which only affects server-side rendering semantics—doesn't impact its behavior. Conditional rendering of dynamically imported components is unaffected by cacheComponents; only prerender/caching semantics change.

Comment on lines +1 to +17
import { useSelectedLayoutSegments } from 'next/navigation';
import { useEffect } from 'react';

import { canUseKeyless } from '../../utils/feature-flags';

export function KeylessDriftDetector() {
const segments = useSelectedLayoutSegments();
const isNotFoundRoute = segments[0]?.startsWith('/_not-found') || false;

useEffect(() => {
if (canUseKeyless && !isNotFoundRoute) {
void import('../keyless-actions.js').then(m => m.detectKeylessEnvDriftAction());
}
}, [isNotFoundRoute]);

return null;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Add the 'use client'; directive

This component uses client-only hooks (useSelectedLayoutSegments, useEffect), but without the 'use client'; directive Next.js will treat it as a server component and fail at build/runtime with “Hooks can only be used in a Client Component” errors. Please add the directive so the file is compiled as a client component.

+'use client';
+
 import { useSelectedLayoutSegments } from 'next/navigation';
 import { useEffect } from 'react';
📝 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
import { useSelectedLayoutSegments } from 'next/navigation';
import { useEffect } from 'react';
import { canUseKeyless } from '../../utils/feature-flags';
export function KeylessDriftDetector() {
const segments = useSelectedLayoutSegments();
const isNotFoundRoute = segments[0]?.startsWith('/_not-found') || false;
useEffect(() => {
if (canUseKeyless && !isNotFoundRoute) {
void import('../keyless-actions.js').then(m => m.detectKeylessEnvDriftAction());
}
}, [isNotFoundRoute]);
return null;
}
'use client';
import { useSelectedLayoutSegments } from 'next/navigation';
import { useEffect } from 'react';
import { canUseKeyless } from '../../utils/feature-flags';
export function KeylessDriftDetector() {
const segments = useSelectedLayoutSegments();
const isNotFoundRoute = segments[0]?.startsWith('/_not-found') || false;
useEffect(() => {
if (canUseKeyless && !isNotFoundRoute) {
void import('../keyless-actions.js').then(m => m.detectKeylessEnvDriftAction());
}
}, [isNotFoundRoute]);
return null;
}
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/client/keyless-drift-detector.tsx around lines
1 to 17, this component uses client-only hooks but lacks the 'use client'
directive; add the exact line 'use client'; as the very first line of the file
(before any imports) so Next.js treats the module as a Client Component and the
hooks (useSelectedLayoutSegments, useEffect) run correctly.

Comment on lines +72 to +78
if (runningWithDriftedKeys) {
onlyTry(async () => {
const detectKeylessEnvDrift = await import('../../server/keyless-telemetry.js').then(
mod => mod.detectKeylessEnvDrift,
);
await detectKeylessEnvDrift();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid wrapping async drift detection in onlyTry

onlyTry is designed for synchronous callbacks; wrapping an async function in it won’t catch rejected Promises. If the dynamic import or detectKeylessEnvDrift() ever rejects, you’ll surface an unhandled rejection. Please handle the Promise chain explicitly (or add an awaited try/catch) so errors stay contained.

-  if (runningWithDriftedKeys) {
-    onlyTry(async () => {
-      const detectKeylessEnvDrift = await import('../../server/keyless-telemetry.js').then(
-        mod => mod.detectKeylessEnvDrift,
-      );
-      await detectKeylessEnvDrift();
-    });
-  }
+  if (runningWithDriftedKeys) {
+    void import('../../server/keyless-telemetry.js')
+      .then(mod => mod.detectKeylessEnvDrift?.())
+      .catch(() => {});
+  }
📝 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 (runningWithDriftedKeys) {
onlyTry(async () => {
const detectKeylessEnvDrift = await import('../../server/keyless-telemetry.js').then(
mod => mod.detectKeylessEnvDrift,
);
await detectKeylessEnvDrift();
});
if (runningWithDriftedKeys) {
void import('../../server/keyless-telemetry.js')
.then(mod => mod.detectKeylessEnvDrift?.())
.catch(() => {});
}
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/server/ClerkProvider.tsx around lines 72 to
78, the code wraps an async operation in onlyTry which only handles synchronous
exceptions; this can lead to unhandled Promise rejections if the dynamic import
or detectKeylessEnvDrift() rejects. Replace the onlyTry(async () => { ... })
usage with an explicit Promise-safe pattern: perform the dynamic import and
await detectKeylessEnvDrift() inside a try/catch (or call the promise and attach
.catch()), and handle/log the error inside the catch so the rejection is
contained and won’t surface as an unhandled rejection.

Comment on lines 16 to 43
export async function getKeylessStatus(
params: Without<NextClerkProviderProps, '__unstable_invokeMiddlewareOnAuthStateChange'>,
) {
let [shouldRunAsKeyless, runningWithClaimedKeys, locallyStoredPublishableKey] = [false, false, ''];
let [shouldRunAsKeyless, runningWithClaimedKeys, runningWithDriftedKeys, locallyStoredPublishableKey] = [
false,
false,
false,
'',
];
if (canUseKeyless) {
locallyStoredPublishableKey = await import('../../server/keyless-node.js')
.then(mod => mod.safeParseClerkFile()?.publishableKey || '')
.catch(() => '');

runningWithClaimedKeys = Boolean(params.publishableKey) && params.publishableKey === locallyStoredPublishableKey;
runningWithDriftedKeys =
Boolean(params.publishableKey) &&
Boolean(locallyStoredPublishableKey) &&
params.publishableKey !== locallyStoredPublishableKey;
shouldRunAsKeyless = !params.publishableKey || runningWithClaimedKeys;
}

return {
shouldRunAsKeyless,
runningWithClaimedKeys,
runningWithDriftedKeys,
};
}
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 | 🟠 Major

Add explicit return type annotation for public API.

The getKeylessStatus function is exported and appears to be part of the public API (used by server ClerkProvider), but lacks an explicit return type annotation.

As per coding guidelines

Apply this diff to add an explicit return type:

-export async function getKeylessStatus(
+export async function getKeylessStatus(
   params: Without<NextClerkProviderProps, '__unstable_invokeMiddlewareOnAuthStateChange'>,
-) {
+): Promise<{
+  shouldRunAsKeyless: boolean;
+  runningWithClaimedKeys: boolean;
+  runningWithDriftedKeys: boolean;
+}> {
📝 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
export async function getKeylessStatus(
params: Without<NextClerkProviderProps, '__unstable_invokeMiddlewareOnAuthStateChange'>,
) {
let [shouldRunAsKeyless, runningWithClaimedKeys, locallyStoredPublishableKey] = [false, false, ''];
let [shouldRunAsKeyless, runningWithClaimedKeys, runningWithDriftedKeys, locallyStoredPublishableKey] = [
false,
false,
false,
'',
];
if (canUseKeyless) {
locallyStoredPublishableKey = await import('../../server/keyless-node.js')
.then(mod => mod.safeParseClerkFile()?.publishableKey || '')
.catch(() => '');
runningWithClaimedKeys = Boolean(params.publishableKey) && params.publishableKey === locallyStoredPublishableKey;
runningWithDriftedKeys =
Boolean(params.publishableKey) &&
Boolean(locallyStoredPublishableKey) &&
params.publishableKey !== locallyStoredPublishableKey;
shouldRunAsKeyless = !params.publishableKey || runningWithClaimedKeys;
}
return {
shouldRunAsKeyless,
runningWithClaimedKeys,
runningWithDriftedKeys,
};
}
export async function getKeylessStatus(
params: Without<NextClerkProviderProps, '__unstable_invokeMiddlewareOnAuthStateChange'>,
): Promise<{
shouldRunAsKeyless: boolean;
runningWithClaimedKeys: boolean;
runningWithDriftedKeys: boolean;
}> {
let [shouldRunAsKeyless, runningWithClaimedKeys, runningWithDriftedKeys, locallyStoredPublishableKey] = [
false,
false,
false,
'',
];
if (canUseKeyless) {
locallyStoredPublishableKey = await import('../../server/keyless-node.js')
.then(mod => mod.safeParseClerkFile()?.publishableKey || '')
.catch(() => '');
runningWithClaimedKeys = Boolean(params.publishableKey) && params.publishableKey === locallyStoredPublishableKey;
runningWithDriftedKeys =
Boolean(params.publishableKey) &&
Boolean(locallyStoredPublishableKey) &&
params.publishableKey !== locallyStoredPublishableKey;
shouldRunAsKeyless = !params.publishableKey || runningWithClaimedKeys;
}
return {
shouldRunAsKeyless,
runningWithClaimedKeys,
runningWithDriftedKeys,
};
}
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/server/keyless-provider.tsx around lines 16 to
43, the exported async function getKeylessStatus lacks an explicit return type;
update the function signature to include a concrete return type annotation such
as Promise<{ shouldRunAsKeyless: boolean; runningWithClaimedKeys: boolean;
runningWithDriftedKeys: boolean }>, leaving the implementation unchanged so the
function returns the same object but now with an explicit public API type.

@blacksmith-sh

This comment has been minimized.

@Pmacdon15
Copy link

In the repohttps://github.com/Pmacdon15/show-error I provided to clerk customer support it was suggested I try this pr to see if it fixed the build error I was getting when using a route with dynamic with params. Now on build I'm getting this error:

Render in Browser should be wrapped in a suspense boundary at page "/test/[test]". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout
    at _ (/home/pmacd/Projects/show-error/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js:21:85)
    at i8 (/home/pmacd/Projects/show-error/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js:39:8922)
    at runNextTicks (node:internal/process/task_queues:65:5)
    at process.processImmediate (node:internal/timers:453:9)
    at process.callbackTrampoline (node:internal/async_hooks:130:17)
    at async i0 (/home/pmacd/Projects/show-error/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js:38:20096)
    at async exportAppPage (/home/pmacd/Projects/show-error/node_modules/next/dist/export/routes/app-page.js:42:24)
    at async Span.traceAsyncFn (/home/pmacd/Projects/show-error/node_modules/next/dist/trace/trace.js:157:20)
    at async exportPage (/home/pmacd/Projects/show-error/node_modules/next/dist/export/worker.js:352:18)
    at async exportPageWithRetry (/home/pmacd/Projects/show-error/node_modules/next/dist/export/worker.js:244:26)
    at async Promise.all (index 4)
    at async Object.exportPages (/home/pmacd/Projects/show-error/node_modules/next/dist/export/worker.js:329:31)
Error occurred prerendering page "/test/[test]". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /test/[test]/page: /test/[test], exiting the build.
 ⨯ Next.js build worker exited with code: 1 and signal: null
error: script "build" exited with code 1

I tired adding a loading.tsx and that didn't help.

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