Skip to content

Commit 70ca64a

Browse files
authored
docs: document validateWebhook (#259)
* document validateWebhook * Update README.md
1 parent 5ba8d17 commit 70ca64a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,49 @@ await replicate.predictions.create({
148148
// => {"id": "xyz", "status": "successful", ... }
149149
```
150150

151+
## Verifying webhooks
152+
153+
To prevent unauthorized requests, Replicate signs every webhook and its metadata with a unique key for each user or organization. You can use this signature to verify the webhook indeed comes from Replicate before you process it.
154+
155+
This client includes a `validateWebhook` convenience function that you can use to validate webhooks.
156+
157+
To validate webhooks:
158+
159+
1. Check out the [webhooks guide](https://replicate.com/docs/webhooks) to get started.
160+
1. [Retrieve your webhook signing secret](https://replicate.com/docs/webhooks#retrieving-the-webhook-signing-key) and store it in your enviroment.
161+
1. Update your webhook handler to call `validateWebhook(request, secret)`, where `request` is an instance of a [web-standard `Request` object](https://developer.mozilla.org/en-US/docs/Web/API/object, and `secret` is the signing secret for your environment.
162+
163+
Here's an example of how to validate webhooks using Next.js:
164+
165+
```js
166+
import { NextResponse } from 'next/server';
167+
import { validateWebhook } from 'replicate';
168+
169+
export async function POST(request) {
170+
const secret = process.env.REPLICATE_WEBHOOK_SIGNING_SECRET;
171+
172+
if (!secret) {
173+
console.log("Skipping webhook validation. To validate webhooks, set REPLICATE_WEBHOOK_SIGNING_SECRET")
174+
const body = await request.json();
175+
console.log(body);
176+
return NextResponse.json({ detail: "Webhook received (but not validated)" }, { status: 200 });
177+
}
178+
179+
const webhookIsValid = await validateWebhook(request.clone(), secret);
180+
181+
if (!webhookIsValid) {
182+
return NextResponse.json({ detail: "Webhook is invalid" }, { status: 401 });
183+
}
184+
185+
// process validated webhook here...
186+
console.log("Webhook is valid!");
187+
const body = await request.json();
188+
console.log(body);
189+
190+
return NextResponse.json({ detail: "Webhook is valid" }, { status: 200 });
191+
}
192+
```
193+
151194
## TypeScript
152195

153196
Currently in order to support the module format used by `replicate` you'll need to set `esModuleInterop` to `true` in your tsconfig.json.

0 commit comments

Comments
 (0)