Skip to content

Commit e549911

Browse files
chore(express): Improve webhook verification DX (#6284)
Co-authored-by: Robert Soriano <[email protected]>
1 parent 404e668 commit e549911

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

.changeset/four-stingrays-cheat.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@clerk/express": patch
3+
---
4+
5+
Make webhook verification work with both raw and parsed request bodies

packages/express/src/webhooks.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ export * from '@clerk/backend/webhooks';
2121
* @example
2222
* ```typescript
2323
* import { verifyWebhook } from '@clerk/express/webhooks';
24-
* import express from 'express';
2524
*
26-
* app.post('/api/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
25+
* app.post('/api/webhooks', async (req, res) => {
2726
* try {
2827
* const evt = await verifyWebhook(req);
2928
* // handle event
@@ -40,8 +39,23 @@ export async function verifyWebhook(req: ExpressRequest, options?: VerifyWebhook
4039
const webRequest = incomingMessageToRequest(req);
4140
// Cloning instead of implementing the body inside incomingMessageToRequest
4241
// to make it more predictable
42+
// we must pass in body as string not as an Object or Buffer
43+
let serializedBody: string;
44+
if (typeof req.body === 'string') {
45+
serializedBody = req.body;
46+
} else if (Buffer.isBuffer(req.body)) {
47+
serializedBody = req.body.toString('utf8');
48+
} else if (req.body === undefined || req.body === null) {
49+
serializedBody = '';
50+
} else {
51+
try {
52+
serializedBody = JSON.stringify(req.body);
53+
} catch (error) {
54+
throw new Error(`Failed to serialize request body: ${error instanceof Error ? error.message : 'Unknown error'}`);
55+
}
56+
}
4357
const clonedRequest = new Request(webRequest, {
44-
body: req.body,
58+
body: serializedBody,
4559
});
4660
return verifyWebhookBase(clonedRequest, options);
4761
}

0 commit comments

Comments
 (0)