| 1 | ---
|
| 2 | title: Webhooks
|
| 3 | # can make a quick how-to on creating a webhook, this was copy/pasted from another doc, needs to be reviewed first
|
| 4 | hidden: true
|
| 5 | ---
|
| 6 |
|
| 7 | # Webhooks
|
| 8 |
|
| 9 | Resource routes can be used to handle webhooks. For example, you can create a webhook that receives notifications from GitHub when a new commit is pushed to a repository:
|
| 10 |
|
| 11 | ```tsx
|
| 12 | import type { Route } from "./+types/github";
|
| 13 |
|
| 14 | import crypto from "node:crypto";
|
| 15 |
|
| 16 | export const action = async ({
|
| 17 | request,
|
| 18 | }: Route.ActionArgs) => {
|
| 19 | if (request.method !== "POST") {
|
| 20 | return Response.json(
|
| 21 | { message: "Method not allowed" },
|
| 22 | {
|
| 23 | status: 405,
|
| 24 | },
|
| 25 | );
|
| 26 | }
|
| 27 | const payload = await request.json();
|
| 28 |
|
| 29 | /* Validate the webhook */
|
| 30 | const signature = request.headers.get(
|
| 31 | "X-Hub-Signature-256",
|
| 32 | );
|
| 33 | const generatedSignature = `sha256=${crypto
|
| 34 | .createHmac("sha256", process.env.GITHUB_WEBHOOK_SECRET)
|
| 35 | .update(JSON.stringify(payload))
|
| 36 | .digest("hex")}`;
|
| 37 | if (signature !== generatedSignature) {
|
| 38 | return Response.json(
|
| 39 | { message: "Signature mismatch" },
|
| 40 | {
|
| 41 | status: 401,
|
| 42 | },
|
| 43 | );
|
| 44 | }
|
| 45 |
|
| 46 | /* process the webhook (e.g. enqueue a background job) */
|
| 47 |
|
| 48 | return Response.json({ success: true });
|
| 49 | };
|
| 50 | ```
|