Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fine-weeks-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/nextjs': patch
---

Fix keyless drift logic to support client components and ensure only apps on development are included. Change createClerkClient to accept an argument for samplingRate in telemetry options and update the ClerkOptions type.
4 changes: 2 additions & 2 deletions packages/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export type ClerkOptions = Omit<CreateBackendApiOptions, 'skipApiVersionInUrl' |
CreateAuthenticateRequestOptions['options'],
'audience' | 'jwtKey' | 'proxyUrl' | 'secretKey' | 'publishableKey' | 'domain' | 'isSatellite'
>
> & { sdkMetadata?: SDKMetadata; telemetry?: Pick<TelemetryCollectorOptions, 'disabled' | 'debug'> };
> & { sdkMetadata?: SDKMetadata; telemetry?: Pick<TelemetryCollectorOptions, 'disabled' | 'debug' | 'samplingRate'> };

// The current exported type resolves the following issue in packages importing createClerkClient
// TS4023: Exported variable 'clerkClient' has or is using name 'AuthErrorReason' from external module "/packages/backend/dist/index" but cannot be named.
Expand All @@ -31,11 +31,11 @@ export function createClerkClient(options: ClerkOptions): ClerkClient {
const apiClient = createBackendApiClient(opts);
const requestState = createAuthenticateRequest({ options: opts, apiClient });
const telemetry = new TelemetryCollector({
...options.telemetry,
publishableKey: opts.publishableKey,
secretKey: opts.secretKey,
samplingRate: 0.1,
...(opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}),
...(opts.telemetry || {}),
});

return {
Expand Down
8 changes: 8 additions & 0 deletions packages/nextjs/src/app-router/client/ClerkProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { canUseKeyless } from '../../utils/feature-flags';
import { mergeNextClerkPropsWithEnv } from '../../utils/mergeNextClerkPropsWithEnv';
import { RouterTelemetry } from '../../utils/router-telemetry';
import { isNextWithUnstableServerActions } from '../../utils/sdk-versions';
import { detectKeylessEnvDriftAction } from '../keyless-actions';
import { invalidateCacheAction } from '../server-actions';
import { useAwaitablePush } from './useAwaitablePush';
import { useAwaitableReplace } from './useAwaitableReplace';
Expand Down Expand Up @@ -43,6 +44,13 @@ const NextClientClerkProvider = (props: NextClerkProviderProps) => {
const replace = useAwaitableReplace();
const [isPending, startTransition] = useTransition();

// Call drift detection on mount (client-side)
useSafeLayoutEffect(() => {
if (canUseKeyless) {
void detectKeylessEnvDriftAction();
}
}, []);

// Avoid rendering nested ClerkProviders by checking for the existence of the ClerkNextOptions context provider
const isNested = Boolean(useClerkNextOptions());
if (isNested) {
Expand Down
13 changes: 13 additions & 0 deletions packages/nextjs/src/app-router/keyless-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,16 @@ export async function deleteKeylessAction() {
await import('../server/keyless-node.js').then(m => m.removeKeyless()).catch(() => {});
return;
}

export async function detectKeylessEnvDriftAction() {
if (!canUseKeyless) {
return;
}

try {
const { detectKeylessEnvDrift } = await import('../server/keyless-telemetry.js');
await detectKeylessEnvDrift();
} catch {
// ignore
}
}
7 changes: 7 additions & 0 deletions packages/nextjs/src/server/keyless-telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { TelemetryEventRaw } from '@clerk/types';
import { promises as fs } from 'fs';
import { dirname, join } from 'path';

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

const EVENT_KEYLESS_ENV_DRIFT_DETECTED = 'KEYLESS_ENV_DRIFT_DETECTED';
Expand Down Expand Up @@ -86,6 +87,9 @@ async function tryMarkTelemetryEventAsFired(): Promise<boolean> {
* @returns Promise<void> - Function completes silently, errors are logged but don't throw
*/
export async function detectKeylessEnvDrift(): Promise<void> {
if (!canUseKeyless) {
return;
}
// Only run on server side
if (typeof window !== 'undefined') {
return;
Expand Down Expand Up @@ -163,6 +167,9 @@ export async function detectKeylessEnvDrift(): Promise<void> {
const clerkClient = createClerkClientWithOptions({
publishableKey: keylessFile.publishableKey,
secretKey: keylessFile.secretKey,
telemetry: {
samplingRate: 1,
},
});

const shouldFireEvent = await tryMarkTelemetryEventAsFired();
Expand Down
Loading