Skip to content
Open
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 an issue where secrets passed directly to clerkPlugin() were not used when verifying sessions, causing authentication failures when keys are loaded at runtime. The runtime-key Clerk client is also now available on `request.clerk`.
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();
});
});
82 changes: 76 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,38 @@ 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('handles signin with Authorization Bearer', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
Expand Down Expand Up @@ -142,6 +178,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

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.

}

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

/**
Expand Down
19 changes: 15 additions & 4 deletions packages/fastify/src/withClerkMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
import { createClerkClient } from '@clerk/backend';
import { AuthStatus } from '@clerk/backend/internal';
import { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';
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 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 clerkClient = createClerkClient({
...options,
publishableKey,
secretKey,
machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,
apiUrl: options.apiUrl || constants.API_URL,
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 +103,6 @@ export const withClerkMiddleware = (options: ClerkFastifyOptions) => {

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