Skip to content
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/silent-fastify-handshakes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/fastify': patch
---

Fixed `clerkPlugin()` to honor `publishableKey` and `secretKey` passed in plugin options when authenticating Fastify requests. The plugin now also exposes `request.clerk`, which uses the same plugin keys and resolves the correct Clerk API host for non-production publishable keys.
3 changes: 2 additions & 1 deletion packages/fastify/src/__tests__/clerkPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,14 @@ describe('clerkPlugin()', () => {
},
);

test('adds auth decorator', () => {
test('adds request decorators', () => {
const doneFn = vi.fn();
const fastify = createFastifyInstanceMock();

clerkPlugin(fastify, {}, doneFn);

expect(fastify.decorateRequest).toHaveBeenCalledWith('auth', null);
expect(fastify.decorateRequest).toHaveBeenCalledWith('clerk', null);
expect(doneFn).toHaveBeenCalled();
});
});
113 changes: 107 additions & 6 deletions packages/fastify/src/__tests__/withClerkMiddleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@ import { beforeEach, describe, expect, test, vi } from 'vitest';

import { clerkPlugin, getAuth } from '../index';

const authenticateRequestMock = vi.fn();
const { authenticateRequestMock, createClerkClientMock, mockClerkClient } = vi.hoisted(() => {
const authenticateRequestMock = vi.fn();
const mockClerkClient = {
authenticateRequest: (...args: any) => authenticateRequestMock(...args),
};
const createClerkClientMock = vi.fn(() => mockClerkClient);

return { authenticateRequestMock, createClerkClientMock, mockClerkClient };
});

vi.mock('@clerk/backend', async () => {
const actual = await vi.importActual('@clerk/backend');
return {
...actual,
createClerkClient: () => {
return {
authenticateRequest: (...args: any) => authenticateRequestMock(...args),
};
},
createClerkClient: (...args: any[]) => createClerkClientMock(...args),
};
});

Expand All @@ -24,6 +28,69 @@ describe('withClerkMiddleware(options)', () => {
vi.restoreAllMocks();
});

test('creates the request client with plugin runtime keys', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: () => ({
tokenType: 'session_token',
}),
});
const fastify = Fastify();
await fastify.register(clerkPlugin, {
secretKey: 'runtime_secret_key',
publishableKey: 'runtime_publishable_key',
});

fastify.get('/', (request: FastifyRequest, reply: FastifyReply) => {
const auth = getAuth(request);
reply.send({ auth });
});

const response = await fastify.inject({
method: 'GET',
path: '/',
});

expect(response.statusCode).toEqual(200);
expect(createClerkClientMock).toHaveBeenLastCalledWith(
expect.objectContaining({
secretKey: 'runtime_secret_key',
publishableKey: 'runtime_publishable_key',
}),
);
});

test('creates the request client with an apiUrl derived from the runtime publishable key', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: () => ({
tokenType: 'session_token',
}),
});
const fastify = Fastify();
await fastify.register(clerkPlugin, {
secretKey: 'runtime_secret_key',
publishableKey: 'pk_test_aW1tdW5lLWhhd2stNjUuY2xlcmsuYWNjb3VudHNzdGFnZS5kZXYk',
});

fastify.get('/', (_request: FastifyRequest, reply: FastifyReply) => {
reply.send({});
});

const response = await fastify.inject({
method: 'GET',
path: '/',
});

expect(response.statusCode).toEqual(200);
expect(createClerkClientMock).toHaveBeenLastCalledWith(
expect.objectContaining({
apiUrl: 'https://api.clerkstage.dev',
publishableKey: 'pk_test_aW1tdW5lLWhhd2stNjUuY2xlcmsuYWNjb3VudHNzdGFnZS5kZXYk',
}),
);
});

test('handles signin with Authorization Bearer', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
Expand Down Expand Up @@ -142,6 +209,40 @@ describe('withClerkMiddleware(options)', () => {
});
});

test('exposes the runtime key clerk client instance on request.clerk', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: () => ({
tokenType: 'session_token',
}),
});
const fastify = Fastify();
await fastify.register(clerkPlugin, {
secretKey: 'runtime_secret_key',
publishableKey: 'runtime_publishable_key',
});

let clerkOnRequest: unknown;
fastify.get('/', (request: FastifyRequest, reply: FastifyReply) => {
clerkOnRequest = request.clerk;
reply.send({});
});

const response = await fastify.inject({
method: 'GET',
path: '/',
});

expect(response.statusCode).toEqual(200);
expect(clerkOnRequest).toBe(mockClerkClient);
expect(createClerkClientMock).toHaveBeenLastCalledWith(
expect.objectContaining({
secretKey: 'runtime_secret_key',
publishableKey: 'runtime_publishable_key',
}),
);
});

test('handles signout case by populating the req.auth', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
Expand Down
2 changes: 2 additions & 0 deletions packages/fastify/src/clerkPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const plugin: FastifyPluginCallback<ClerkFastifyOptions> = (
done,
) => {
instance.decorateRequest('auth', null);
instance.decorateRequest('clerk', null as any);

// run clerk as a middleware to all scoped routes
const hookName = opts.hookName || 'preHandler';
if (!ALLOWED_HOOKS.includes(hookName)) {
Expand Down
8 changes: 7 additions & 1 deletion packages/fastify/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { ClerkOptions } from '@clerk/backend';
import type { ClerkClient, ClerkOptions } from '@clerk/backend';
import type { ShouldProxyFn } from '@clerk/shared/proxy';

declare module 'fastify' {
interface FastifyRequest {
clerk: ClerkClient;
}
Comment on lines +4 to +7
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot May 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the type/decorator contract mismatch locations
rg -n "interface FastifyRequest|clerk:\\s*ClerkClient|decorateRequest\\('clerk'" packages/fastify/src/types.ts packages/fastify/src/clerkPlugin.ts

Repository: clerk/javascript

Length of output: 259


Fix FastifyRequest.clerk type to match decorateRequest initialization

packages/fastify/src/types.ts declares FastifyRequest.clerk: ClerkClient, but packages/fastify/src/clerkPlugin.ts initializes it via instance.decorateRequest('clerk', null);, creating a compile-time type contract mismatch. Align the runtime value with the augmented type (e.g., make it nullable).

Suggested minimal fix
 declare module 'fastify' {
   interface FastifyRequest {
-    clerk: ClerkClient;
+    clerk: ClerkClient | null;
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
declare module 'fastify' {
interface FastifyRequest {
clerk: ClerkClient;
}
declare module 'fastify' {
interface FastifyRequest {
clerk: ClerkClient | null;
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/fastify/src/types.ts` around lines 4 - 7, The FastifyRequest
augmentation declares clerk as ClerkClient but the runtime plugin calls
instance.decorateRequest('clerk', null); causing a type mismatch—change the
augmented type to allow null (e.g., FastifyRequest.clerk: ClerkClient | null) so
it matches the decorateRequest initialization; update the declaration in
types.ts referencing FastifyRequest.clerk and ensure any code using clerk
handles the nullable type or narrows it before use.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From Fastify Decorator docs:

Keep the initial shape of a decorated field close to its future dynamic value. Initialize a decorator as '' for strings and null for objects or functions.

So this is just a placehodler required by Fastify API and the value is always set to the actual ClerkClient before any route handler runs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wobsoriano, that makes sense — the null initialization is purely a Fastify/V8 optimization hint and not a value that consumers ever see. The non-nullable clerk: ClerkClient type is correct. Sorry for the noise!


✏️ Learnings added
Learnt from: wobsoriano
Repo: clerk/javascript PR: 8640
File: packages/fastify/src/types.ts:4-7
Timestamp: 2026-05-29T20:36:33.106Z
Learning: In the Fastify integration (`packages/fastify/src/clerkPlugin.ts` and `packages/fastify/src/types.ts`), `instance.decorateRequest('clerk', null)` uses `null` as a required Fastify API placeholder (V8 shape hint) — not a runtime null. The `clerk` property is always assigned to a real `ClerkClient` before any route handler executes, so `FastifyRequest.clerk: ClerkClient` (non-nullable) is the correct type augmentation. Do not flag this as a type mismatch.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wobsoriano
Repo: clerk/javascript PR: 7883
File: packages/backend/src/api/__tests__/M2MTokenApi.test.ts:414-419
Timestamp: 2026-02-24T18:03:27.067Z
Learning: In TypeScript files within the clerk/javascript repository, enforce explicit return type annotations for exported functions and public APIs, but allow internal test helper functions without explicit return types. This helps maintain API clarity and type safety for consumers while not burdening test helpers that are not part of the public surface.

}

export const ALLOWED_HOOKS = ['onRequest', 'preHandler'] as const;

/**
Expand Down
23 changes: 18 additions & 5 deletions packages/fastify/src/withClerkMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
import { createClerkClient } from '@clerk/backend';
import { AuthStatus } from '@clerk/backend/internal';
import { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';
import { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { Readable } from 'stream';

import { clerkClient } from './clerkClient';
import * as constants from './constants';
import type { ClerkFastifyOptions } from './types';
import { fastifyRequestToRequest, requestToProxyRequest } from './utils';

export const withClerkMiddleware = (options: ClerkFastifyOptions) => {
const frontendApiProxy = options.frontendApiProxy;
const { hookName: _hookName, frontendApiProxy, ...clerkOptions } = options;
const proxyPath = stripTrailingSlashes(frontendApiProxy?.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;
const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;
const secretKey = options.secretKey || constants.SECRET_KEY;
const apiUrl = options.apiUrl || apiUrlFromPublishableKey(publishableKey);
const clerkClient = createClerkClient({
...clerkOptions,
publishableKey,
secretKey,
machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,
apiUrl,
apiVersion: options.apiVersion || constants.API_VERSION,
jwtKey: options.jwtKey || constants.JWT_KEY,
userAgent: options.userAgent || `${constants.SDK_METADATA.name}@${constants.SDK_METADATA.version}`,
sdkMetadata: options.sdkMetadata || constants.SDK_METADATA,
});

return async (fastifyRequest: FastifyRequest, reply: FastifyReply) => {
const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;
const secretKey = options.secretKey || constants.SECRET_KEY;

// Handle Frontend API proxy requests and auto-derive proxyUrl
let resolvedProxyUrl = options.proxyUrl;
if (frontendApiProxy) {
Expand Down Expand Up @@ -93,5 +105,6 @@ export const withClerkMiddleware = (options: ClerkFastifyOptions) => {

// @ts-expect-error Inject auth so getAuth can read it
fastifyRequest.auth = requestState.toAuth();
fastifyRequest.clerk = clerkClient;
};
};
Loading