Skip to content

Clerk on a server with no frontend: reading the session on a script-free page #113

Closed

Description

@allisonmahmood

Question

How does a plain Node server — no Next.js, no ClerkJS on the page — authenticate a document request with Clerk, so the login door can sit in front of a tier 0 page whose CSP allows no script? From Clerk's docs and the @clerk/backend source:

  1. authenticateRequest: what it takes (a Web Request? which headers?), the RequestState it returns (signed-in, signed-out, handshake), and the headers it asks the server to set on the response.
  2. The cookies involved — __session, __client_uat, __clerk_db_jwt / the dev browser — and which domain each is set on, in a development instance and in production.
  3. The handshake: when it triggers, what it does for a document request versus an API request, and whether it needs any script on the app's own page to complete. This is the load-bearing claim: a page under default-src 'none' must still get a fresh session after the 60-second token expires.
  4. Session-token verification: jwtKey (PEM) local verification versus JWKS fetch, token lifetime and refresh, authorizedParties, clock skew.
  5. The claims a session token carries by default, and how email and name get in (session token customization).
  6. The domain constraint: must the app serving pages share a registrable domain with Clerk's Frontend API and the Account Portal? What satellite domains are for. What a development instance does instead.
  7. Sign-out from a server-rendered page with no ClerkJS.
  8. @clerk/express and @clerk/fastify as worked examples of a plain server; the current @clerk/backend version and Node requirement.

Output: the resolution comment on this ticket, each claim cited to the doc page or source file. Feeds the door prototype and The login door on a tier 0 page.

Activity

  1. added
    wayfinder:research
    on Sep 2, 2026
  2. allisonmahmood commented on Sep 2, 2026

    @allisonmahmood
    OwnerAuthor

    Resolution

    Sources read 2026-09-02: clerk.com/docs pages cited inline; clerk/javascript main branch source (packages/backend = @clerk/[email protected], packages/[email protected], packages/[email protected], per each package's package.json on main, matching npm latest for all three); clerk/openapi-specs FAPI spec fapi/2026-05-12.yml (the SUPPORTED_BAPI_VERSION the SDK sends); npm registry for @clerk/backend@latest. Where a claim comes from source rather than docs it is marked (src).

    Bottom line. Yes: a plain Node server can gate a script-free document with clerkClient.authenticateRequest(webRequest, opts). The handshake that refreshes an expired 60-second session token is a pure 307-redirect chain (app -> Frontend API -> app) and the SDK turns the returned payload into Set-Cookie headers on the server's own response; no script on the app page is involved. The sign-in itself happens on Clerk's Account Portal (its own origin, which runs ClerkJS), so the tier 0 page never needs to load ClerkJS.

    1. authenticateRequest

    • Signature: authenticateRequest(request: Request, options: AuthenticateRequestOptions): Promise<RequestState>; takes a standard Fetch Request [https://clerk.com/docs/reference/backend/authenticate-request]. @clerk/express builds one from IncomingMessage (incomingMessageToRequest) and @clerk/fastify via fastifyRequestToRequest (src packages/express/src/authenticateRequest.ts, packages/fastify/src/withClerkMiddleware.ts).
    • What it reads from the request (src packages/backend/src/constants.ts, tokens/authenticateContext.ts, tokens/clerkRequest.ts): cookies __session, __client_uat, __clerk_db_jwt, __clerk_handshake, __clerk_handshake_nonce, __clerk_redirect_count, __refresh (each also in a suffixed form <name>_<suffix>; __refresh is read in the suffixed form only); headers authorization (Bearer), sec-fetch-dest, accept, referer, origin, host, x-forwarded-host, x-forwarded-proto / cloudfront-forwarded-proto, user-agent; query params __clerk_db_jwt (legacy __dev_session), __clerk_handshake, __clerk_handshake_nonce, __clerk_synced, __clerk_redirect_url. The request URL is rebuilt from the first value of x-forwarded-host / x-forwarded-proto when present (deriveUrlFromHeaders), so the server behind a proxy must forward those or the handshake redirect_url will be wrong. The cookie token wins over the header token: sessionToken = sessionTokenInCookie || tokenInHeader (src authenticateContext.ts line 66).
    • Options (docs table + tokens/types.ts src): secretKey (asserted present unless acceptsToken is m2m_token, src request.ts; the docs table types it optional), publishableKey ("Required when using authenticateRequest(), unless acceptsToken is set to 'api_key' or 'm2m_token'"; the Frontend API host and instance type are decoded from it), jwtKey (PEM, networkless), authorizedParties: string[], clockSkewInMs (default 5000), audience, acceptsToken (default 'session_token'; 'api_key' | 'oauth_token' | 'm2m_token' | 'any' or an array), domain, isSatellite (default false), proxyUrl, signInUrl, signUpUrl, satelliteAutoSync (default false), skipJwksCache, organizationSyncOptions [https://clerk.com/docs/reference/backend/authenticate-request, https://clerk.com/docs/reference/backend/overview]. Docs: "it's highly recommended to explicitly set the authorizedParties option"; "Not setting this value can open your application to CSRF attacks" [authenticate-request; https://clerk.com/docs/guides/sessions/manual-jwt-verification].
    • RequestState: { status: 'signed-in' | 'signed-out' | 'handshake', isAuthenticated, isSignedIn (deprecated), reason: string | null, message, tokenType, token: string | null, headers: Headers, toAuth() } [same page]. toAuth() on a signed-in session gives { isAuthenticated, userId, sessionId, sessionClaims (JwtPayload), sessionStatus: 'active' | 'pending', orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge, actor, getToken(), has(), tokenType: 'session_token' } [https://clerk.com/docs/reference/backend/types/auth-object]; toAuth({ treatPendingAsSignedOut }) defaults to true, so a pending session reads as signed out (src tokens/authStatus.ts line 147; not on the docs page). On handshake, toAuth() returns null (src HandshakeState).
    • Headers the server must copy onto its response (src tokens/request.ts, tokens/handshake.ts): on status === 'handshake': Location (the FAPI handshake URL), cache-control: no-store ("Chrome aggressively caches inactive tabs. If we don't set the header here, all 307 redirects will be cached and the handshake will end up in an infinite loop"), and Set-Cookie: __clerk_redirect_count=<n>; SameSite=Lax; HttpOnly; Max-Age=2; the server must respond 307 with those headers. When the handshake payload comes back and is resolved, the returned state (signed-in or signed-out) carries Set-Cookie directives for the session cookies plus Access-Control-Allow-Origin: null, Access-Control-Allow-Credentials: true; on a development instance it also carries Location (the same URL with __clerk_handshake, __clerk_help, __clerk_db_jwt, __clerk_handshake_nonce stripped) and Cache-Control: no-store, i.e. one more 307. Contract as implemented by both official plain-server SDKs and documented for SDK authors: append every header from requestState.headers, then if location is present end the response with 307; a handshake status without Location is an error ('Clerk: unexpected handshake without redirect' in express, 'Clerk: handshake status without redirect' in fastify) (src express setResponseForHandshake, fastify withClerkMiddleware; [https://clerk.com/docs/guides/development/sdk-development/fullstack] shows context.redirect(locationHeader, 307)). The authenticate-request docs page itself does not list these headers; the source and the SDK-development guide do.
    • Redirect-loop guard: after __clerk_redirect_count reaches 3 the SDK returns signed-out instead of another handshake and logs "Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match" (src checkAndTrackRedirectLoop, getHandshakeRedirectLoopMessage).

    2. Cookies and their domains

    Cookie Set by Domain Attributes Notes
    __session ClerkJS on the app page (dev and prod), or the server via handshake Set-Cookie directives "Set on your application's domain directly, scoped strictly so it cannot be shared across subdomains" [https://clerk.com/docs/guides/how-clerk-works/overview]; ClerkJS sets it with no Domain attribute, i.e. host-only (src clerk-js/src/core/auth/cookies/session.ts) HttpOnly: No, SameSite=Lax (None when partitioned/iframe), cookie expires 1 year (addYears(Date.now(), 1), src) but JWT exp 60 s [overview] The Clerk-signed session JWT.
    __client_uat In production "set by the Clerk FAPI"; in development "set by clerk-js on the client-side" [https://clerk.com/docs/guides/development/sdk-development/terminology; src cookies/clientUat.ts comment] or by handshake directives eTLD+1 of the app host, "aligns with logic in FAPI" (src clerk-js/src/core/auth/getCookieDomain.ts); localhost / 127.0.0.1 / 0.0.0.0 returned as-is ClerkJS in dev uses SameSite=Strict; "In production, nothing is cross-domain and Lax is used when client_uat is set from FAPI" (src) Value 0 = signed out, else floor(client.updatedAt / 1000) (src). The backend compares it with the JWT: iat < client_uat -> handshake reason session-token-iat-before-client-uat (src request.ts).
    __client FAPI "Set on your FAPI domain (clerk.example.com), rather than on your app domain"; HttpOnly: Yes, SameSite=Lax; "only used in production environments" [overview] Source of truth for auth state; the server never sees it.
    __clerk_db_jwt ClerkJS (dev only) app host (no Domain), SameSite=Lax (src cookies/devBrowser.ts); also carried as query __clerk_db_jwt The "dev browser", the development stand-in for __client: transmitted "via querystring (__clerk_db_jwt) rather than via cookie" [https://clerk.com/docs/guides/development/managing-environments]. The backend reads it from the query first, then the cookie (src).
    __clerk_handshake / __clerk_handshake_nonce FAPI, on the redirect back production: a cookie "set on etld+1" (src comment in request.ts); development: a query parameter (src: authenticateContext reads query then cookie; resolveHandshake strips the query params in dev) Payload that carries the new cookies; format=nonce is what the SDK requests (src). Docs only say Clerk uses "non-persistent cookies (e.g., __clerk_handshake) for internal mechanisms" [terminology].
    __clerk_redirect_count the app server (SDK header) host-only SameSite=Lax; HttpOnly; Max-Age=2 (src) loop guard.
    __refresh FAPI (suffixed form only is read, src initCookieValues) Enables attemptRefresh via BAPI sessions.refreshSession on GET when the token is expired; when FAPI sets it is unverified.

    Suffixed cookies: every one of these also exists as <name>_<suffix> where suffix = base64url(sha1(publishableKey)).substring(0, 8) (src packages/shared/src/keys.ts getCookieSuffix, getSuffixedCookieName), so two Clerk apps on one registrable domain do not collide; the backend decides which family to trust with usesSuffixedCookies() (src). Size: "Most browsers limit cookie size to 4KB" and custom claims should stay "under 1.2KB" [https://clerk.com/docs/guides/sessions/session-tokens].

    Development instance: the Frontend API is on clerk.accounts.dev, so app -> FAPI is cross-site and the dev browser replaces __client [https://clerk.com/docs/guides/how-clerk-works/overview; managing-environments]. Dev instances are "capped at 100 users", "have a more relaxed security posture and are not suitable for production workloads" [managing-environments]. The FAPI spec's DevBrowser security scheme is a query param (__dev_session, the legacy name; the SDKs use __clerk_db_jwt), "It must be set before making any request to a dev instance, even for endpoints that are public" [fapi/2026-05-12.yml /v1/dev_browser, securitySchemes].

    3. The handshake (load-bearing)

    • Purpose per docs: "Server-to-server requests cannot include browser cookies", so when the session token has expired and ClerkJS's 50-second background refresh could not run, "The server returns a redirect response to the browser; the browser follows the redirect to FAPI; FAPI receives the request with the __client cookie" and issues a new session token [https://clerk.com/docs/guides/how-clerk-works/overview]. "If a short-lived session JWT is expired on a request to an application's backend, the SDK doesn't know if the session has ended, or if a new short-lived JWT needs to be issued. When an SDK gets into this state, it triggers the handshake" [https://clerk.com/docs/guides/development/sdk-development/terminology]. FAPI spec: GET /v1/client/handshake "Generate and return a new session token for a given client. When the authentication status cannot be determined from the current session token, we initiate a handshake to refresh the token and send it back to the application. Called in server environments", params redirect_url, format (nonce | token, default token), organization_id, satellite_fapi; response 307 [fapi/2026-05-12.yml].
    • When it triggers (src request.ts authenticateRequestWithTokenInCookie, handleSessionTokenError, reason strings from authStatus.ts AuthErrorReason): session-token-expired-refresh-<refreshError> (see below), session-token-nbf, session-token-iat-in-the-future (verify failed on time), client-uat-but-no-session-token, session-token-but-no-client-uat, session-token-iat-before-client-uat, dev-browser-missing, dev-browser-sync (dev instance only), satellite sync reasons, primary-domain cross-origin sync, and active-organization mismatch. It does not trigger when both __session and __client_uat are absent (session-token-and-uat-missing -> signed-out, checked after the dev-browser checks) nor for invalid signatures.
    • Eligibility (src handshake.ts isRequestEligibleForHandshake): method === 'GET' ("Non-GET requests (e.g. POST form submissions) also set sec-fetch-dest: document, but redirecting them would result in a 405 Method Not Allowed from FAPI") and (sec-fetch-dest is document or iframe, or no sec-fetch-dest and accept starts with text/html). Everything else (fetch/XHR, POST, JSON API) gets signed-out with the same reason. So on /api/* a stale cookie token is a 401 whose reason is session-token-expired-refresh-non-eligible-no-refresh-cookie (GET with no __refresh cookie) or session-token-expired-refresh-non-eligible-non-get (src convertTokenVerificationErrorReasonToAuthErrorReason, RefreshTokenErrorReason); match it by prefix, not equality. Only document navigations get redirected. Browsers send Sec-Fetch-* only to potentially trustworthy URLs ("Assert: r's url is a potentially trustworthy URL"), which covers https and hosts localhost, 127.0.0.0/8, ::1/128 [https://w3c.github.io/webappsec-fetch-metadata/, https://w3c.github.io/webappsec-secure-contexts/]; the Accept fallback covers plain http elsewhere.
    • Redirect built by the SDK (src buildRedirectToHandshake): https://<frontendApi>/v1/client/handshake?redirect_url=<current URL minus __clerk_db_jwt/__dev_session>&__clerk_api_version=2026-05-12&suffixed_cookies=<bool>&__clerk_hs_reason=<reason>&format=nonce[&__session=<old token>][&__clerk_db_jwt=<dev browser> (dev only)][&organization_id=... (org sync)]. FAPI redirects the browser back to redirect_url carrying the payload as __clerk_handshake_nonce / __clerk_handshake, as a query parameter in development and a cookie on the eTLD+1 in production (src authenticateContext.initHandshakeValues, request.ts comment); the SDK, not the page, turns the payload into Set-Cookie headers (src resolveHandshake). Unverified: no clerk.com page states the dev-vs-prod encoding of the payload in prose; the src is the authority here.
    • Completion (src getCookiesFromHandshake, resolveHandshake): on the return request the SDK sees __clerk_handshake_nonce (query or cookie) and calls BAPI clients.getHandshakePayload({ nonce }) (needs secretKey and network; a failure is logged and the flow falls through to a new handshake), or sees __clerk_handshake and verifies that JWT locally (verifyHandshakeToken, jwtKey or JWKS); the payload is a list of raw Set-Cookie directives which the SDK appends to headers, extracts the new __session from (getCookieName(x).startsWith('__session')), verifies with verifyToken, and returns signed-in (or signed-out with reason session-token-missing if no session cookie is in the payload, i.e. the user is signed out at Clerk). Because the SDK always sends format=nonce, completing a handshake is a BAPI call even with jwtKey set (unverified whether FAPI ever falls back to token format).
    • Script on the page: none. Every step is a top-level GET navigation and response headers; the only party that runs ClerkJS is Clerk's Account Portal / sign-in origin. For a page under default-src 'none', after 60 s the next navigation is: app 307 -> FAPI 307 -> app (sets cookies, serves page; in dev one more 307 to clean the URL). Both official plain-server SDKs do exactly this and nothing else (src express setResponseHeaders; fastify withClerkMiddleware, which also has an __internal_enableHandshake switch that still forces the redirect for dev-browser-missing / dev-browser-sync because "Development instances cannot establish auth state without the dev browser handshake").
    • Getting into the signed-in state the first time without script: after sign-in on the Account Portal the user is redirected to redirect_url; in production FAPI has set __client (FAPI host) and __client_uat (eTLD+1), so the app's first document request has __client_uat but no __session -> client-uat-but-no-session-token handshake -> cookies set. In development ClerkJS on the Account Portal appends __clerk_db_jwt to any cross-origin redirect (buildUrlWithAuth -> decorateUrlWithDevBrowserToken, src clerk-js/src/core/clerk.ts; not re-read in this verification pass), the server sees the query param -> dev-browser-sync handshake -> FAPI -> back with __clerk_handshake in the query -> cookies set -> 307 to the clean URL. A dev-instance browser with no dev browser token at all gets dev-browser-missing -> handshake, on every document request until one succeeds (bounded by the loop counter).
    • Dev-only clock-skew fallback: if the handshake-delivered token fails on time, the SDK logs "Clerk: Clock skew detected. This usually means that your system clock is inaccurate." and retries with clockSkewInMs: 86_400_000 (src resolveHandshake).

    4. Session-token verification

    • verifyToken key selection (src tokens/verify.ts): jwtKey -> loadClerkJwkFromPem (no network); else secretKey -> loadClerkJWKFromRemote, which fetches BAPI ${apiUrl}/v1/jwks with Authorization: Bearer <secretKey> and caches per process for 5 minutes (MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60; jwksCacheTtlInMs is "@deprecated ... a no-op"; skipJwksCache forces a fetch) (src tokens/keys.ts, constants.ts). Docs: get the PEM from Dashboard API keys "JWKS Public Key", or https://api.clerk.com/v1/jwks, or <Frontend API>/.well-known/jwks.json; set CLERK_JWT_KEY for "networkless" verification [https://clerk.com/docs/guides/sessions/manual-jwt-verification]. Express reads CLERK_JWT_KEY, CLERK_SECRET_KEY, CLERK_PUBLISHABLE_KEY, CLERK_API_URL, CLERK_API_VERSION, CLERK_DOMAIN, CLERK_PROXY_URL, CLERK_SIGN_IN_URL, CLERK_IS_SATELLITE, CLERK_MACHINE_SECRET_KEY (src express/src/utils.ts); Fastify reads only CLERK_API_VERSION, CLERK_SECRET_KEY, CLERK_MACHINE_SECRET_KEY, CLERK_PUBLISHABLE_KEY, CLERK_API_URL, CLERK_JWT_KEY (src fastify/src/constants.ts).
    • Checks (src jwt/verifyJwt.ts, jwt/assertions.ts): header typ and alg (RS256 family), signature, exp (expired when exp <= now - clockSkew), nbf, iat (each with clockSkewInMs, default DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000), azp against authorizedParties ("Once authorized parties are configured the azp claim must be present and match one of them"; with none configured an azp-less token is accepted and logger.warnOnce logs "Session token from cookie is missing the azp claim. In a future version of Clerk, this token will be considered invalid"), aud only if both audience option and aud claim exist ("Clerk JWTs use AZP claim instead of Audience"), sub must be a string. Tokens whose header cat marks them as M2M are rejected by verifyToken; the cookie path additionally rejects isMachineJwt / hasNonSessionJwtCategory tokens with reason token-type-mismatch (src request.ts).
    • Lifetime and refresh: the session token "Expiration: 60 seconds"; ClerkJS refreshes it "on a 50-second interval (allowing 10 seconds for network latency)"; Clerk "decouple[s] token expiration from session lifetime" [overview]. The session-tokens page says exp is "Determined using the Token lifetime JWT template setting", which the overview does not mention; treat 60 s as the default and confirm on the instance [https://clerk.com/docs/guides/sessions/session-tokens]. Session (not token) lifetime is a Dashboard-only setting: inactivity timeout "disabled" by default; maximum lifetime "enabled with a default value of 7 days for all newly created instances"; "Either one or both must be enabled at all times" [https://clerk.com/docs/guides/secure/session-options]. A revoked session's already-issued JWT stays cryptographically valid until exp; the revoke docs do not say this in as many words (unverified as an explicit sentence; it follows from local verification).
    • Server-side refresh without redirect exists only for GET requests carrying a suffixed __refresh cookie and an expired token: apiClient.sessions.refreshSession(sid, { format: 'cookie', suffixed_cookies, expired_token, refresh_token, request_origin, request_headers }) (BAPI, network) and its Set-Cookie headers ride on the signed-in state (src request.ts refreshToken, attemptRefresh).

    5. Default claims and getting email/name in

    • Session token v2 default claims: azp ("The Origin header that was included in the original Frontend API request made from the user"), exp, fva, iat, iss ("The Frontend API URL of your instance"), jti, nbf, sid, sub (user ID), v (2), pla, fea, sts, o ({ id, slg, rol, per, fpm }, only with an active organization), act (impersonation) [https://clerk.com/docs/guides/sessions/session-tokens]. No email or name by default.
    • Customization: Dashboard > Sessions page > "Customize session token" Claims editor, a JSON claims editor; shortcodes include {{user.primary_email_address}}, {{user.full_name}}, {{user.first_name}}, {{user.last_name}}, {{user.image_url}}, {{user.id}}, {{user.email_verified}}, {{user.public_metadata}}; example { "fullName": "{{user.full_name}}", "primaryEmail": "{{user.primary_email_address}}" }; "After accounting for the size of Clerk's default claims, the cookie can support up to 1.2KB of custom claims"; read them on the server from toAuth().sessionClaims.<name> [https://clerk.com/docs/guides/sessions/customize-session-tokens, https://clerk.com/docs/guides/sessions/jwt-templates]. Reserved: azp exp iat iss jti nbf sub "cannot be overridden by templates" [jwt-templates]. Custom claims are untyped on JwtPayload; the server should decode them with a schema.

    6. Domain constraint

    • Production: the Frontend API is hosted on a subdomain of your application (e.g. clerk.example.com) via CNAME, making app and FAPI "same-site" [overview]; Account Portal at https://accounts.<your-domain>/sign-in etc. [https://clerk.com/docs/guides/account-portal/getting-started]; "Clerk's authentication will work across all subdomains. User sessions will also be shared across the subdomains" and "By default, the Frontend API (FAPI) accepts cross-origin requests from any subdomain of your configured root domain" (a subdomain allowlist is recommended) [https://clerk.com/docs/guides/development/deployment/production]. __client_uat and (in production) __clerk_handshake live on the eTLD+1 (src, section 2). So the host serving /d/<id> must be the instance's root domain or a subdomain of it. Patchy serves API and pages from one host, which satisfies this.
    • Satellite domains are for a second registrable domain: "Your 'primary' domain is where the authentication state lives, and satellite domains are able to securely read that state from the primary domain"; users must complete sign-in and sign-up on the primary domain; options isSatellite, domain, signInUrl, signUpUrl, proxyUrl; "This feature requires a paid plan for production use, but all features are free to use in development mode" [https://clerk.com/docs/guides/dashboard/dns-domains/satellite-domains]; pricing (read 2026-09-02): Hobby free, Pro "$25/mo ($20/mo billed annually)", "Satellite domains (Additional $10/mo each)" [https://clerk.com/pricing]. Not needed for a single host.
    • Proxying FAPI through your own path (/__clerk; frontendApiProxy option in @clerk/express and Next; headers Clerk-Proxy-Url, Clerk-Secret-Key, X-Forwarded-For) is an alternative to the CNAME but "proxying does not work for Clerk development instances" [https://clerk.com/docs/guides/dashboard/dns-domains/proxy-fapi].
    • Development instance: no DNS; FAPI on clerk.accounts.dev, Account Portal on "a randomly generated domain on accounts.dev", the app on localhost, and "the development host (e.g., http://localhost:3000) is dynamically detected by Clerk at runtime and tied to your client browser" [account-portal/getting-started]. Account Portal redirect_url "must be a URL on your instance's domain or one of its subdomains, or share the same origin as the requesting page (which is why localhost works in development)" [https://clerk.com/docs/guides/account-portal/direct-links]. The login door therefore links to https://<slug>.accounts.dev/sign-in?redirect_url=<absolute patch URL> in dev and https://accounts.<root>/sign-in?redirect_url=... in production.

    7. Sign-out from a server-rendered page with no ClerkJS

    • There is no Account Portal sign-out page in the docs: getting-started lists /sign-in, /sign-up, /user, /unauthorized-sign-in, /organization, /create-organization; direct-links only documents the https://accounts.<your-domain.com>/<account-portal-page>?redirect_url=<your-redirect-url> format with a sign-in example [account-portal/getting-started, direct-links]. FAPI has DELETE /v1/client ("Ends all Sessions of the Current Client"), DELETE /v1/client/sessions ("Removes all the sessions of the current client without removing the __client cookie"), POST /v1/client/sessions/{session_id}/end, POST /v1/client/sessions/{session_id}/remove [fapi/2026-05-12.yml]; they authenticate with the __client cookie (ProductionBrowser scheme) or the dev browser token as query __dev_session (DevBrowser scheme), i.e. from the browser, and cannot be issued by an HTML form (DELETE) or without script (POST needs the dev-browser query in dev). Unverified: whether a plain <form method="post"> to /v1/client/sessions/{sid}/end on the FAPI origin works in production (__client is SameSite=Lax; a cross-site top-level POST would not send it).
    • Practical path for a plain server: a POST to your own route that (a) calls BAPI POST /sessions/{session_id}/revoke (clerkClient.sessions.revokeSession(sessionId): Promise<Session>: "Revokes the given session. The user will be signed out from the client the session is associated with") [https://clerk.com/docs/reference/backend/sessions/revoke-session] using sessionId from toAuth(), and (b) clears __session and its suffixed twin and sets __client_uat=0 (both names) on the eTLD+1 in the response, then redirects. Note signedOut() in the SDK only passes through headers it is given and never generates cookie-clearing directives (src authStatus.ts), so the server must expire its own cookies; the revoked JWT stays cryptographically valid until exp (<= 60 s). The next document request with __client_uat=0 and no __session yields signed-out (session-token-and-uat-missing) without a handshake; if the user later signs in again on the Account Portal, section 3's first-visit flow re-establishes cookies.

    8. Worked examples and versions

    • @clerk/express: clerkMiddleware(options) converts the request (incomingMessageToRequest), calls authenticateRequest with acceptsToken: 'any' (set in clerkMiddleware.ts, not in authenticateRequest.ts), appends every requestState.headers entry, ends with 307 when location is set, otherwise attaches req.auth; getAuth(req) reads it; requireAuth "is now deprecated. For new route protection, use clerkMiddleware() with getAuth() instead" [https://clerk.com/docs/reference/express/overview, https://clerk.com/docs/reference/express/clerk-middleware; src]. Options mirror section 1 (publishableKey, secretKey, jwtKey, authorizedParties, clockSkewInMs "Defaults to 5000 ms (5 seconds)", audience, signInUrl, signUpUrl, domain, isSatellite, proxyUrl, debug "Defaults to false", frontendApiProxy, organizationSyncOptions). Peer express ^4.17.0 || ^5.0.0, engines.node >=20.9.0 (src package.json on main and npm latest, version 2.1.65).
    • @clerk/fastify: fastify.register(clerkPlugin, { hookName: 'preHandler' (default; or 'onRequest'), secretKey, publishableKey, jwtKey, domain, isSatellite, proxyUrl, apiUrl, ... }) builds its own createClerkClient and does the same header/307 dance with acceptsToken: 'any'; getAuth(request) [https://clerk.com/docs/reference/fastify/clerk-plugin; src]. Peer fastify >=5, engines.node >=20.9.0 (src and npm, version 3.1.75).
    • @clerk/backend: npm latest is 3.17.0 (read 2026-09-02), engines.node >=20.9.0, deps @clerk/shared ^4.30.2, standardwebhooks ^1.0.0, tslib 2.8.1 [https://registry.npmjs.org/@clerk/backend/latest]. createClerkClient({ secretKey, publishableKey, jwtKey?, apiUrl?, apiVersion?, domain?, isSatellite?, proxyUrl?, ... }).authenticateRequest(req, opts) is the plain-server entry point [https://clerk.com/docs/reference/backend/overview]. Node 22 satisfies the engine range.

    Open questions

    1. azp on handshake-minted tokens. azp is the Origin of the FAPI request, but a handshake is a top-level navigation that sends no Origin, and with authorizedParties configured a missing azp fails verification (src assertAuthorizedPartiesClaim). Whether FAPI fills azp from redirect_url is unverified; test on the dev instance before turning authorizedParties on, or the handshake loops to signed-out.
    2. format=nonce means every handshake completion calls BAPI with the secret key, so jwtKey does not make the login door networkless. Whether FAPI honours format=token when asked (the spec's default is token; the SDK hard-codes nonce) is unverified.
    3. Domain attribute of the Set-Cookie directives FAPI returns in the handshake payload (host-only vs eTLD+1 for __session) is FAPI-side and unverified; it decides whether __session leaks to sibling subdomains.
    4. Whether the handshake payload in production also expires the __clerk_handshake cookie, or the server should clear it after resolveHandshake (src does not).
    5. How the Account Portal decides the "requesting page" origin for redirect_url on a first visit from a plain server (Referer?), and whether a Patchy page URL with a query string round-trips intact.
    6. The docs' "how Clerk works" page and the SDK disagree on __client_uat scope in dev (SameSite=Strict, eTLD+1) vs the docs' "app domain, scoped strictly" for __session; the src is authoritative for what the backend expects. The session-tokens page's "Token lifetime JWT template setting" for exp versus the overview's flat 60 s is a second doc discrepancy.
    7. Converting an Effect HttpServerRequest (effect/unstable/http) to a Fetch Request with body-less headers and cookies; both official SDKs hand-build one from the Node request, and nothing here was verified against Effect.
    8. Session token sts: 'pending' (organisation tasks) is treated as signed out by default; decide whether Patchy ever enables organisations in Clerk or keeps companies entirely in Postgres.

    Verification

    Checked on 2026-09-02 against the cited primary sources: every packages/backend, packages/express, packages/fastify, packages/clerk-js and packages/shared file named above on clerk/javascript@main (versions 3.17.0 / 2.1.65 / 3.1.75, matching npm latest), clerk/openapi-specs fapi/2026-05-12.yml, the npm registry, and the clerk.com docs pages cited inline plus the SDK-development terminology and fullstack pages.

    Confirmed unchanged: the authenticateRequest contract and handshake headers (claim 1); handshake eligibility, redirect URL and completion (claim 2); cookie placement, attributes and suffixing (claim 4); key loading, JWKS cache, clock skew and azp rule (claim 5); default claims and customization (claim 6); sign-out endpoints and the BAPI revoke path (claim 7); versions, engines and the wrappers' behaviour (claim 8).

    Changed: (a) the signed-out reason for an expired token on a non-document request is session-token-expired-refresh-<refreshError> (e.g. ...-non-eligible-no-refresh-cookie), not bare session-token-expired; (b) two reason strings corrected to client-uat-but-no-session-token and session-token-but-no-client-uat; (c) the quoted "encoded either in the URL (development) or as a cookie (production)..." sentence exists on none of the sources and is replaced by the source-backed statement, marked unverified in prose; (d) the Account Portal page list comes from getting-started, not direct-links; (e) Fastify reads a smaller env-var set than Express; (f) the fastify error text differs from express's; (g) express's acceptsToken: 'any' lives in clerkMiddleware.ts; (h) authorizedParties docs wording corrected to the actual text; (i) noted the session-tokens page's "Token lifetime JWT template setting" wording for exp.

    Still unverifiable from primary sources: FAPI's azp on handshake-minted tokens; whether FAPI honours format=token; the Domain attribute FAPI puts on handshake Set-Cookie directives; when FAPI sets __refresh; whether the revoked JWT's validity-until-exp is stated anywhere in docs; the clerk.ts decorateUrlWithDevBrowserToken behaviour (cited by the original researcher, not re-read here).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

wayfinder:research

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions