From 1f7f44b5700c65604ed622ac8335de6bd0cf3b97 Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Thu, 3 Dec 2026 09:35:53 +0800 Subject: [PATCH 1/4] feat(hono): read the remaining Clerk environment variables in clerkMiddleware --- .changeset/hono-middleware-env-vars.md | 5 ++ .../src/__tests__/clerkMiddleware.test.ts | 77 ++++++++++++++++++- packages/hono/src/clerkMiddleware.ts | 26 ++++++- 3 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 .changeset/hono-middleware-env-vars.md diff --git a/.changeset/hono-middleware-env-vars.md b/.changeset/hono-middleware-env-vars.md new file mode 100644 index 00000000000..f27f34c75d2 --- /dev/null +++ b/.changeset/hono-middleware-env-vars.md @@ -0,0 +1,5 @@ +--- +'@clerk/hono': minor +--- + +`clerkMiddleware()` now reads `CLERK_JWT_KEY`, `CLERK_DOMAIN`, `CLERK_PROXY_URL`, `CLERK_IS_SATELLITE`, `CLERK_SIGN_IN_URL`, `CLERK_TELEMETRY_DISABLED` and `CLERK_TELEMETRY_DEBUG` from the environment, including Cloudflare Workers bindings. Options passed to `clerkMiddleware()` still take precedence. Setting `CLERK_JWT_KEY` lets the middleware verify session tokens without fetching the JWKS. diff --git a/packages/hono/src/__tests__/clerkMiddleware.test.ts b/packages/hono/src/__tests__/clerkMiddleware.test.ts index 2fcc7cf73a3..582e67cc1e8 100644 --- a/packages/hono/src/__tests__/clerkMiddleware.test.ts +++ b/packages/hono/src/__tests__/clerkMiddleware.test.ts @@ -1,5 +1,5 @@ import { Hono } from 'hono'; -import { beforeEach, describe, expect, test, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { clerkMiddleware, getAuth } from '../index'; @@ -174,6 +174,81 @@ describe('clerkMiddleware()', () => { expect(response.status).toEqual(500); }); + + describe('environment variables', () => { + const satelliteEnv = { + CLERK_JWT_KEY: 'jwt-key', + CLERK_DOMAIN: 'satellite.dev', + CLERK_PROXY_URL: 'https://example.com/__clerk', + CLERK_IS_SATELLITE: 'true', + CLERK_SIGN_IN_URL: 'https://primary.dev/sign-in', + }; + + const expectedOptions = { + jwtKey: 'jwt-key', + domain: 'satellite.dev', + proxyUrl: 'https://example.com/__clerk', + isSatellite: true, + signInUrl: 'https://primary.dev/sign-in', + }; + + const createApp = (options?: Parameters[0]) => { + authenticateRequestMock.mockResolvedValueOnce({ + headers: new Headers(), + toAuth: createMockSessionAuth, + }); + const app = new Hono(); + app.use('*', clerkMiddleware(options)); + app.get('/', c => c.json({ ok: true })); + return app; + }; + + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + test('reads satellite and JWT key settings from process.env', async () => { + Object.entries(satelliteEnv).forEach(([key, value]) => vi.stubEnv(key, value)); + + const response = await createApp().request(new Request('http://localhost/')); + + expect(response.status).toEqual(200); + expect(authenticateRequestMock).toHaveBeenCalledWith( + expect.any(Request), + expect.objectContaining(expectedOptions), + ); + }); + + test('reads satellite and JWT key settings from Cloudflare Workers bindings', async () => { + vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' }); + + const response = await createApp().request(new Request('http://localhost/'), undefined, { + ...EnvVariables, + ...satelliteEnv, + }); + + expect(response.status).toEqual(200); + expect(authenticateRequestMock).toHaveBeenCalledWith( + expect.any(Request), + expect.objectContaining(expectedOptions), + ); + }); + + test('prefers options passed to clerkMiddleware() over environment variables', async () => { + Object.entries(satelliteEnv).forEach(([key, value]) => vi.stubEnv(key, value)); + + const response = await createApp({ domain: 'other.dev', isSatellite: false }).request( + new Request('http://localhost/'), + ); + + expect(response.status).toEqual(200); + expect(authenticateRequestMock).toHaveBeenCalledWith( + expect.any(Request), + expect.objectContaining({ domain: 'other.dev', isSatellite: false }), + ); + }); + }); }); describe('Frontend API proxy handling', () => { diff --git a/packages/hono/src/clerkMiddleware.ts b/packages/hono/src/clerkMiddleware.ts index 67bf53686c5..8712ccfef16 100644 --- a/packages/hono/src/clerkMiddleware.ts +++ b/packages/hono/src/clerkMiddleware.ts @@ -3,6 +3,7 @@ import { createClerkClient } from '@clerk/backend'; import type { AuthenticateRequestOptions, AuthOptions, GetAuthFnNoRequest } from '@clerk/backend/internal'; import { getAuthObjectForAcceptedToken } from '@clerk/backend/internal'; import { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, matchProxyPath, stripTrailingSlashes } from '@clerk/backend/proxy'; +import { isTruthy } from '@clerk/shared/underscore'; import type { MiddlewareHandler } from 'hono'; import { env } from 'hono/adapter'; @@ -14,6 +15,14 @@ type ClerkEnv = { CLERK_MACHINE_SECRET_KEY?: string; CLERK_API_URL?: string; CLERK_API_VERSION?: string; + CLERK_JWT_KEY?: string; + CLERK_DOMAIN?: string; + CLERK_PROXY_URL?: string; + CLERK_IS_SATELLITE?: string; + CLERK_SIGN_IN_URL?: string; + CLERK_TELEMETRY_DISABLED?: string; + CLERK_TELEMETRY_DEBUG?: string; + NODE_ENV?: string; }; export type ClerkMiddlewareOptions = Omit & { @@ -47,6 +56,11 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan machineSecretKey = clerkEnv.CLERK_MACHINE_SECRET_KEY || '', apiUrl = clerkEnv.CLERK_API_URL, apiVersion = clerkEnv.CLERK_API_VERSION, + jwtKey = clerkEnv.CLERK_JWT_KEY, + domain = clerkEnv.CLERK_DOMAIN, + proxyUrl = clerkEnv.CLERK_PROXY_URL, + isSatellite = isTruthy(clerkEnv.CLERK_IS_SATELLITE), + signInUrl = clerkEnv.CLERK_SIGN_IN_URL, frontendApiProxy, ...rest } = options || {}; @@ -64,7 +78,7 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan } // Handle Frontend API proxy requests and auto-derive proxyUrl - let derivedProxyUrl = rest.proxyUrl; + let derivedProxyUrl = proxyUrl; if (frontendApiProxy) { const proxyPath = stripTrailingSlashes(frontendApiProxy.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH; const requestUrl = new URL(c.req.url); @@ -95,7 +109,13 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan secretKey, publishableKey, machineSecretKey, + jwtKey, userAgent: `${PACKAGE_NAME}@${PACKAGE_VERSION}`, + sdkMetadata: { name: PACKAGE_NAME, version: PACKAGE_VERSION, environment: clerkEnv.NODE_ENV }, + telemetry: { + disabled: isTruthy(clerkEnv.CLERK_TELEMETRY_DISABLED), + debug: isTruthy(clerkEnv.CLERK_TELEMETRY_DEBUG), + }, }); const requestState = await clerkClient.authenticateRequest(c.req.raw, { @@ -103,7 +123,11 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan secretKey, publishableKey, machineSecretKey, + jwtKey, + domain, proxyUrl: derivedProxyUrl, + isSatellite, + signInUrl, acceptsToken: 'any', }); From 72af79f66e19dc9727c2cdad8c931c8ffdfcdc35 Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Thu, 3 Dec 2026 09:38:15 +0800 Subject: [PATCH 2/4] chore(hono): tighten the changeset wording --- .changeset/hono-middleware-env-vars.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.changeset/hono-middleware-env-vars.md b/.changeset/hono-middleware-env-vars.md index f27f34c75d2..e69d92ba43f 100644 --- a/.changeset/hono-middleware-env-vars.md +++ b/.changeset/hono-middleware-env-vars.md @@ -2,4 +2,14 @@ '@clerk/hono': minor --- -`clerkMiddleware()` now reads `CLERK_JWT_KEY`, `CLERK_DOMAIN`, `CLERK_PROXY_URL`, `CLERK_IS_SATELLITE`, `CLERK_SIGN_IN_URL`, `CLERK_TELEMETRY_DISABLED` and `CLERK_TELEMETRY_DEBUG` from the environment, including Cloudflare Workers bindings. Options passed to `clerkMiddleware()` still take precedence. Setting `CLERK_JWT_KEY` lets the middleware verify session tokens without fetching the JWKS. +`clerkMiddleware()` now reads these environment variables from `process.env` or from Cloudflare Workers bindings: + +- `CLERK_JWT_KEY` +- `CLERK_DOMAIN` +- `CLERK_PROXY_URL` +- `CLERK_IS_SATELLITE` +- `CLERK_SIGN_IN_URL` +- `CLERK_TELEMETRY_DISABLED` +- `CLERK_TELEMETRY_DEBUG` + +An option passed to `clerkMiddleware()` overrides the matching variable. With `CLERK_JWT_KEY` set, the middleware verifies session tokens without fetching the JWKS. From 2c39ccc516467cb4007590990df1fe4fad492c99 Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Thu, 3 Dec 2026 09:52:11 +0800 Subject: [PATCH 3/4] fix(hono): configure the exposed client with the resolved settings --- .changeset/hono-middleware-env-vars.md | 2 +- .../src/__tests__/clerkMiddleware.test.ts | 44 +++++++++++++++++++ packages/hono/src/clerkMiddleware.ts | 3 ++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/.changeset/hono-middleware-env-vars.md b/.changeset/hono-middleware-env-vars.md index e69d92ba43f..e50ead30086 100644 --- a/.changeset/hono-middleware-env-vars.md +++ b/.changeset/hono-middleware-env-vars.md @@ -12,4 +12,4 @@ - `CLERK_TELEMETRY_DISABLED` - `CLERK_TELEMETRY_DEBUG` -An option passed to `clerkMiddleware()` overrides the matching variable. With `CLERK_JWT_KEY` set, the middleware verifies session tokens without fetching the JWKS. +An option passed to `clerkMiddleware()` overrides the matching variable. With `CLERK_JWT_KEY` set, the middleware verifies session tokens without fetching the JWKS when the key type matches the token's algorithm. diff --git a/packages/hono/src/__tests__/clerkMiddleware.test.ts b/packages/hono/src/__tests__/clerkMiddleware.test.ts index 582e67cc1e8..5d3406a57fe 100644 --- a/packages/hono/src/__tests__/clerkMiddleware.test.ts +++ b/packages/hono/src/__tests__/clerkMiddleware.test.ts @@ -18,6 +18,7 @@ const createMockSessionAuth = () => ({ }); const authenticateRequestMock = vi.fn(); +const createClerkClientMock = vi.fn(); const { mockClerkFrontendApiProxy } = vi.hoisted(() => ({ mockClerkFrontendApiProxy: vi.fn(), @@ -37,6 +38,7 @@ vi.mock(import('@clerk/backend'), async importOriginal => { return { ...original, createClerkClient(options: Parameters[0]) { + createClerkClientMock(options); const client = original.createClerkClient(options); vi.spyOn(client, 'authenticateRequest').mockImplementation(authenticateRequestMock); return client; @@ -248,6 +250,48 @@ describe('clerkMiddleware()', () => { expect.objectContaining({ domain: 'other.dev', isSatellite: false }), ); }); + + test("configures the client from c.get('clerk') with the same settings", async () => { + Object.entries(satelliteEnv).forEach(([key, value]) => vi.stubEnv(key, value)); + + const response = await createApp().request(new Request('http://localhost/')); + + expect(response.status).toEqual(200); + expect(createClerkClientMock).toHaveBeenCalledWith( + expect.objectContaining({ + jwtKey: 'jwt-key', + domain: 'satellite.dev', + proxyUrl: 'https://example.com/__clerk', + isSatellite: true, + }), + ); + }); + + test.each([ + { flags: {}, isEnabled: true, isDebug: false }, + { flags: { CLERK_TELEMETRY_DISABLED: '1', CLERK_TELEMETRY_DEBUG: '1' }, isEnabled: false, isDebug: true }, + { flags: { CLERK_TELEMETRY_DISABLED: 'false', CLERK_TELEMETRY_DEBUG: 'false' }, isEnabled: true, isDebug: false }, + ])('reads telemetry flags $flags from Cloudflare Workers bindings', async ({ flags, isEnabled, isDebug }) => { + vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' }); + authenticateRequestMock.mockResolvedValueOnce({ + headers: new Headers(), + toAuth: createMockSessionAuth, + }); + const app = new Hono(); + app.use('*', clerkMiddleware()); + app.get('/', c => { + const { telemetry } = c.get('clerk'); + return c.json({ isEnabled: telemetry.isEnabled, isDebug: telemetry.isDebug }); + }); + + const response = await app.request(new Request('http://localhost/'), undefined, { + CLERK_SECRET_KEY: 'sk_test_secret', + CLERK_PUBLISHABLE_KEY: `pk_test_${btoa('example.clerk.accounts.dev$')}`, + ...flags, + }); + + expect(await response.json()).toEqual({ isEnabled, isDebug }); + }); }); }); diff --git a/packages/hono/src/clerkMiddleware.ts b/packages/hono/src/clerkMiddleware.ts index 8712ccfef16..1bfcea02c5f 100644 --- a/packages/hono/src/clerkMiddleware.ts +++ b/packages/hono/src/clerkMiddleware.ts @@ -110,6 +110,9 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan publishableKey, machineSecretKey, jwtKey, + domain, + proxyUrl: derivedProxyUrl, + isSatellite, userAgent: `${PACKAGE_NAME}@${PACKAGE_VERSION}`, sdkMetadata: { name: PACKAGE_NAME, version: PACKAGE_VERSION, environment: clerkEnv.NODE_ENV }, telemetry: { From 80d94fbfa16ad2c1e0f7c3f7be3e62d6d2905f7a Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Fri, 4 Dec 2026 04:31:50 +0800 Subject: [PATCH 4/4] test(hono): clear shell telemetry flags in the telemetry tests --- packages/hono/src/__tests__/clerkMiddleware.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/hono/src/__tests__/clerkMiddleware.test.ts b/packages/hono/src/__tests__/clerkMiddleware.test.ts index 5d3406a57fe..c86a1b6bdc5 100644 --- a/packages/hono/src/__tests__/clerkMiddleware.test.ts +++ b/packages/hono/src/__tests__/clerkMiddleware.test.ts @@ -272,6 +272,8 @@ describe('clerkMiddleware()', () => { { flags: { CLERK_TELEMETRY_DISABLED: '1', CLERK_TELEMETRY_DEBUG: '1' }, isEnabled: false, isDebug: true }, { flags: { CLERK_TELEMETRY_DISABLED: 'false', CLERK_TELEMETRY_DEBUG: 'false' }, isEnabled: true, isDebug: false }, ])('reads telemetry flags $flags from Cloudflare Workers bindings', async ({ flags, isEnabled, isDebug }) => { + vi.stubEnv('CLERK_TELEMETRY_DISABLED', ''); + vi.stubEnv('CLERK_TELEMETRY_DEBUG', ''); vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' }); authenticateRequestMock.mockResolvedValueOnce({ headers: new Headers(),