-
Notifications
You must be signed in to change notification settings - Fork 460
chore(nextjs): Add support for pages router when verifying webhooks #5618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
wobsoriano
merged 7 commits into
main
from
rob/eco-571-widen-type-support-for-nextjs-verifywebhook-request-param-by
Apr 14, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ab476cc
chore(nextjs): Add support for pages router when verifying webhooks
wobsoriano f560f2a
chore(nextjs): Add custom verify webhook unit test
wobsoriano 30c637b
chore: clean up
wobsoriano 742b87f
chore: revert exported type
wobsoriano 205a40c
Merge branch 'main' into rob/eco-571-widen-type-support-for-nextjs-ve…
wobsoriano c1d3b46
chore: add changeset
wobsoriano e6a0538
chore: update changeset
wobsoriano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| --- | ||
| '@clerk/nextjs': patch | ||
| --- | ||
|
|
||
| Add support for webhook verification with Next.js Pages Router. | ||
|
|
||
| ```ts | ||
| // Next.js Pages Router | ||
| import type { NextApiRequest, NextApiResponse } from 'next' | ||
| import { verifyWebhook } from '@clerk/nextjs/webhooks'; | ||
|
|
||
| export const config = { | ||
| api: { | ||
| bodyParser: false, | ||
| }, | ||
| } | ||
|
|
||
| export default async function handler( | ||
| req: NextApiRequest, | ||
| res: NextApiResponse | ||
| ) { | ||
| try { | ||
| const evt = await verifyWebhook(req); | ||
| // Handle webhook event | ||
| res.status(200).json({ received: true }); | ||
| } catch (err) { | ||
| res.status(400).json({ error: 'Webhook verification failed' }); | ||
| } | ||
| } | ||
|
|
||
| // tRPC | ||
| import { verifyWebhook } from '@clerk/nextjs/webhooks'; | ||
|
|
||
| const webhookRouter = router({ | ||
| webhook: publicProcedure | ||
| .input(/** schema */) | ||
| .mutation(async ({ ctx }) => { | ||
| const evt = await verifyWebhook(ctx.req); | ||
| // Handle webhook event | ||
| return { received: true }; | ||
| }), | ||
| }); | ||
| ``` |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import type { NextApiRequest } from 'next'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import type { RequestLike } from '../server/types'; | ||
| import { verifyWebhook } from '../webhooks'; | ||
|
|
||
| const mockSuccessResponse = { | ||
| type: 'user.created', | ||
| data: { id: 'user_123' }, | ||
| object: 'event', | ||
| } as any; | ||
|
|
||
| const mockError = new Error('Missing required Svix headers: svix-id, svix-timestamp, svix-signature'); | ||
|
|
||
| vi.mock('@clerk/backend/webhooks', () => ({ | ||
| verifyWebhook: vi.fn().mockImplementation((request: Request) => { | ||
| const svixId = request.headers.get('svix-id'); | ||
| const svixTimestamp = request.headers.get('svix-timestamp'); | ||
| const svixSignature = request.headers.get('svix-signature'); | ||
|
|
||
| if (!svixId || !svixTimestamp || !svixSignature) { | ||
| throw mockError; | ||
| } | ||
|
|
||
| return mockSuccessResponse; | ||
| }), | ||
| })); | ||
|
|
||
| describe('verifyWebhook', () => { | ||
| const mockSecret = 'test_signing_secret'; | ||
| const mockBody = JSON.stringify(mockSuccessResponse); | ||
| const mockHeaders = { | ||
| 'svix-id': 'msg_123', | ||
| 'svix-timestamp': '1614265330', | ||
| 'svix-signature': 'v1,test_signature', | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| process.env.CLERK_WEBHOOK_SIGNING_SECRET = mockSecret; | ||
| }); | ||
|
|
||
| describe('with standard Request', () => { | ||
| it('verifies webhook with standard Request object', async () => { | ||
| const mockRequest = new Request('https://clerk.com/webhooks', { | ||
| method: 'POST', | ||
| body: mockBody, | ||
| headers: new Headers(mockHeaders), | ||
| }) as unknown as RequestLike; | ||
|
|
||
| const result = await verifyWebhook(mockRequest); | ||
| expect(result).toEqual(mockSuccessResponse); | ||
| }); | ||
| }); | ||
|
|
||
| describe('with NextApiRequest', () => { | ||
| it('verifies webhook with NextApiRequest object', async () => { | ||
| const mockNextApiRequest = { | ||
| method: 'POST', | ||
| url: '/webhooks', | ||
| headers: { | ||
| ...mockHeaders, | ||
| host: 'clerk.com', | ||
| 'x-forwarded-proto': 'https', | ||
| }, | ||
| body: JSON.parse(mockBody), | ||
| query: {}, | ||
| cookies: {}, | ||
| env: {}, | ||
| aborted: false, | ||
| } as unknown as NextApiRequest; | ||
|
|
||
| const result = await verifyWebhook(mockNextApiRequest); | ||
| expect(result).toEqual(mockSuccessResponse); | ||
| }); | ||
|
|
||
| it('throws error when headers are missing', async () => { | ||
| const mockNextApiRequest = { | ||
| method: 'POST', | ||
| url: '/webhooks', | ||
| headers: { | ||
| host: 'clerk.com', | ||
| 'x-forwarded-proto': 'https', | ||
| }, | ||
| body: JSON.parse(mockBody), | ||
| query: {}, | ||
| cookies: {}, | ||
| env: {}, | ||
| aborted: false, | ||
| } as unknown as NextApiRequest; | ||
|
|
||
| await expect(verifyWebhook(mockNextApiRequest)).rejects.toThrow(mockError); | ||
| }); | ||
| }); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,81 @@ | ||
| /* eslint-disable import/export */ | ||
| import type { VerifyWebhookOptions } from '@clerk/backend/webhooks'; | ||
| import { verifyWebhook as verifyWebhookBase } from '@clerk/backend/webhooks'; | ||
|
|
||
| import { getHeader, isNextRequest, isRequestWebAPI } from './server/headers-utils'; | ||
| import type { RequestLike } from './server/types'; | ||
| // Ordering of exports matter here since | ||
| // we're overriding the base verifyWebhook | ||
| export * from '@clerk/backend/webhooks'; | ||
|
|
||
| const SVIX_ID_HEADER = 'svix-id'; | ||
| const SVIX_TIMESTAMP_HEADER = 'svix-timestamp'; | ||
| const SVIX_SIGNATURE_HEADER = 'svix-signature'; | ||
|
|
||
| /** | ||
| * Verifies the authenticity of a webhook request using Svix. | ||
| * | ||
| * @param request - The incoming webhook request object | ||
| * @param options - Optional configuration object | ||
| * @param options.signingSecret - Custom signing secret. If not provided, falls back to CLERK_WEBHOOK_SIGNING_SECRET env variable | ||
| * @throws Will throw an error if the webhook signature verification fails | ||
| * @returns A promise that resolves to the verified webhook event data | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { verifyWebhook } from '@clerk/nextjs/webhooks'; | ||
| * | ||
| * export async function POST(req: Request) { | ||
| * try { | ||
| * const evt = await verifyWebhook(req); | ||
| * | ||
| * // Access the event data | ||
| * const { id } = evt.data; | ||
| * const eventType = evt.type; | ||
| * | ||
| * // Handle specific event types | ||
| * if (evt.type === 'user.created') { | ||
| * console.log('New user created:', evt.data.id); | ||
| * // Handle user creation | ||
| * } | ||
| * | ||
| * return new Response('Success', { status: 200 }); | ||
| * } catch (err) { | ||
| * console.error('Webhook verification failed:', err); | ||
| * return new Response('Webhook verification failed', { status: 400 }); | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| export async function verifyWebhook(request: RequestLike, options?: VerifyWebhookOptions) { | ||
| if (isNextRequest(request) || isRequestWebAPI(request)) { | ||
| return verifyWebhookBase(request, options); | ||
| } | ||
|
|
||
| const webRequest = nextApiRequestToWebRequest(request); | ||
| return verifyWebhookBase(webRequest, options); | ||
| } | ||
|
|
||
| function nextApiRequestToWebRequest(req: RequestLike): Request { | ||
| const headers = new Headers(); | ||
| const svixId = getHeader(req, SVIX_ID_HEADER) || ''; | ||
| const svixTimestamp = getHeader(req, SVIX_TIMESTAMP_HEADER) || ''; | ||
| const svixSignature = getHeader(req, SVIX_SIGNATURE_HEADER) || ''; | ||
|
|
||
| headers.set(SVIX_ID_HEADER, svixId); | ||
| headers.set(SVIX_TIMESTAMP_HEADER, svixTimestamp); | ||
| headers.set(SVIX_SIGNATURE_HEADER, svixSignature); | ||
|
|
||
| // Create a dummy URL to make a Request object | ||
| const protocol = getHeader(req, 'x-forwarded-proto') || 'http'; | ||
| const host = getHeader(req, 'x-forwarded-host') || 'clerk-dummy'; | ||
| const dummyOriginReqUrl = new URL(req.url || '', `${protocol}://${host}`); | ||
|
|
||
| const body = 'body' in req && req.body ? JSON.stringify(req.body) : undefined; | ||
|
|
||
| return new Request(dummyOriginReqUrl, { | ||
| method: req.method, | ||
| headers, | ||
| body, | ||
| }); | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For standard web
Request, it uses the defaultverifyWebhookprovided by the backend SDK. ForNextApiRequesttype, we're converting it to aRequestbefore verifying