Skip to content

fix: create server clerkClient lazily (no secretKey in inlined bundles, breaks nonce handshakes) - #442

Open
amitosdev wants to merge 1 commit into
clerk-community:mainfrom
amitosdev:fix/lazy-clerk-client
Open

fix: create server clerkClient lazily (no secretKey in inlined bundles, breaks nonce handshakes)#442
amitosdev wants to merge 1 commit into
clerk-community:mainfrom
amitosdev:fix/lazy-clerk-client

Conversation

@amitosdev

Copy link
Copy Markdown

Problem

The server clerkClient singleton is created at module scope, reading CLERK_SECRET_KEY/CLERK_JWT_KEY from $env/dynamic/private (via constants.ts). In inlined server bundles — e.g. adapter-vercel — module evaluation runs before SvelteKit's Server.init() populates dynamic env, so the client is permanently constructed with secretKey: undefined. Every Backend API call it makes then throws Missing Clerk Secret Key, even though the env var is correctly set on the platform.

This stayed near-invisible for a long time because:

  • Passing secretKey to withClerkHandler() options covers authenticateRequest's own token verification, but not the singleton's embedded BAPI apiClient, which keeps the empty key.
  • Since Clerk's FAPI began serving nonce-format handshakes to production instances (~mid 2026), handshake resolution requires a server-to-server BAPI call (clients.getHandshakePayload) through this singleton. @clerk/backend swallows the failure (getCookiesFromHandshake catches and continues), so handshakes silently deliver no cookies — and flows that depend on server-side handshake convergence (e.g. Dashboard impersonation) dead-loop to the sign-in page with no error surfaced.

The only trace is a Clerk: HandshakeService: error getting handshake payload: Error: Missing Clerk Secret Key. line in function logs.

Reproduction

Any SvelteKit app on Vercel (adapter-vercel) with CLERK_SECRET_KEY set as a runtime env var:

curl https://your-app.example/ -H 'Cookie: __clerk_handshake_nonce=garbage'

Function logs show Missing Clerk Secret Key (broken) instead of an authenticated BAPI 404 for the unknown nonce (healthy).

Fix

Defer client creation to first property access via a Proxy, so the dynamic-env read happens at request time, after Server.init(). The exported clerkClient object shape and its ClerkClient type are unchanged — no call-site or API changes.

The client is only memoized once the secret key is readable, so a property access that happens before dynamic env is populated (e.g. from user module-scope code) can't permanently capture a keyless client.

Note this also transparently fixes withClerkHandler for env-only setups on affected bundles: its constants.SECRET_KEY fallback is still a module-scope read (undefined there), but @clerk/backend's option merging (options[key] || buildTimeOptions[key]) falls back to the now correctly lazily-read client key.

Verified in production

Deployed as a pnpm patch on a production Vercel app that hit this bug:

  • Before: the curl probe above → Missing Clerk Secret Key in logs, zero handshake_payload requests reaching Clerk's API (confirmed by Clerk support); Dashboard impersonation dead-loops to /login.
  • After (lazy init): same probe → authenticated ClerkAPIResponseError: Not Found for the garbage nonce; Dashboard impersonation works.

Out of scope (same latent pattern, lower stakes)

A few other module-scope dynamic-env reads in constants.ts share the timing pattern but fail loud or fall back safely, so they're left untouched here: PUBLISHABLE_KEY (an empty value fails loudly via assertValidPublishableKey in authenticateRequest), API_URL (apiUrlFromPublishableKey(undefined) falls back to the production API URL — only wrong for staging/local or a custom PUBLIC_CLERK_API_URL), and the telemetry flags (cosmetic). If you'd rather close the whole class, converting constants.ts to lazy getters would do it — happy to follow up.

@netlify

netlify Bot commented Jul 8, 2026

Copy link
Copy Markdown

Deploy Preview for svelte-clerk ready!

Name Link
🔨 Latest commit 0bad95a
🔍 Latest deploy log https://app.netlify.com/projects/svelte-clerk/deploys/6a4ea72651713200083336ec
😎 Deploy Preview https://deploy-preview-442--svelte-clerk.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

The server `clerkClient` singleton was created at module scope, reading
`secretKey`/`jwtKey` from `$env/dynamic/private`. In inlined server
bundles (e.g. `adapter-vercel`), module evaluation runs before
SvelteKit's `Server.init()` populates dynamic env, so the client was
built with an undefined `secretKey`. Every Backend API call then fails
with "Missing Clerk Secret Key".

This is largely invisible until a code path exercises the client's
embedded BAPI client — most notably nonce-format handshake resolution
(`clients.getHandshakePayload`), which `@clerk/backend` swallows, so
handshakes silently deliver no cookies.

Defer creation to first property access via a Proxy so the dynamic-env
read happens at request time, after `Server.init()`. The exported
`clerkClient` shape and its `ClerkClient` type are unchanged.
@amitosdev
amitosdev force-pushed the fix/lazy-clerk-client branch from 0bad95a to 97de312 Compare July 22, 2026 18:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant