- 
                Notifications
    
You must be signed in to change notification settings  - Fork 402
 
fix(nextjs): Improve support for cacheComponents #7119
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
base: main
Are you sure you want to change the base?
fix(nextjs): Improve support for cacheComponents #7119
Conversation
This PR also prevents keylessDriftDetection from firing as an action when the RSC variant is used.
          🦋 Changeset detectedLatest commit: f6c4a1c The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
 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  | 
    
| 
           The latest updates on your projects. Learn more about Vercel for GitHub. 
  | 
    
          
WalkthroughThis 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
 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
    Estimated code review effort🎯 4 (Complex) | ⏱️ ~35–50 minutes 
 Poem
 Pre-merge checks and finishing touches❌ Failed checks (1 warning)
 ✅ Passed checks (2 passed)
 ✨ Finishing touches
 🧪 Generate unit tests (beta)
 Comment   | 
    
          
@clerk/agent-toolkit
 @clerk/astro
 @clerk/backend
 @clerk/chrome-extension
 @clerk/clerk-js
 @clerk/dev-cli
 @clerk/elements
 @clerk/clerk-expo
 @clerk/expo-passkeys
 @clerk/express
 @clerk/fastify
 @clerk/localizations
 @clerk/nextjs
 @clerk/nuxt
 @clerk/clerk-react
 @clerk/react-router
 @clerk/remix
 @clerk/shared
 @clerk/tanstack-react-start
 @clerk/testing
 @clerk/themes
 @clerk/types
 @clerk/upgrade
 @clerk/vue
 commit:   | 
    
There was a problem hiding this 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
disableKeylessanddisableKeylessDriftDetection. 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.
📒 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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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.tsxpackages/nextjs/src/app-router/suspense-when-cached.tsxpackages/nextjs/src/app-router/server/ClerkProvider.tsxpackages/nextjs/src/app-router/server/keyless-provider.tsxpackages/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
runningWithDriftedKeyscalculation 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
disableKeylessDriftDetectiontoClientClerkProvider. The prop is properly threaded through and conditionally gates theLazyKeylessDriftDetectorrender 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
LazyKeylessDriftDetectorfollows the same pattern asLazyCreateKeylessApplication, 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.
LazyKeylessDriftDetectoris properly defined as a dynamic import, and conditional rendering works correctly whethercacheComponentsis 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.
| 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; | ||
| } | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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.
| if (runningWithDriftedKeys) { | ||
| onlyTry(async () => { | ||
| const detectKeylessEnvDrift = await import('../../server/keyless-telemetry.js').then( | ||
| mod => mod.detectKeylessEnvDrift, | ||
| ); | ||
| await detectKeylessEnvDrift(); | ||
| }); | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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.
| 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, | ||
| }; | ||
| } | 
There was a problem hiding this comment.
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.
| 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.
      
        
              This comment has been minimized.
        
        
      
    
  This comment has been minimized.
| 
           In the repo I tired adding a loading.tsx and that didn't help.  | 
    
This PR also prevents keylessDriftDetection from firing as an action when the RSC variant is used.
Description
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Improvements