fix: create server clerkClient lazily (no secretKey in inlined bundles, breaks nonce handshakes) - #442
Open
amitosdev wants to merge 1 commit into
Open
Conversation
✅ Deploy Preview for svelte-clerk ready!
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
force-pushed
the
fix/lazy-clerk-client
branch
from
July 22, 2026 18:49
0bad95a to
97de312
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The server
clerkClientsingleton is created at module scope, readingCLERK_SECRET_KEY/CLERK_JWT_KEYfrom$env/dynamic/private(viaconstants.ts). In inlined server bundles — e.g.adapter-vercel— module evaluation runs before SvelteKit'sServer.init()populates dynamic env, so the client is permanently constructed withsecretKey: undefined. Every Backend API call it makes then throwsMissing Clerk Secret Key, even though the env var is correctly set on the platform.This stayed near-invisible for a long time because:
secretKeytowithClerkHandler()options coversauthenticateRequest's own token verification, but not the singleton's embedded BAPIapiClient, which keeps the empty key.clients.getHandshakePayload) through this singleton.@clerk/backendswallows the failure (getCookiesFromHandshakecatches 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) withCLERK_SECRET_KEYset as a runtime env var: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, afterServer.init(). The exportedclerkClientobject shape and itsClerkClienttype 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
withClerkHandlerfor env-only setups on affected bundles: itsconstants.SECRET_KEYfallback is still a module-scope read (undefinedthere), 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 patchon a production Vercel app that hit this bug:Missing Clerk Secret Keyin logs, zerohandshake_payloadrequests reaching Clerk's API (confirmed by Clerk support); Dashboard impersonation dead-loops to/login.ClerkAPIResponseError: Not Foundfor the garbage nonce; Dashboard impersonation works.Out of scope (same latent pattern, lower stakes)
A few other module-scope dynamic-env reads in
constants.tsshare the timing pattern but fail loud or fall back safely, so they're left untouched here:PUBLISHABLE_KEY(an empty value fails loudly viaassertValidPublishableKeyinauthenticateRequest),API_URL(apiUrlFromPublishableKey(undefined)falls back to the production API URL — only wrong for staging/local or a customPUBLIC_CLERK_API_URL), and the telemetry flags (cosmetic). If you'd rather close the whole class, convertingconstants.tsto lazy getters would do it — happy to follow up.