Skip to content

Commit 330c30a

Browse files
authored
Add Typescript example to securing-your-webhooks.md (#25790)
1 parent ef413e4 commit 330c30a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

content/webhooks-and-events/webhooks/securing-your-webhooks.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,30 @@ def verify_signature(payload_body, secret_token, signature_header):
112112
raise HTTPException(status_code=403, detail="Request signatures didn't match!")
113113
```
114114

115+
### Typescript example
116+
117+
For example, you can define the following `verify_signature` function and call it when you receive a webhook payload:
118+
119+
```javascript{:copy}
120+
import * as crypto from "crypto";
121+
122+
const WEBHOOK_SECRET: string = process.env.WEBHOOK_SECRET;
123+
124+
const verify_signature = (req: Request) => {
125+
const signature = crypto
126+
.createHmac("sha256", WEBHOOK_SECRET)
127+
.update(JSON.stringify(req.body))
128+
.digest("hex");
129+
return `sha256=${signature}` === req.headers.get("x-hub-signature-256");
130+
};
131+
132+
const handleWebhook = (req: Request, res: Response) => {
133+
if (!verify_signature(req)) {
134+
res.status(401).send("Unauthorized");
135+
return;
136+
}
137+
// The rest of your logic here
138+
};
139+
```
140+
115141
[secure_compare]: https://rubydoc.info/github/rack/rack/main/Rack/Utils:secure_compare

0 commit comments

Comments
 (0)