diff --git a/docs/docs.json b/docs/docs.json index f4d8ebc5fd0..4bce9dbf3e0 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -568,7 +568,6 @@ "guides/frameworks/drizzle", "guides/frameworks/prisma", "guides/frameworks/nango", - "guides/frameworks/sequin", { "group": "Supabase", "icon": { @@ -590,10 +589,10 @@ }, "pages": [ "guides/frameworks/webhooks-guides-overview", - "guides/frameworks/nextjs-webhooks", - "guides/frameworks/remix-webhooks", "guides/examples/stripe-webhook", - "guides/examples/hookdeck-webhook" + "guides/examples/hookdeck-webhook", + "guides/frameworks/nextjs-webhooks", + "guides/frameworks/remix-webhooks" ] } ] @@ -812,6 +811,11 @@ ] }, "redirects": [ + { + "source": "/guides/frameworks/sequin", + "destination": "/guides/frameworks/webhooks-guides-overview", + "permanent": true + }, { "source": "/webhooks/private-beta", "destination": "/webhooks/public-beta", diff --git a/docs/guides/examples/stripe-webhook.mdx b/docs/guides/examples/stripe-webhook.mdx index 588caf0bacb..d7ee7a00d73 100644 --- a/docs/guides/examples/stripe-webhook.mdx +++ b/docs/guides/examples/stripe-webhook.mdx @@ -1,151 +1,129 @@ --- title: "Trigger a task from Stripe webhook events" sidebarTitle: "Stripe webhooks" -description: "This example demonstrates how to handle Stripe webhook events using Trigger.dev." +description: "Receive Stripe events on a hosted webhook endpoint, verified with your Stripe signing secret, and run a task when a checkout session completes." --- -## Overview +Learn how to run a task for every completed Stripe checkout without writing a webhook handler. You'll declare a Stripe endpoint, subscribe a task to `checkout.session.completed`, register the endpoint's URL with Stripe, and send a test event. -This example shows how to set up a webhook handler in your existing app for incoming Stripe events. The handler triggers a task when a `checkout.session.completed` event is received. This is easily customisable to handle other Stripe events. +Trigger.dev hosts the endpoint, verifies each request with your Stripe signing secret, deduplicates Stripe's retries on the event id, and runs the task with the verified event. -## Key features +## Prerequisites -- Shows how to create a Stripe webhook handler in your app -- Triggers a task from your backend when a `checkout.session.completed` event is received +- A project set up with Trigger.dev and `@trigger.dev/sdk` 4.8.1 or later. See [Webhooks public beta](/webhooks/public-beta#install-the-packages). +- A [Stripe](https://stripe.com) account. +- The [Stripe CLI](https://docs.stripe.com/stripe-cli), for sending a test event. On some accounts an administrator has to turn on CLI access before `stripe login` works. +- The `stripe` package, for the event types: -## Environment variables + -You'll need to configure the following environment variables for this example to work: +```bash npm +npm i stripe +``` -- `STRIPE_WEBHOOK_SECRET` The secret key used to verify the Stripe webhook signature. -- `TRIGGER_API_URL` Your Trigger.dev API url: `https://api.trigger.dev` -- `TRIGGER_SECRET_KEY` A named **Trigger only** API key from the Trigger.dev environment your app uses +```bash pnpm +pnpm add stripe +``` -## Setting up the Stripe webhook handler +```bash bun +bun add stripe +``` -First you'll need to create a [Stripe webhook](https://stripe.com/docs/webhooks) handler route that listens for POST requests and verifies the Stripe signature. + -Here are examples of how you can set up a handler using different frameworks: +## Declare the endpoint and subscribe a task - +Declare the endpoint with `webhooks.stripe()` and subscribe a task to it. The filter means only `checkout.session.completed` events start a run: -```ts Next.js -// app/api/stripe-webhook/route.ts -import { NextResponse } from "next/server"; -import { tasks } from "@trigger.dev/sdk"; -import Stripe from "stripe"; -import type { stripeCheckoutCompleted } from "@/trigger/stripe-checkout-completed"; -// 👆 **type-only** import - -export async function POST(request: Request) { - const signature = request.headers.get("stripe-signature"); - const payload = await request.text(); - - if (!signature || !payload) { - return NextResponse.json( - { error: "Invalid Stripe payload/signature" }, - { - status: 400, - } - ); - } - - const event = Stripe.webhooks.constructEvent( - payload, - signature, - process.env.STRIPE_WEBHOOK_SECRET as string - ); - - // Perform the check based on the event type - switch (event.type) { - case "checkout.session.completed": { - // Trigger the task only if the event type is "checkout.session.completed" - const { id } = await tasks.trigger( - "stripe-checkout-completed", - event.data.object - ); - return NextResponse.json({ runId: id }); - } - default: { - // Return a response indicating that the event is not handled - return NextResponse.json( - { message: "Event not handled" }, - { - status: 200, - } - ); - } - } -} -``` +```ts /trigger/stripe.ts +import type Stripe from "stripe"; +import { webhook, webhooks } from "@trigger.dev/sdk"; -```ts Remix -// app/webhooks.stripe.ts -import { type ActionFunctionArgs, json } from "@remix-run/node"; -import type { stripeCheckoutCompleted } from "src/trigger/stripe-webhook"; -// 👆 **type-only** import -import { tasks } from "@trigger.dev/sdk"; -import Stripe from "stripe"; - -export async function action({ request }: ActionFunctionArgs) { - // Validate the Stripe webhook payload - const signature = request.headers.get("stripe-signature"); - const payload = await request.text(); - - if (!signature || !payload) { - return json({ error: "Invalid Stripe payload/signature" }, { status: 400 }); - } - - const event = Stripe.webhooks.constructEvent( - payload, - signature, - process.env.STRIPE_WEBHOOK_SECRET as string - ); - - // Perform the check based on the event type - switch (event.type) { - case "checkout.session.completed": { - // Trigger the task only if the event type is "checkout.session.completed" - const { id } = await tasks.trigger( - "stripe-checkout-completed", - event.data.object - ); - return json({ runId: id }); - } - default: { - // Return a response indicating that the event is not handled - return json({ message: "Event not handled" }, { status: 200 }); - } - } -} +export const stripe = webhooks.endpoint.define({ + id: "stripe", + source: webhooks.stripe(), +}); + +export const fulfillOrder = webhook({ + id: "fulfill-order", + endpoint: stripe, + filter: "event.type == 'checkout.session.completed'", + onEvent: async ({ event }) => { + const session = event.data.object; // typed as Stripe.Checkout.Session by the filter + console.log("Checkout completed", session.id, session.amount_total); + // Fulfill the order here + }, +}); ``` - +`webhook()` takes the same options as a [task](/tasks/overview), such as `retry`, `queue` and `machine`. To handle another Stripe event, subscribe another `webhook()` task to the same endpoint with its own [filter](/webhooks/filters). -## Task code +## Register the endpoint with Stripe -This task is triggered when a `checkout.session.completed` event is received from Stripe. + + + Run `trigger dev`, then open the **Webhooks** page in your Development environment and select the `stripe` endpoint. When you deploy, the endpoint also appears in the Production environment. Each environment has its own endpoint URL, and each team member has their own development environment. Register your development URL in a Stripe sandbox (or test mode) and the production URL in live mode. + + + Copy the endpoint's **Webhook URL**. In the Stripe Dashboard, open the **Webhooks** tab in Workbench and choose **Create an event destination**: -```ts trigger/stripe-checkout-completed.ts -import { task } from "@trigger.dev/sdk"; -import type stripe from "stripe"; + 1. Select **Your account**. + 2. Choose the **Snapshot** payload, and the API version that matches your `stripe` package. + 3. Select the `checkout.session.completed` event. + 4. Choose **Webhook endpoint** as the destination type. + 5. Paste the URL as the **Endpoint URL**. -export const stripeCheckoutCompleted = task({ - id: "stripe-checkout-completed", - run: async (payload: stripe.Checkout.Session) => { - // Add your custom logic for handling the checkout.session.completed event here - }, -}); + + Stripe marks **Thin** as recommended, but thin payloads don't include `data.object`. Choose + **Snapshot** so the task receives the full checkout session. + + + + On the destination's page in Stripe, choose **Reveal secret** and copy the signing secret (it starts with `whsec_`). Then choose **Set signing secret** on the Trigger.dev endpoint and paste it. Every delivery is rejected until the secret is set. + + To store it from the command line without printing it, put the secret in `STRIPE_WEBHOOK_SECRET` in your shell or `.env` file, then run: + + + + ```bash npm + npx trigger.dev@latest webhooks set-secret stripe --env dev --from-env STRIPE_WEBHOOK_SECRET + ``` + + ```bash pnpm + pnpm dlx trigger.dev@latest webhooks set-secret stripe --env dev --from-env STRIPE_WEBHOOK_SECRET + ``` + + ```bash bun + bunx trigger.dev@latest webhooks set-secret stripe --env dev --from-env STRIPE_WEBHOOK_SECRET + ``` + + + + For production, repeat this step with the live-mode secret and `--env prod`. + + + +To have an AI coding agent register the URL and secret instead, copy the endpoint's setup prompt. The agent creates its own Stripe endpoint with the Stripe CLI or API, so use either the prompt or the steps above, not both. See [Connect a provider](/webhooks/connect#set-it-up-with-an-ai-agent). + +## Test it + +With `trigger dev` running, send a test event with the [Stripe CLI](https://docs.stripe.com/stripe-cli). Run `stripe login` first, and make sure the CLI is on the same account and sandbox where you created the destination (`stripe login list` shows them): + +```bash +stripe trigger checkout.session.completed ``` -## Testing your task locally +The event appears on the endpoint's **Deliveries** tab as **Succeeded**. Open the delivery to see the `fulfill-order` run it started. The Stripe CLI also creates events such as `payment_intent.created`, but Stripe only sends the events your destination subscribes to. If you subscribed to more events than the task's filter takes, those deliveries show as **Filtered** and start no run. -To test everything is working you can use the Stripe CLI to send test events to your endpoint: +If no delivery appears, open the destination's **Event deliveries** tab in Stripe Workbench to see the HTTP status Trigger.dev returned, and check that Stripe uses the copied URL and that the signing secret matches. See [Deliveries and endpoints](/webhooks/deliveries) for every status and how to replay a delivery. -1. Install the [Stripe CLI](https://stripe.com/docs/stripe-cli#install), and login -2. Follow the instructions to [test your handler](https://docs.stripe.com/webhooks#test-webhook). This will include a temporary `STRIPE_WEBHOOK_SECRET` that you can use for testing. -3. When triggering the event, use the `checkout.session.completed` event type. With the Stripe CLI: `stripe trigger checkout.session.completed` -4. If your endpoint is set up correctly, you should see the Stripe events logged in your console with a status of `200`. -5. Then, check the [Trigger.dev](https://cloud.trigger.dev) dashboard and you should see the successful run of the `stripe-webhook` task. +## Next steps -For more information on setting up and testing Stripe webhooks, refer to the [Stripe Webhook Documentation](https://stripe.com/docs/webhooks). + + + Choose which events each subscribed task takes. + + + Pause a run until a matching webhook arrives. + + diff --git a/docs/guides/frameworks/nextjs-webhooks.mdx b/docs/guides/frameworks/nextjs-webhooks.mdx index 25c91f07265..4e59f07d5fa 100644 --- a/docs/guides/frameworks/nextjs-webhooks.mdx +++ b/docs/guides/frameworks/nextjs-webhooks.mdx @@ -6,22 +6,17 @@ description: "Learn how to trigger a task from a webhook in a Next.js app." import VercelDocsCards from "/snippets/vercel-docs-cards.mdx"; + + To receive webhooks without adding a route to your app, use a [hosted webhook + endpoint](/webhooks/overview). Trigger.dev hosts the URL, verifies each request, and runs your + tasks. Use this guide when your Next.js app has to receive the request itself. + + ## Prerequisites -- [A Next.js project, set up with Trigger.dev](/guides/frameworks/nextjs) +- [A Next.js project, set up with Trigger.dev](/guides/frameworks/nextjs), with `TRIGGER_SECRET_KEY` set in `.env.local` (see [Create an API key for local development](/guides/frameworks/nextjs#create-an-api-key-for-local-development)) - [cURL](https://curl.se/) installed on your local machine. This will be used to send a POST request to your webhook handler. -## GitHub repo - - - Click here to view the full code for this project in our examples repository on GitHub. You can - fork it and use it as a starting point for your own project. - - ## Adding the webhook handler The webhook handler in this guide will be an API route. @@ -30,12 +25,12 @@ This will be different depending on whether you are using the Next.js pages rout ### Pages router: creating the webhook handler -Create a new file `pages/api/webhook-handler.ts` or `pages/api/webhook-hander.js`. +Create a new file `pages/api/webhook-handler.ts`. In your new file, add the following code: ```ts /pages/api/webhook-handler.ts -import { helloWorldTask } from "@/trigger/example"; +import type { helloWorldTask } from "@/trigger/example"; import { tasks } from "@trigger.dev/sdk"; import type { NextApiRequest, NextApiResponse } from "next"; @@ -54,7 +49,7 @@ This code will handle the webhook payload and trigger the 'Hello World' task. ### App router: creating the webhook handler -Create a new file in the `app/api/webhook-handler/route.ts` or `app/api/webhook-handler/route.js`. +Create a new file `app/api/webhook-handler/route.ts`. In your new file, add the following code: @@ -70,12 +65,14 @@ export async function POST(req: Request) { // Trigger the helloWorldTask with the webhook data as the payload await tasks.trigger("hello-world", payload); - return NextResponse.json("OK", { status: 200 }); + return NextResponse.json({ message: "OK" }, { status: 200 }); } ``` This code will handle the webhook payload and trigger the 'Hello World' task. +The `@/trigger/example` import must point to where `init` created your example task. If `init` created `src/trigger` in a project without a `src` folder, import from `@/src/trigger/example` instead. + ## Triggering the task locally Now that you have your webhook handler set up, you can trigger the 'Hello World' task from it. We will do this locally using cURL. @@ -96,13 +93,13 @@ First, run your Next.js app. pnpm run dev ``` - ```bash yarn - yarn dev + ```bash bun + bun run dev ``` -Then, open up a second terminal window and start the Trigger.dev dev server: +Then, open up a second terminal window and start the Trigger.dev dev server from your project root: @@ -114,11 +111,11 @@ Then, open up a second terminal window and start the Trigger.dev dev server: pnpm dlx trigger.dev@latest dev ``` - ```bash yarn - yarn dlx trigger.dev@latest dev + ```bash bun + bunx trigger.dev@latest dev ``` - + @@ -141,9 +138,11 @@ This will send a POST request to your webhook handler, with a JSON payload. -After running the command, you should see a successful dev run and a 200 response in your terminals. +curl prints `{"message":"OK"}`, the Next.js terminal logs `POST /api/webhook-handler 200`, and the `trigger dev` terminal logs a successful `hello-world` run. + +If curl gets a `500` and the Next.js terminal shows `ApiClientMissingError`, `TRIGGER_SECRET_KEY` isn't set. -If you now go to your [Trigger.dev dashboard](https://cloud.trigger.dev), you should also see a successful run for the 'Hello World' task, with the payload you sent, in this case; `{"name": "John Doe", "age": "87"}`. +Open the run link that `trigger dev` prints, or the **Runs** page of your Development environment, and you should see a successful run for the 'Hello World' task, with the payload you sent, in this case; `{"Name": "John Doe", "Age": "87"}`. diff --git a/docs/guides/frameworks/remix-webhooks.mdx b/docs/guides/frameworks/remix-webhooks.mdx index a62d90cb9d0..99509ac2d21 100644 --- a/docs/guides/frameworks/remix-webhooks.mdx +++ b/docs/guides/frameworks/remix-webhooks.mdx @@ -4,32 +4,27 @@ sidebarTitle: "Remix webhooks" description: "Learn how to trigger a task from a webhook in a Remix app." --- + + To receive webhooks without adding a route to your app, use a [hosted webhook + endpoint](/webhooks/overview). Trigger.dev hosts the URL, verifies each request, and runs your + tasks. Use this guide when your Remix app has to receive the request itself. + + ## Prerequisites -- [A Remix project, set up with Trigger.dev](/guides/frameworks/remix) +- [A Remix v2 project, set up with Trigger.dev](/guides/frameworks/remix), with `TRIGGER_SECRET_KEY` set in your `.env` file and the `trigger` folder in `src/trigger` - [cURL](https://curl.se/) installed on your local machine. This will be used to send a POST request to your webhook handler. -## GitHub repo - - - Click here to view the full code for this project in our examples repository on GitHub. You can - fork it and use it as a starting point for your own project. - - ## Adding the webhook handler The webhook handler in this guide will be an API route. Create a new file `app/routes/api.webhook-handler.ts` or `app/routes/api.webhook-handler.js`. In your new file, add the following code: -```ts /api/webhook-handler.ts +```ts app/routes/api.webhook-handler.ts import type { ActionFunctionArgs } from "@remix-run/node"; import { tasks } from "@trigger.dev/sdk"; -import { helloWorldTask } from "src/trigger/example"; +import type { helloWorldTask } from "../../src/trigger/example"; export async function action({ request }: ActionFunctionArgs) { const payload = await request.json(); @@ -63,8 +58,8 @@ First, run your Remix app. pnpm run dev ``` - ```bash yarn - yarn dev + ```bash bun + bun run dev ``` @@ -81,8 +76,8 @@ Then, open up a second terminal window and start the Trigger.dev dev server: pnpm dlx trigger.dev@latest dev ``` - ```bash yarn - yarn dlx trigger.dev@latest dev + ```bash bun + bunx trigger.dev@latest dev ``` @@ -108,9 +103,9 @@ This will send a POST request to your webhook handler, with a JSON payload. -After running the command, you should see a successful dev run and a 200 response in your terminals. +curl prints `OK`, and the `trigger dev` terminal logs a successful `hello-world` run. -If you now go to your [Trigger.dev dashboard](https://cloud.trigger.dev), you should also see a successful run for the 'Hello World' task, with the payload you sent, in this case; `{"name": "John Doe", "age": "87"}`. +Open the run link that `trigger dev` prints, or the **Runs** page of your Development environment, and you should see a successful run for the 'Hello World' task, with the payload you sent, in this case; `{"Name": "John Doe", "Age": "87"}`. diff --git a/docs/guides/frameworks/sequin.mdx b/docs/guides/frameworks/sequin.mdx deleted file mode 100644 index 77910d70478..00000000000 --- a/docs/guides/frameworks/sequin.mdx +++ /dev/null @@ -1,328 +0,0 @@ ---- -title: "Sequin database triggers" -sidebarTitle: "Sequin database triggers" -description: "This guide will show you how to trigger tasks from database changes using Sequin" -icon: "database" ---- - -[Sequin](https://sequinstream.com) allows you to trigger tasks from database changes. Sequin captures every insert, update, and delete on a table and then ensures a task is triggered for each change. - -Often, task runs coincide with database changes. For instance, you might want to use a Trigger.dev task to generate an embedding for each post in your database: - -Sequin and Trigger.dev Overview - -In this guide, you'll learn how to use Sequin to trigger Trigger.dev tasks from database changes. - -## Prerequisites - -You are about to create a [regular Trigger.dev task](/tasks/overview) that you will execute when ever a post is inserted or updated in your database. Sequin will detect all the changes on the `posts` table and then send the payload of the post to an API endpoint that will call `tasks.trigger()` to create the embedding and update the database. - -As long as you create an HTTP endpoint that Sequin can deliver webhooks to, you can use any web framework or edge function (e.g. Supabase Edge Functions, Vercel Functions, Cloudflare Workers, etc.) to invoke your Trigger.dev task. In this guide, we'll show you how to setup Trigger.dev tasks using Next.js API Routes. - -You'll need the following to follow this guide: - -- A Next.js project with [Trigger.dev](https://trigger.dev) installed - - If you don't have one already, follow [Trigger.dev's Next.js setup - guide](/guides/frameworks/nextjs) to setup your project. You can return to this guide when - you're ready to write your first Trigger.dev task. - -- A [Sequin](https://console.sequinstream.com/register) account -- A Postgres database (Sequin works with any Postgres database version 12 and up) with a `posts` table. - -## Create a Trigger.dev task - -Start by creating a new Trigger.dev task that takes in a Sequin change event as a payload, creates an embedding, and then inserts the embedding into the database: - - - - In your `src/trigger/tasks` directory, create a new file called `create-embedding-for-post.ts` and add the following code: - - -```ts trigger/create-embedding-for-post.ts -import { task } from "@trigger.dev/sdk"; -import { OpenAI } from "openai"; -import { upsertEmbedding } from "../util"; - -const openai = new OpenAI({ - apiKey: process.env.OPENAI_API_KEY, -}); - -export const createEmbeddingForPost = task({ - id: "create-embedding-for-post", - run: async (payload: { - record: { - id: number; - title: string; - body: string; - author: string; - createdAt: string; - embedding: string | null; - }, - metadata: { - table_schema: string, - table_name: string, - consumer: { - id: string; - name: string; - }; - }; - }) => { - // Create an embedding using the title and body of payload.record - const content = `${payload.record.title}\n\n${payload.record.body}`; - const embedding = (await openai.embeddings.create({ - model: "text-embedding-ada-002", - input: content, - })).data[0].embedding; - - // Upsert the embedding in the database. See utils.ts for the implementation -> -> - await upsertEmbedding(embedding, payload.record.id); - - // Return the updated record - return { - ...payload.record, - embedding: JSON.stringify(embedding), - }; - } -}); -```` - -```ts utils.ts -import pg from "pg"; - -export async function upsertEmbedding(embedding: number[], id: number) { - const client = new pg.Client({ - connectionString: process.env.DATABASE_URL, - }); - await client.connect(); - - try { - const query = ` - INSERT INTO post_embeddings (id, embedding) - VALUES ($2, $1) - ON CONFLICT (id) - DO UPDATE SET embedding = $1 - `; - const values = [JSON.stringify(embedding), id]; - - const result = await client.query(query, values); - console.log(`Updated record in database. Rows affected: ${result.rowCount}`); - - return result.rowCount; - } catch (error) { - console.error("Error updating record in database:", error); - throw error; - } finally { - await client.end(); - } -} -```` - - - -This task takes in a Sequin record event, creates an embedding, and then upserts the embedding into a `post_embeddings` table. - - - - Register the `create-embedding-for-post` task to your Trigger.dev cloud project by running the following command: - -```bash -npx trigger.dev@latest dev -``` - -In the Trigger.dev dashboard, you should now see the `create-embedding-for-post` task: - - - Task added - - - - - - You've successfully created a Trigger.dev task that will create an embedding for each post in your - database. In the next step, you'll create an API endpoint that Sequin can deliver records to. - - -## Setup API route - -You'll now create an API endpoint that will receive posts from Sequin and then trigger the `create-embedding-for-post` task. - - - This guide covers how to setup an API endpoint using the Next.js App Router. You can find examples - for Next.js Server Actions and Pages Router in the [Trigger.dev - documentation](https://trigger.dev/docs/guides/frameworks/nextjs). - - - - - Add a route handler by creating a new `route.ts` file in a `/app/api/create-embedding-for-post` directory: - -```ts app/api/create-embedding-for-post/route.ts -import type { createEmbeddingForPost } from "@/trigger/create-embedding-for-post"; -import { tasks } from "@trigger.dev/sdk"; -import { NextResponse } from "next/server"; - -export async function POST(req: Request) { - const authHeader = req.headers.get("authorization"); - if (!authHeader || authHeader !== `Bearer ${process.env.SEQUIN_WEBHOOK_SECRET}`) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - const payload = await req.json(); - const handle = await tasks.trigger( - "create-embedding-for-post", - payload - ); - - return NextResponse.json(handle); -} -``` - -This route handler will receive records from Sequin, parse them, and then trigger the `create-embedding-for-post` task. - - - - You'll need to set four secret keys in a `.env.local` file: - -```bash -SEQUIN_WEBHOOK_SECRET=your-secret-key -TRIGGER_SECRET_KEY=secret-from-trigger-dev -OPENAI_API_KEY=sk-proj-asdfasdfasdf -DATABASE_URL=postgresql:// -``` - -The `SEQUIN_WEBHOOK_SECRET` ensures that only Sequin can access your API endpoint. - -Create a named key with **Trigger only** access in the Trigger.dev environment your app uses, then set it as `TRIGGER_SECRET_KEY`. - -The `OPENAI_API_KEY` and `DATABASE_URL` are used to create an embedding using OpenAI and connect to your database. Be sure to add these as [environment variables](https://trigger.dev/docs/deploy-environment-variables) in Trigger.dev as well. - - - - - - You've successfully created an API endpoint that can receive record payloads from Sequin and - trigger a Trigger.dev task. In the next step, you'll setup Sequin to trigger the endpoint. - - -## Create Sequin consumer - -You'll now configure Sequin to send every row in your `posts` table to your Trigger.dev task. - - - - 1. Login to your Sequin account and click the **Add New Database** button. - 2. Enter the connection details for your Postgres database. - - If you need to connect to a local dev database, flip the **use localhost** switch and follow the instructions to create a tunnel using the [Sequin CLI](https://sequinstream.com/docs/cli). - - 3. Follow the instructions to create a publication and a replication slot by running two SQL commands in your database: - - ```sql - create publication sequin_pub for all tables; - select pg_create_logical_replication_slot('sequin_slot', 'pgoutput'); - ``` - - 4. Name your database and click the **Connect Database** button. - - Sequin will connect to your database and ensure that it's configured properly. - - - If you need step-by-step connection instructions to connect Sequin to your database, check out our [quickstart guide](https://sequinstream.com/docs/quickstart). - - - - Now, create a tunnel to your local endpoint so Sequin can deliver change payloads to your local API: - - 1. In the Sequin console, open the **HTTP Endpoint** tab and click the **Create HTTP Endpoint** button. - 2. Enter a name for your endpoint (i.e. `local_endpoint`) and flip the **Use localhost** switch. Follow the instructions in the Sequin console to [install the Sequin CLI](https://sequinstream.com/docs/cli), then run: - - ```bash - sequin tunnel --ports=3001:local_endpoint - ``` - - 3. Now, click **Add encryption header** and set the key to `Authorization` and the value to `Bearer SEQUIN_WEBHOOK_SECRET`. - 4. Click **Create HTTP Endpoint**. - - - Create a push consumer that will capture posts from your database and deliver them to your local endpoint: - - 1. Navigate to the **Consumers** tab and click the **Create Consumer** button. - 2. Select your `posts` table (i.e `public.posts`). - 3. You want to ensure that every post receives an embedding - and that embeddings are updated as posts are updated. To do this, select to process **Rows** and click **Continue**. - - You can also use **changes** for this particular use case, but **rows** comes with some nice replay and backfill features. - - 4. You'll now set the sort and filter for the consumer. For this guide, we'll sort by `updated_at` and start at the beginning of the table. We won't apply any filters: - - Consumer Sort and Filter - - 5. On the next screen, select **Push** to have Sequin send the events to your webhook URL. Click **Continue**. - 6. Now, give your consumer a name (i.e. `posts_push_consumer`) and in the **HTTP Endpoint** section select the `local_endpoint` you created above. Add the exact API route you created in the previous step (i.e. `/api/create-embedding-for-post`): - - Consumer Endpoint - - 7. Click the **Create Consumer** button. - - - - -Your Sequin consumer is now created and ready to send events to your API endpoint. - -## Test end-to-end - - - - 1. The Next.js app is running: `npm run dev` - 2. The Trigger.dev dev server is running `npx trigger.dev@latest dev` - 3. The Sequin tunnel is running: `sequin tunnel --ports=3001:local_endpoint` - - - - ```sql - insert into - posts (title, body, author) - values - ( - 'The Future of AI', - 'An insightful look into how artificial intelligence is shaping the future of technology and society.', - 'Alice H Johnson' - ); - ``` - - - In the Sequin console, navigate to the [**Trace**](https://console.sequinstream.com/trace) tab and confirm that Sequin delivered the event to your local endpoint: - - Trace Event - - - - - In your local terminal, you should see a `200` response in your Next.js app: - - ```bash - POST /api/create-embedding-for-post 200 in 262ms - ``` - - - Finally, in the [**Trigger.dev dashboard**](https://cloud.trigger.dev/), navigate to the Runs page and confirm that the task run completed successfully: - - - Task run - - - - - - - Every time a post is created or updated, Sequin will deliver the row payload to your API endpoint - and Trigger.dev will run the `create-embedding-for-post` task. - - -## Next steps - -With Sequin and Trigger.dev, every post in your database will now have an embedding. This is a simple example of how you can trigger long-running tasks on database changes. - -From here, add error handling and deploy to production: - -- Add [retries](/errors-retrying) to your Trigger.dev task to ensure that any errors are captured and logged. -- Deploy to [production](/guides/frameworks/nextjs#deploying-your-task-to-trigger-dev) and update your Sequin consumer to point to your production database and endpoint. diff --git a/docs/guides/frameworks/supabase-edge-functions-basic.mdx b/docs/guides/frameworks/supabase-edge-functions-basic.mdx index 6d3ceae15aa..8825b52dc57 100644 --- a/docs/guides/frameworks/supabase-edge-functions-basic.mdx +++ b/docs/guides/frameworks/supabase-edge-functions-basic.mdx @@ -32,17 +32,6 @@ This guide shows you how to set up and deploy a simple Supabase edge function ex - [Create a Trigger.dev account](https://cloud.trigger.dev) - Create a new Trigger.dev project -## GitHub repo - - - Click here to view the full code for this project in our examples repository on GitHub. You can - fork it and use it as a starting point for your own project. - - ## Initial setup diff --git a/docs/guides/frameworks/supabase-edge-functions-database-webhooks.mdx b/docs/guides/frameworks/supabase-edge-functions-database-webhooks.mdx index f0fd2b5be80..280360dac97 100644 --- a/docs/guides/frameworks/supabase-edge-functions-database-webhooks.mdx +++ b/docs/guides/frameworks/supabase-edge-functions-database-webhooks.mdx @@ -1,293 +1,154 @@ --- -title: "Triggering tasks from Supabase Database Webhooks" +title: "Trigger tasks from Supabase database webhooks" sidebarTitle: "Database webhooks" -description: "This guide shows you how to trigger a transcribing task when a row is added to a table in a Supabase database, using a Database Webhook and Edge Function." +description: "Transcribe a video when a row is added to a Supabase table, using a database webhook that posts to a hosted Trigger.dev webhook endpoint." --- -import Prerequisites from "/snippets/framework-prerequisites.mdx"; -import SupabasePrerequisites from "/snippets/supabase-prerequisites.mdx"; -import UsefulNextSteps from "/snippets/useful-next-steps.mdx"; -import TriggerTaskNextjs from "/snippets/trigger-tasks-nextjs.mdx"; -import NextjsTroubleshootingMissingApiKey from "/snippets/nextjs-missing-api-key.mdx"; -import NextjsTroubleshootingButtonSyntax from "/snippets/nextjs-button-syntax.mdx"; import SupabaseDocsCards from "/snippets/supabase-docs-cards.mdx"; -import SupabaseAuthInfo from "/snippets/supabase-auth-info.mdx"; -## Overview +A Supabase database webhook posts each new row to a [hosted webhook endpoint](/webhooks/overview), and Trigger.dev runs a task with the row. You don't need an Edge Function. -Supabase and Trigger.dev can be used together to create powerful workflows triggered by real-time changes in your database tables: +In this guide: -- A Supabase Database Webhook triggers an Edge Function when a row including a video URL is inserted into a table -- The Edge Function triggers a Trigger.dev task, passing the `video_url` column data from the new table row as the payload -- The Trigger.dev task then: - - - Uses [FFmpeg](https://www.ffmpeg.org/) to extract the audio track from a video URL - - Uses [Deepgram](https://deepgram.com) to transcribe the extracted audio - - Updates the original table row using the `record.id` in Supabase with the new transcription using `update` +- A Supabase database webhook fires when a row with a video URL is inserted into a table +- Trigger.dev checks the webhook's shared secret and runs the `transcribe-video` task with the row +- The task transcribes the video with [Deepgram](https://deepgram.com) and writes the transcription back to the same row ## Prerequisites -- Ensure you have the [Supabase CLI](https://supabase.com/docs/guides/cli/getting-started) installed -- Since Supabase CLI version 1.123.4, you must have [Docker Desktop installed](https://supabase.com/docs/guides/functions/deploy#deploy-your-edge-functions) to deploy Edge Functions -- Ensure TypeScript is installed -- [Create a Trigger.dev account](https://cloud.trigger.dev) -- Create a new Trigger.dev project -- [Create a new Deepgram account](https://deepgram.com/) and get your API key from the dashboard - -## GitHub repo - - - Click here to view the full code for this project in our examples repository on GitHub. You can - fork it and use it as a starting point for your own project. - - -## Initial setup - - - - - -The easiest way to get started is to use the CLI. It will add Trigger.dev to your existing project, create a `/trigger` folder and give you an example task. - -Run this command in the root of your project to get started: - - - -```bash npm -npx trigger.dev@latest init -``` - -```bash pnpm -pnpm dlx trigger.dev@latest init -``` - -```bash yarn -yarn dlx trigger.dev@latest init -``` - - - -It will do a few things: - -1. Log you into the CLI if you're not already logged in. -2. Create a `trigger.config.ts` file in the root of your project. -3. Ask where you'd like to create the `/trigger` directory. -4. Create the `/trigger` directory with an example task, `/trigger/example.[ts/js]`. - -Choose "None" when prompted to install an example task. We will create a new task for this guide. - - - - +- A Supabase project +- The [Supabase CLI](https://supabase.com/docs/guides/cli/getting-started), logged in with `supabase login` +- Trigger.dev set up in your project with the [quick start](/quick-start) (`npx trigger.dev@latest init`), using `@trigger.dev/sdk` 4.8.1 or later. See [Webhooks public beta](/webhooks/public-beta#install-the-packages) +- A [Deepgram](https://deepgram.com) API key -## Create a new table in your Supabase database +## Create the table -First, in the Supabase project dashboard, you'll need to create a new table to store the video URL and transcription. - -To do this, click on 'Table Editor' in the left-hand menu and create a new table. +In the Supabase dashboard, open the **Table Editor** and create a new table . ![How to create a new Supabase table](/images/supabase-new-table-1.png) -Call your table `video_transcriptions`. - -Add two new columns, one called `video_url` with the type `text` , and another called `transcription`, also with the type `text` . +Call the table `video_transcriptions` . Add a `video_url` column of type `text` and a `transcription` column of type `text` . ![How to create a new Supabase table 2](/images/supabase-new-table-2.png) -## Create and deploy the Trigger.dev task +## Generate the database types -### Generate the Database type definitions - -To allow you to use TypeScript to interact with your table, you need to [generate the type definitions](https://supabase.com/docs/guides/api/rest/generating-types) for your Supabase table using the Supabase CLI. +Generate [type definitions](https://supabase.com/docs/guides/api/rest/generating-types) for your schema so the task's database calls are typed. Run this in the root of your project: ```bash -supabase gen types --lang=typescript --project-id --schema public > database.types.ts +supabase gen types --lang=typescript --remote= --schema public > database.types.ts ``` - Replace `` with your Supabase project reference ID. This can be found in your Supabase project settings under 'General'. - -### Create the transcription task +Replace `` with your project's reference ID, which is in the project's URL in the dashboard. -Create a new task file in your `/trigger` folder. Call it `videoProcessAndUpdate.ts`. +## Write the task -This task takes a video from a public video url, extracts the audio using FFmpeg and transcribes the audio using Deepgram. The transcription summary will then be updated back to the original row in the `video_transcriptions` table in Supabase. - -You will need to install some additional dependencies for this task: +Install the Deepgram and Supabase clients: ```bash npm -npm install @deepgram/sdk @supabase/supabase-js fluent-ffmpeg +npm i @deepgram/sdk @supabase/supabase-js ``` ```bash pnpm -pnpm install @deepgram/sdk @supabase/supabase-js fluent-ffmpeg +pnpm add @deepgram/sdk @supabase/supabase-js ``` -```bash yarn -yarn install @deepgram/sdk @supabase/supabase-js fluent-ffmpeg +```bash bun +bun add @deepgram/sdk @supabase/supabase-js ``` -These dependencies will allow you to interact with the Deepgram and Supabase APIs and extract audio from a video using FFmpeg. +Create the endpoint and the task. The endpoint uses `webhooks.supabase()`, and the filter means only inserts into `video_transcriptions` start a run: - - When updating your tables from a Trigger.dev task which has been triggered by a database change, - be extremely careful to not cause an infinite loop. Ensure you have the correct conditions in - place to prevent this. - +```ts src/trigger/transcribe-video.ts +import { DeepgramClient } from "@deepgram/sdk"; +import { createClient } from "@supabase/supabase-js"; +import { logger, webhook, webhooks } from "@trigger.dev/sdk"; +import type { Database } from "../../database.types"; // the file generated in the previous step -```ts /trigger/videoProcessAndUpdate.ts -// Install any missing dependencies below -import { createClient as createDeepgramClient } from "@deepgram/sdk"; -import { createClient as createSupabaseClient } from "@supabase/supabase-js"; -import { logger, task } from "@trigger.dev/sdk"; -import ffmpeg from "fluent-ffmpeg"; -import fs from "fs"; -import { Readable } from "node:stream"; -import os from "os"; -import path from "path"; -import { Database } from "../../database.types"; - -// Create a single Supabase client for interacting with your database -// 'Database' supplies the type definitions to supabase-js -const supabase = createSupabaseClient( - // These details can be found in your Supabase project settings under `API` - process.env.SUPABASE_PROJECT_URL as string, // e.g. https://abc123.supabase.co - replace 'abc123' with your project ID - process.env.SUPABASE_SERVICE_ROLE_KEY as string // Your service role secret key -); - -// Your DEEPGRAM_SECRET_KEY can be found in your Deepgram dashboard -const deepgram = createDeepgramClient(process.env.DEEPGRAM_SECRET_KEY); - -export const videoProcessAndUpdate = task({ - id: "video-process-and-update", - run: async (payload: { videoUrl: string; id: number }) => { - const { videoUrl, id } = payload; - - logger.log(`Processing video at URL: ${videoUrl}`); - - // Generate temporary file names - const tempDirectory = os.tmpdir(); - const outputPath = path.join(tempDirectory, `audio_${Date.now()}.wav`); - - const response = await fetch(videoUrl); - - // Extract the audio using FFmpeg - await new Promise((resolve, reject) => { - if (!response.body) { - return reject(new Error("Failed to fetch video")); - } - - ffmpeg(Readable.from(response.body)) - .outputOptions([ - "-vn", // Disable video output - "-acodec pcm_s16le", // Use PCM 16-bit little-endian encoding - "-ar 44100", // Set audio sample rate to 44.1 kHz - "-ac 2", // Set audio channels to stereo - ]) - .output(outputPath) - .on("end", resolve) - .on("error", reject) - .run(); - }); +type VideoTranscription = Database["public"]["Tables"]["video_transcriptions"]["Row"]; - logger.log(`Audio extracted from video`, { outputPath }); +// The bodies a Supabase database webhook sends +type DatabaseWebhookEvent = + | { type: "INSERT"; table: string; schema: string; record: VideoTranscription; old_record: null } + | { type: "UPDATE"; table: string; schema: string; record: VideoTranscription; old_record: VideoTranscription } + | { type: "DELETE"; table: string; schema: string; record: null; old_record: VideoTranscription }; - // Transcribe the audio using Deepgram - const { result, error } = await deepgram.listen.prerecorded.transcribeFile( - fs.readFileSync(outputPath), - { - model: "nova-2", // Use the Nova 2 model - smart_format: true, // Automatically format the transcription - diarize: true, // Enable speaker diarization - } - ); +export const supabaseDatabase = webhooks.endpoint.define({ + id: "supabase-database", + source: webhooks.supabase(), +}); - if (error) { - throw error; +export const transcribeVideo = webhook({ + id: "transcribe-video", + endpoint: supabaseDatabase, + filter: "event.type == 'INSERT' && event.table == 'video_transcriptions'", + onEvent: async ({ event }) => { + const { id, video_url: videoUrl } = event.record; // the filter narrows event to an INSERT + + if (!videoUrl) { + logger.warn("Row has no video_url", { id }); + return; } - const transcription = result.results.channels[0].alternatives[0].paragraphs?.transcript; + // Create the clients here, not when the file loads, so a missing variable only fails this run + const deepgram = new DeepgramClient({ apiKey: process.env.DEEPGRAM_API_KEY }); + const supabase = createClient( + process.env.SUPABASE_URL as string, + process.env.SUPABASE_SECRET_KEY as string // server-side secret key + ); - logger.log(`Transcription: ${transcription}`); + // Deepgram fetches the video and transcribes its audio track + const response = await deepgram.listen.v1.media.transcribeUrl({ + url: videoUrl, + model: "nova-3", + smart_format: true, + }); + + if (!("results" in response)) { + throw new Error(`Deepgram returned no results for row ${id}`); + } - // Delete the temporary audio file - fs.unlinkSync(outputPath); - logger.log(`Temporary audio file deleted`, { outputPath }); + const transcription = + response.results.channels[0]?.alternatives?.[0]?.paragraphs?.transcript ?? null; - const { error: updateError } = await supabase + logger.log("Transcription", { id, transcription }); + + const { error } = await supabase .from("video_transcriptions") - // Update the transcription column - .update({ transcription: transcription }) - // Find the row by its ID + .update({ transcription }) .eq("id", id); - if (updateError) { - throw new Error(`Failed to update transcription: ${updateError.message}`); + if (error) { + throw new Error(`Failed to update row ${id}: ${error.message}`); } - - return { - message: `Summary of the audio: ${transcription}`, - result, - }; }, }); ``` +Put the file in a folder listed in `dirs` in your `trigger.config.ts`. The import path assumes that folder is `src/trigger` and `database.types.ts` is in the project root. Adjust it if your layout differs. + - This task uses your service role secret key to bypass Row Level Security. This is not recommended - for production use as it has unlimited access and bypasses all security checks. + A task that a database change triggers can trigger itself again if it writes to the same table. + Here the webhook only fires on `INSERT` and the task only runs `update`, so it can't loop. - - -### Adding the FFmpeg build extension - -Before you can deploy the task, you'll need to add the FFmpeg build extension to your `trigger.config.ts` file. +The secret key bypasses Row Level Security. Use it only in server-side code such as tasks. See the [Supabase authentication guide](/guides/frameworks/supabase-authentication) for user-scoped access. -```ts trigger.config.ts -// Add this import -import { ffmpeg } from "@trigger.dev/build/extensions/core"; -import { defineConfig } from "@trigger.dev/sdk"; +## Add the environment variables -export default defineConfig({ - project: "", // Replace with your project ref - // Your other config settings... - build: { - // Add the FFmpeg build extension - extensions: [ffmpeg()], - }, -}); -``` +On the **Environment variables** page of your Trigger.dev project, add these to the Production environment. To run the task with `trigger dev`, add them to the Development environment too. - - [Build extensions](/config/extensions/overview) allow you to hook into the build system and - customize the build process or the resulting bundle and container image (in the case of - deploying). You can use pre-built extensions or create your own. - +| Variable | Value | +| --- | --- | +| `SUPABASE_URL` | Your project URL, from the **Connect** dialog in the Supabase dashboard | +| `SUPABASE_SECRET_KEY` | A secret key (`sb_secret_...`) from **Settings > API Keys** in the Supabase dashboard. Create one if the project has none. | +| `DEEPGRAM_API_KEY` | Your Deepgram API key | - - You'll also need to add `@trigger.dev/build` to your `package.json` file under `devDependencies` - if you don't already have it there. - - -If you are modifying this example and using popular FFmpeg libraries like `fluent-ffmpeg` you'll also need to add them to [`external`](/config/config-file#external) in your `trigger.config.ts` file. - -### Add your Deepgram and Supabase environment variables to your Trigger.dev project - -You will need to add your `DEEPGRAM_SECRET_KEY`, `SUPABASE_PROJECT_URL` and `SUPABASE_SERVICE_ROLE_KEY` as environment variables in your Trigger.dev project. This can be done in the 'Environment Variables' page in your project dashboard. - -![Adding environment variables](/images/environment-variables-page.jpg) - -### Deploying your task - -Now you can now deploy your task using the following command: +## Deploy the task @@ -299,135 +160,49 @@ npx trigger.dev@latest deploy pnpm dlx trigger.dev@latest deploy ``` -```bash yarn -yarn dlx trigger.dev@latest deploy +```bash bun +bunx trigger.dev@latest deploy ``` -## Create and deploy the Supabase Edge Function - -### Create a Trigger.dev API key for Supabase - -Open the API Keys page for your Production environment in the Trigger.dev [project dashboard](https://cloud.trigger.dev). Create a named key with **Trigger only** access and copy it. Trigger.dev shows the complete value only once. - -Then, in [Supabase](https://supabase.com/dashboard/projects), select the project you want to use, navigate to 'Project settings' , click 'Edge Functions' in the configurations menu, and then click the 'Add new secret' button. - -Add `TRIGGER_SECRET_KEY` with the environment API key you created. - -![Add secret key in Supabase](/images/supabase-keys-1.png) - -### Create a new Edge Function using the Supabase CLI - -Now create an Edge Function using the Supabase CLI. Call it `video-processing-handler`. This function will be triggered by the Database Webhook. - -```bash -supabase functions new video-processing-handler -``` - -```ts functions/video-processing-handler/index.ts -// Setup type definitions for built-in Supabase Runtime APIs -import "jsr:@supabase/functions-js/edge-runtime.d.ts"; -import { tasks } from "npm:@trigger.dev/sdk@latest"; -// Import the videoProcessAndUpdate task from the trigger folder -import type { videoProcessAndUpdate } from "../../../src/trigger/videoProcessAndUpdate.ts"; -// 👆 type only import - -// Sets up a Deno server that listens for incoming JSON requests -Deno.serve(async (req) => { - const payload = await req.json(); - - // This payload will contain the video url and id from the new row in the table - const videoUrl = payload.record.video_url; - const id = payload.record.id; - - // Trigger the videoProcessAndUpdate task with the videoUrl payload - await tasks.trigger("video-process-and-update", { videoUrl, id }); - console.log(payload ?? "No name provided"); - - return new Response("ok"); -}); -``` - - - Tasks in the `trigger` folder use Node, so they must stay in there or they will not run, - especially if you are using a different runtime like Deno. Also do not add "`npm:`" to imports - inside your task files, for the same reason. - - -### Deploy the Edge Function +The deploy syncs the `supabase-database` endpoint. It appears on the Production environment's **Webhooks** page with its URL. -Now deploy your new Edge Function with the following command: +## Connect the database webhook -```bash -supabase functions deploy video-processing-handler -``` - -Follow the CLI instructions, selecting the same project where you created the Production environment API key. Once complete, you should see your new Edge Function deployment in your Supabase Edge Functions dashboard. - -There will be a link to the dashboard in your terminal output. - -## Create the Database Webhook - -In your Supabase project dashboard, click 'Project settings' , then the 'API' tab , and copy the `anon` `public` API key from the table . - -![How to find your Supabase API keys](/images/supabase-api-key.png) - -Then, go to 'Database' click on 'Webhooks' , and then click 'Create a new hook' . - -![How to create a new webhook](/images/supabase-create-webhook-1.png) - - Call the hook `edge-function-hook`. - - Select the new table you have created: -`public` `video_transcriptions`. - - Choose the `insert` event. - -![How to create a new webhook 2](/images/supabase-create-webhook-2.png) +Supabase database webhooks aren't signed, so the endpoint checks a shared secret in the `Authorization` header instead. - Under 'Webhook configuration', select -'Supabase Edge Functions'{" "} - - Under 'Edge Function', choose `POST` -and select the Edge Function you have created: `video-processing-handler`.{" "} - - Under 'HTTP Headers', add a new header with the key `Authorization` and the value `Bearer ` (replace `` with the `anon` `public` API key you copied earlier). - - - Supabase Edge Functions require a JSON Web Token [JWT](https://supabase.com/docs/guides/auth/jwts) - in the authorization header. This is to ensure that only authorized users can access your edge - functions. - - - Click 'Create webhook'.{" "} - -![How to create a new webhook 3](/images/supabase-create-webhook-3.png) - -Your Database Webhook is now ready to use. - -## Triggering the entire workflow + + + Open the `supabase-database` endpoint on the **Webhooks** page, choose **Generate secret**, then choose **Generate secret** again in the dialog. Copy the value: Trigger.dev shows it only once. Supabase has no signing-secret field, so the secret goes in a header in the next step. Copy the endpoint's **Webhook URL** too. + + Every delivery is rejected until the secret is set. + + + In the Supabase dashboard, open **Integrations > Database Webhooks**. If the **Overview** tab shows **Enable webhooks**, choose it. Then open the **Webhooks** tab and choose **Create webhook**: + + 1. Give it a name, such as `transcribe-video`. + 2. Select the `public` `video_transcriptions` table and the **Insert** event. + 3. Under **Type of webhook**, choose **HTTP Request**, with the method `POST` and the endpoint's **Webhook URL**. + 4. Under **HTTP Headers**, add a header named `Authorization` with the value `Bearer ` (capital B, one space), using the secret you generated. + 5. Create the webhook. + + -Your `video-processing-handler` Edge Function is now set up to trigger the `videoProcessAndUpdate` task every time a new row is inserted into your `video_transcriptions` table. +## Test it -To do this, go back to your Supabase project dashboard, click on 'Table Editor' in the left-hand menu, click on the `video_transcriptions` table , and then click 'Insert', 'Insert Row' . +Open the **Table Editor** , select the `video_transcriptions` table , and choose **Insert** > **Insert row** . ![How to insert a new row 1](/images/supabase-new-table-3.png) -Add a new item under `video_url`, with a public video url. . - -You can use the following public video URL for testing: `https://content.trigger.dev/Supabase%20Edge%20Functions%20Quickstart.mp4`. +Set `video_url` to a public video URL , such as `https://content.trigger.dev/Supabase%20Edge%20Functions%20Quickstart.mp4`, then choose **Save**. ![How to insert a new row 2](/images/supabase-new-table-4.png) -Once the new table row has been inserted, check your [cloud.trigger.dev](https://cloud.trigger.dev) project 'Runs' list and you should see a processing `videoProcessAndUpdate` task which has been triggered when you added a new row with the video url to your `video_transcriptions` table. - -![Supabase successful run](/images/supabase-run-result.png) - -Once the run has completed successfully, go back to your Supabase `video_transcriptions` table, and you should see that in the row containing the original video URL, the transcription has now been added to the `transcription` column. +The delivery appears on the `supabase-database` endpoint's **Deliveries** tab, and its detail page links to the `transcribe-video` run it started. When the run completes, the row's `transcription` column holds the transcript. ![Supabase successful table update](/images/supabase-table-result.png) -**Congratulations! You have completed the full workflow from Supabase to Trigger.dev and back again.** +If no delivery appears, check the webhook URL and the `Authorization` header in Supabase. A delivery marked **Filtered** wasn't an insert into `video_transcriptions`. diff --git a/docs/guides/frameworks/webhooks-guides-overview.mdx b/docs/guides/frameworks/webhooks-guides-overview.mdx index 4c0a4404276..ef18435e18c 100644 --- a/docs/guides/frameworks/webhooks-guides-overview.mdx +++ b/docs/guides/frameworks/webhooks-guides-overview.mdx @@ -1,16 +1,70 @@ --- title: "Using webhooks with Trigger.dev" sidebarTitle: "Overview" -description: "Guides for using webhooks with Trigger.dev." +description: "Receive provider webhooks on hosted, verified Trigger.dev endpoints, or trigger tasks from a webhook handler in your own app." --- -## Overview +**Trigger.dev hosts webhook endpoints for you: register one URL with a provider, and each verified event runs the subscribed tasks whose filters match it.** You don't write a route handler, verify signatures, or call `tasks.trigger()` yourself. -Webhooks are a way to send and receive events from external services. Triggering tasks using webhooks allow you to add real-time, event driven functionality to your app. +There are two ways to run tasks from webhooks: -A webhook handler is code that executes in response to an event. They can be endpoints in your framework's routing which can be triggered by an external service. +- **Hosted webhook endpoints (recommended):** Trigger.dev receives the request, verifies it, records it as a delivery you can inspect and replay, and runs your subscribed tasks. +- **Your own handler:** a route in your app receives the request, verifies it, and triggers a task with `tasks.trigger()`. Use this when the HTTP response has to come from your app, for example to return a result to the caller, or when no [source](/webhooks/sources) can verify the provider's requests. -## Webhook guides +## Receive webhooks on a hosted endpoint + +Declare an endpoint with a [source](/webhooks/sources), then subscribe tasks to it with `webhook()`: + +```ts /trigger/stripe.ts +import { webhook, webhooks } from "@trigger.dev/sdk"; + +export const stripe = webhooks.endpoint.define({ + id: "stripe", + source: webhooks.stripe(), +}); + +export const fulfillOrder = webhook({ + id: "fulfill-order", + endpoint: stripe, + filter: "event.type == 'checkout.session.completed'", + onEvent: async ({ event }) => { + console.log("Fulfilling", event.data.object.id); + }, +}); +``` + +When you deploy or run `trigger dev`, the endpoint appears on the environment's **Webhooks** page with its URL. Register that URL with Stripe and store the signing secret, and each `checkout.session.completed` event runs `fulfill-order`. + +Hosted endpoints give you: + +- **Verification for 40+ providers**, including Stripe, GitHub, Clerk, Resend, Shopify, Linear, Supabase and Hookdeck, plus `webhooks.custom()` for other HMAC, public-key or shared-secret schemes. +- **Filters per subscriber**, so one endpoint can route checkout events to one task and refunds to another. +- **Deliveries you can inspect and replay**, with the payload, headers and the runs each event started. +- **Waiters**, which pause a run until a matching event arrives, without using compute while it waits. +- **[Agent routing](/webhooks/session-routing)**, which sends events into a `chat.agent` session, including agents that live in Slack and Linear. + +Webhooks are in [public beta](/webhooks/public-beta) and need `@trigger.dev/sdk` 4.8.1 or later. + +| Page | What it covers | +| --- | --- | +| [Webhooks overview](/webhooks/overview) | Endpoints, subscribers, and the `onEvent` handler. | +| [Sources](/webhooks/sources) | Every supported provider and custom verification. | +| [Connect a provider](/webhooks/connect) | Register the URL and signing secret, by hand or with an AI coding agent. | +| [Deliveries](/webhooks/deliveries) | Inspect payloads, replay deliveries, and see the runs each one started. | +| [Filters](/webhooks/filters) | Choose which events each subscriber takes. | +| [Waiters](/webhooks/waiters) | Pause a run until a matching webhook arrives. | +| [Session routing](/webhooks/session-routing) | Route each event to a durable agent session by key. | +| [Channels](/webhooks/channels) | Turn a webhook into a chat frontend for an agent. | +| [Human-in-the-loop](/webhooks/human-in-the-loop) | Approvals and interactive controls over a channel. | +| [Slack agents](/webhooks/slack) and [Linear agents](/webhooks/linear) | Turn a `chat.agent` into an agent that lives in Slack or Linear. | +| [Stripe webhooks](/guides/examples/stripe-webhook) | Run a task when a Stripe checkout completes. | +| [Supabase database webhooks](/guides/frameworks/supabase-edge-functions-database-webhooks) | Run a task when a row is inserted into a Supabase table. | +| [Hookdeck webhooks](/guides/examples/hookdeck-webhook) | Forward events from a Hookdeck connection to a hosted endpoint. | +| [Resend email agent](/guides/example-projects/resend-email-agent) | An agent that drafts replies to a Resend inbox and waits for approval in Slack. | + +## Trigger tasks from your own webhook handler + +These guides receive the webhook in your app and trigger a task from the handler: - How to create a webhook handler in a Next.js app, and trigger a task from it. + Create a webhook handler in a Next.js app and trigger a task from it. - How to create a webhook handler in a Remix app, and trigger a task from it. - - - How to create a Stripe webhook handler and trigger a task when a 'checkout session completed' - event is received. - - - Use Hookdeck to receive webhooks and forward them to Trigger.dev tasks with logging and replay - capabilities. - - - Learn how to trigger a task from a Supabase edge function when an event occurs in your database. + Create a webhook handler in a Remix app and trigger a task from it. diff --git a/docs/guides/introduction.mdx b/docs/guides/introduction.mdx index d354fea6ae3..9f012123c7a 100644 --- a/docs/guides/introduction.mdx +++ b/docs/guides/introduction.mdx @@ -36,10 +36,9 @@ Get set up fast using our detailed walk-through guides. | [Python document to markdown](/guides/python/python-doc-to-markdown) | Use Python and MarkItDown to convert documents to markdown | | [Python PDF form extractor](/guides/python/python-pdf-form-extractor) | Use Python, PyMuPDF and Trigger.dev to extract data from a PDF form | | [Python web crawler](/guides/python/python-crawl4ai) | Use Python, Crawl4AI and Playwright to create a headless web crawler | -| [Sequin database triggers](/guides/frameworks/sequin) | Trigger tasks from database changes using Sequin | -| [Stripe webhooks](/guides/examples/stripe-webhook) | Trigger tasks from incoming Stripe webhook events | -| [Hookdeck webhooks](/guides/examples/hookdeck-webhook) | Use Hookdeck to receive webhooks and forward them to Trigger.dev tasks | -| [Supabase database webhooks](/guides/frameworks/supabase-edge-functions-database-webhooks) | Trigger tasks using Supabase database webhooks | +| [Stripe webhooks](/guides/examples/stripe-webhook) | Run a task from Stripe events on a hosted, verified endpoint | +| [Hookdeck webhooks](/guides/examples/hookdeck-webhook) | Forward events from a Hookdeck connection to a hosted endpoint | +| [Supabase database webhooks](/guides/frameworks/supabase-edge-functions-database-webhooks) | Run a task when a row is inserted, using a hosted endpoint | | [Supabase edge function hello world](/guides/frameworks/supabase-edge-functions-basic) | Trigger tasks from Supabase edge function | | [Using webhooks in Next.js](/guides/frameworks/nextjs-webhooks) | Trigger tasks from a webhook in Next.js | | [Using webhooks in Remix](/guides/frameworks/remix-webhooks) | Trigger tasks from a webhook in Remix | diff --git a/docs/guides/use-cases/data-processing-etl.mdx b/docs/guides/use-cases/data-processing-etl.mdx index f6bfdd65819..42d44718aeb 100644 --- a/docs/guides/use-cases/data-processing-etl.mdx +++ b/docs/guides/use-cases/data-processing-etl.mdx @@ -28,7 +28,7 @@ Build complex data pipelines that process large datasets without timeouts. Handl icon="book" href="/guides/frameworks/supabase-edge-functions-database-webhooks" > - Trigger tasks from Supabase database webhooks. + Run a task when a row is inserted, using a hosted endpoint. diff --git a/docs/idempotency.mdx b/docs/idempotency.mdx index 26065505ee2..ab8e1478312 100644 --- a/docs/idempotency.mdx +++ b/docs/idempotency.mdx @@ -36,7 +36,7 @@ Other common use cases include: - **Preventing duplicate emails** - Trigger the email task once, even if the parent task retries - **Avoiding double-charging customers** - Trigger the payment task once, even if the parent task retries. The payment API call itself still needs the provider's own idempotency key, see [Side effects inside `run()`](#side-effects-inside-run) - **One-time setup tasks** - Trigger initialization or migration tasks once -- **Deduplicating webhook processing** - Trigger the handler task once per webhook event, even if the event is delivered multiple times +- **Deduplicating webhook processing** - Trigger the handler task once per webhook event, even if the event is delivered multiple times. [Hosted webhook endpoints](/webhooks/deliveries#deduplication) deduplicate provider retries within a time window, using the provider's event ID when the source maps one ## Side effects inside `run()` diff --git a/docs/images/sequin-consumer-config.png b/docs/images/sequin-consumer-config.png deleted file mode 100644 index 4409c065d9b..00000000000 Binary files a/docs/images/sequin-consumer-config.png and /dev/null differ diff --git a/docs/images/sequin-final-run.png b/docs/images/sequin-final-run.png deleted file mode 100644 index 0461f5510b4..00000000000 Binary files a/docs/images/sequin-final-run.png and /dev/null differ diff --git a/docs/images/sequin-intro.png b/docs/images/sequin-intro.png deleted file mode 100644 index 4be9cad73e7..00000000000 Binary files a/docs/images/sequin-intro.png and /dev/null differ diff --git a/docs/images/sequin-register-task.png b/docs/images/sequin-register-task.png deleted file mode 100644 index 9ab16b08474..00000000000 Binary files a/docs/images/sequin-register-task.png and /dev/null differ diff --git a/docs/images/sequin-sort-and-filter.png b/docs/images/sequin-sort-and-filter.png deleted file mode 100644 index c2d877675e4..00000000000 Binary files a/docs/images/sequin-sort-and-filter.png and /dev/null differ diff --git a/docs/images/sequin-trace.png b/docs/images/sequin-trace.png deleted file mode 100644 index f5e6ff696c0..00000000000 Binary files a/docs/images/sequin-trace.png and /dev/null differ diff --git a/docs/images/supabase-api-key.png b/docs/images/supabase-api-key.png deleted file mode 100644 index 612c2cf4cd1..00000000000 Binary files a/docs/images/supabase-api-key.png and /dev/null differ diff --git a/docs/images/supabase-create-webhook-1.png b/docs/images/supabase-create-webhook-1.png deleted file mode 100644 index 34eac7f0081..00000000000 Binary files a/docs/images/supabase-create-webhook-1.png and /dev/null differ diff --git a/docs/images/supabase-create-webhook-2.png b/docs/images/supabase-create-webhook-2.png deleted file mode 100644 index 0c21b485ec9..00000000000 Binary files a/docs/images/supabase-create-webhook-2.png and /dev/null differ diff --git a/docs/images/supabase-create-webhook-3.png b/docs/images/supabase-create-webhook-3.png deleted file mode 100644 index 269ab65becd..00000000000 Binary files a/docs/images/supabase-create-webhook-3.png and /dev/null differ diff --git a/docs/images/supabase-run-result.png b/docs/images/supabase-run-result.png deleted file mode 100644 index 2e29f79393c..00000000000 Binary files a/docs/images/supabase-run-result.png and /dev/null differ diff --git a/docs/migration-n8n.mdx b/docs/migration-n8n.mdx index 680944c14cc..d331cc8df63 100644 --- a/docs/migration-n8n.mdx +++ b/docs/migration-n8n.mdx @@ -14,7 +14,7 @@ Your task code runs on Trigger.dev's managed infrastructure, so there are no ser | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | Workflow | [task](/tasks/overview) plus its config (queue, retry, onFailure) | | Schedule Trigger | [schedules.task](/tasks/scheduled) | -| Webhook node | Route handler + [task.trigger()](/triggering) | +| Webhook node | [Webhook endpoint](/webhooks/overview) + a [webhook()](/webhooks/overview#the-handler) task | | Node | A step or library call inside `run()` | | Execute Sub-workflow node (wait for completion) | [tasks.triggerAndWait()](/triggering#yourtask-triggerandwait) | | Execute Sub-workflow node (execute in background) | [tasks.trigger()](/triggering) | @@ -30,7 +30,7 @@ Your task code runs on Trigger.dev's managed infrastructure, so there are no ser | Execution | Run (visible in the dashboard with full logs) | | Retry on Fail (per-node setting) | [retry.maxAttempts](/tasks/overview#retry-options) (retries the whole `run()`, not a single step) | | AI Agent node | Any AI SDK called inside `run()` (Vercel AI SDK, Claude SDK, OpenAI SDK, etc.) | -| Respond to Webhook node | Route handler + [task.triggerAndWait()](/triggering#yourtask-triggerandwait) returning the result as HTTP response | +| Respond to Webhook node | Route handler + [tasks.trigger()](/triggering#tasks-trigger) and `runs.poll()`, returning the result as the HTTP response | --- @@ -50,7 +50,7 @@ Go to [Trigger.dev Cloud](https://cloud.trigger.dev), create an account, and cre npx trigger.dev@latest init ``` -This adds Trigger.dev to your project and creates a `trigger/` directory for your tasks. +This adds Trigger.dev to your project and creates a directory for your tasks (`src/trigger/` if your project uses `src`), set by `dirs` in `trigger.config.ts`. The examples below use `trigger/`. @@ -74,38 +74,75 @@ You'll get a local server that behaves like production. Your runs appear in the In n8n you use a **Webhook** trigger node, which registers a URL that starts the workflow. -In Trigger.dev, your existing route handler receives the webhook and triggers the task: +In Trigger.dev, declare a [hosted webhook endpoint](/webhooks/overview). Trigger.dev hosts its URL, verifies each request, and runs the tasks subscribed to it. This endpoint receives GitHub events and runs a task for each push: - +```ts trigger/github.ts +import { webhook, webhooks } from "@trigger.dev/sdk"; -```ts app/api/webhook/route.ts -import { processWebhook } from "@/trigger/process-webhook"; +export const github = webhooks.endpoint.define({ + id: "github", + source: webhooks.github(), +}); -export async function POST(request: Request) { - const body = await request.json(); +export const processPush = webhook({ + id: "process-push", + endpoint: github, + filter: "header.x-github-event == 'push'", + onEvent: async ({ event }) => { + console.log("Push to", event.ref); + }, +}); +``` - await processWebhook.trigger({ - event: body.event, - data: body.data, - }); +After you run the dev server or deploy, connect GitHub to the endpoint, the way you'd paste an n8n webhook URL: - return Response.json({ received: true }); -} -``` +1. Generate the endpoint's signing secret. Every delivery is rejected until it has one. This command saves it to `.env.local` without printing it (keep that file out of git): + + ```bash + npx trigger.dev@latest webhooks generate-secret github --env dev --to-env GITHUB_WEBHOOK_SECRET + ``` + + If you deployed, use `--env prod` instead, and copy the URL from the Production environment in the next step. + +2. Copy the endpoint's **Webhook URL** from the **Webhooks** page. +3. In the GitHub repository's **Settings > Webhooks**, add a webhook with that URL as the **Payload URL**, **Content type** set to `application/json`, the `GITHUB_WEBHOOK_SECRET` value from `.env.local` as the **Secret**, and **Just the push event** selected. + +GitHub sends a `ping` event as soon as the webhook is created. The filter skips it, so it shows as **Filtered** on the endpoint's **Deliveries** tab. Each push then starts a `process-push` run. See [Connect a provider](/webhooks/connect) for other providers. + +The endpoint also verifies the provider's signature, which an n8n Webhook node doesn't do on its own. [Sources](/webhooks/sources) cover 40+ providers, and `webhooks.custom()` handles most other signature and shared-secret schemes. + +A hosted endpoint responds as soon as it accepts the delivery. To return a task's result in the HTTP response, as n8n's **Respond to Webhook** node does, use a route handler in your own app that triggers the task with [tasks.trigger()](/triggering#tasks-trigger) and waits for the result with `runs.poll()`: ```ts trigger/process-webhook.ts import { task } from "@trigger.dev/sdk"; export const processWebhook = task({ id: "process-webhook", - run: async (payload: { event: string; data: Record }) => { - // handle the webhook payload - await handleEvent(payload.event, payload.data); + run: async (payload: { event: string }) => { + return { received: payload.event }; }, }); ``` - +```ts app/api/webhook/route.ts +import { runs, tasks } from "@trigger.dev/sdk"; +import type { processWebhook } from "@/trigger/process-webhook"; + +export async function POST(request: Request) { + const body = await request.json(); + + const handle = await tasks.trigger("process-webhook", body); + const run = await runs.poll(handle, { pollIntervalMs: 1000 }); + + if (!run.isSuccess) { + return Response.json({ error: `Run ${run.id} ended with status ${run.status}` }, { status: 500 }); + } + + return Response.json(run.output); +} +``` + +The task's return value becomes `run.output`. The request stays open until the run finishes, so keep the task short enough for your host's request time limit. The route handler needs `TRIGGER_SECRET_KEY` in your app's environment; see [API keys](/apikeys). --- diff --git a/docs/snippets/examples-cards.mdx b/docs/snippets/examples-cards.mdx index 41333536e22..b40e4a5240d 100644 --- a/docs/snippets/examples-cards.mdx +++ b/docs/snippets/examples-cards.mdx @@ -10,8 +10,8 @@ Deepgram, FFmpeg, Puppeteer, Stripe, Supabase and more. - Learn how to trigger tasks from webhooks, including Next.js, Remix, Supabase and Stripe and - more. + Receive webhooks on hosted, verified endpoints, or trigger tasks from a handler in your own + app. Full-stack projects demonstrating how to use Trigger.dev. Fork them in GitHub as a starting diff --git a/docs/snippets/supabase-docs-cards.mdx b/docs/snippets/supabase-docs-cards.mdx index e8feb68da0d..575d7053924 100644 --- a/docs/snippets/supabase-docs-cards.mdx +++ b/docs/snippets/supabase-docs-cards.mdx @@ -15,7 +15,8 @@ icon="book" href="/guides/frameworks/supabase-edge-functions-database-webhooks" > - Learn how to trigger a task from a Supabase edge function when an event occurs in your database. + Run a task when a row is inserted into a table, using a Supabase database webhook that posts + to a hosted webhook endpoint.