Build an AI onboarding agent with Clerk and Trigger.dev

Timonwa Akintokun

Timonwa Akintokun

Guest author

Image for Build an AI onboarding agent with Clerk and Trigger.dev

Most products send every new user the same welcome email: "Welcome to Acme! Here are three ways to get started." It would be nicer to send each new sign-up an email written just for them, but past a handful of sign-ups, nobody has time to write them.

In this article, we'll build Brandnote, a small AI marketing tool. When someone signs up:

  • Clerk sends a user.created webhook.
  • Trigger.dev starts an AI agent that reads the new user's website.
  • The agent sets up their workspace from what it learns about their brand.
  • It drafts a welcome email just for them, and someone on your team approves it before it goes out.

Here's the whole thing running, from sign-up to the email landing in an inbox.

It isn't too hard to get an agent to do something but this is built to work in production:

  • It has to wait for that approval, even if it takes days, without you keeping a server running.
  • If Clerk sends the same sign-up twice, the user should only be onboarded once.
  • If the AI model is busy, the agent should wait and try again instead of failing.

Trigger.dev handles all of this.

Brandnote’s architecture

Clerk handles sign-up and sends a user.created webhook when someone signs up. That webhook starts the agent.

On Trigger.dev, the agent is a task, a long-running function that Trigger.dev runs and retries if it fails. Each time a task runs, that’s a run. A run can start from an inbound webhook, like Clerk’s, and pause on a wait token until your code completes it, for example when someone clicks approve.

Brandnote's architecture. A new user signs up through Brandnote's form and Clerk. Clerk's user.created webhook starts the onboard-new-user run on Trigger.dev, which reads their website, saves the workspace and a welcome email draft to Supabase, waits for approval from the /admin page, then sends the email through Zoho CPaaS to their inbox.

Prerequisites

This demo uses Next.js, Clerk, Supabase, Gemini through the AI SDK, and Zoho CPaaS. You’ll need:

  • Node.js 22 or later and pnpm
  • Accounts with Clerk, Supabase, Trigger.dev, Google AI Studio (for a Gemini API key), and Zoho CPaaS

You don’t have to use the same stack. Trigger.dev only needs a webhook from your auth provider when someone signs up, so your front end, database, AI model, and email service can be whatever you already use.

Three ways to use this project

  • Run the finished app from the main branch of the Brandnote repo.
  • Add the agent to your own app by pointing Cursor or Claude Code at this post, with the Trigger.dev MCP server installed.
  • Build it yourself from the starter branch, which has everything except the agent. The rest of this post walks through it step by step.

Set up the starter app

Clone the Brandnote repo, check out the starter branch, and install the dependencies.


git clone https://github.com/jackbridger/clerk-onboarding-agent
cd clerk-onboarding-agent
git checkout starter
pnpm install

Copy .env.example to .env.local and fill in your Clerk, Supabase, and Zoho CPaaS keys. The README lists where to find each one.


cp .env.example .env.local

Next, set up Supabase and Clerk.

  1. In your Supabase project’s SQL editor, run supabase/schema.sql to create the tables.
  2. In Clerk, under User & authentication, turn on First and last name. The welcome email greets people by their first name.

Start the app with pnpm dev. Then, in a second terminal, invite yourself as an admin. Clerk emails you a link, and the script prints it too. Once you open the link and finish signing up, you’ll land on the /admin page.


pnpm invite-admin [email protected]

Use a different email address from the one you’ll test sign-ups with. Admins join by invitation, so the agent never treats them as a new customer.

The starter is a Next.js app with everything in Brandnote except the agent:

  • A two-step sign-up, with a form for the business name, website, and role, then Clerk’s own sign-up form. The answers are saved on the new Clerk user as unsafeMetadata, which is where our agent will read them.
  • The /workspace page, where a customer sees their brand profile, brand voice, and customer profiles
  • The /admin page, where someone on your team edits welcome drafts and approves them
  • Two Supabase tables, workspaces and welcome_drafts, where the agent’s work is saved

What the agent gets from sign-up

FieldAsked onUsed for
Business nameBrandnote’s formWhose site the agent is reading, and the workspace name
WebsiteBrandnote’s formWhere the agent starts reading
RoleBrandnote’s formWhich line about how Brandnote helps goes in the email
Name and emailClerk’s formThe greeting, and where the email goes

Each role (founder, marketing team, agency, freelancer, or something else) has its own line. The code picks it, and the agent works it into the email in its own words.

Now sign up with a test account. Your workspace will say “Setting up” until we add the agent.

Set up your Trigger.dev project

  1. Sign up for Trigger.dev and create an organization and a project, or use a project you already have.
  2. Copy the project ref from the project’s settings. It starts with proj_, and you’ll need it in the next section.
  3. In the project’s Development environment, open API keys, create a new key, and pick Waitpoints only. The app only uses it to resume the waiting agent once an admin approves the email.
  4. Copy the key straight away, because Trigger.dev shows it only once, and add it to .env.local as TRIGGER_SECRET_KEY.
The New API key dialog in Trigger.dev's Development environment, with the Waitpoints only access preset

Add Trigger.dev to the project

Install the SDK and the CLI.


pnpm add @trigger.dev/sdk
pnpm add -D trigger.dev

The CLI needs esbuild’s install script. The starter already allows it, but in your own project pnpm may stop with ERR_PNPM_IGNORED_BUILDS. If it does, run pnpm approve-builds and allow esbuild.

Then create trigger.config.ts in the project root, with the project ref you copied, to tell Trigger.dev which project this is and where your tasks live.


// trigger.config.ts
import { defineConfig } from "@trigger.dev/sdk";
export default defineConfig({
// Your project ref, from the Trigger.dev dashboard's project settings.
project: "<your-project-ref>",
dirs: ["./src/trigger"],
// Counts compute time only: while the agent waits for an approval, the clock is stopped.
maxDuration: 300,
retries: {
enabledInDev: true,
default: {
maxAttempts: 3,
minTimeoutInMs: 1000,
maxTimeoutInMs: 10000,
factor: 2,
randomize: true,
},
},
});

maxDuration caps a run’s compute time, in seconds. retries sets the default retry policy for every task, and it’s on in dev too, so you see the same behavior locally.

Add a script to package.json to start Trigger.dev’s dev server with pnpm.


// package.json
"dev:trigger": "trigger dev"

Log in and start the dev server in a second terminal, next to pnpm dev.


pnpm exec trigger login
pnpm dev:trigger

Once you see Local worker ready, Trigger.dev is watching src/trigger for tasks. Lines marked “Error” that mention punycode or localStorage are Node.js warnings that depend on your Node.js version. They don’t affect your tasks.

Create the onboarding task

Before anything can react to a sign-up, we need the task that does the onboarding. Create src/trigger/onboard-new-user.ts with the imports and a Clerk client. signUpAnswersSchema is already in the starter, so we only import it.


// src/trigger/onboard-new-user.ts
import { logger, schemaTask } from "@trigger.dev/sdk";
import { createClerkClient } from "@clerk/backend";
import { z } from "zod";
import { signUpAnswersSchema } from "../lib/sign-up-answers";
const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });

Below the Clerk client, add the task. For now, it looks the new user up and skips admins.


// src/trigger/onboard-new-user.ts
export const onboardNewUser = schemaTask({
id: "onboard-new-user",
schema: z.object({ userId: z.string() }),
run: async ({ userId }) => {
// The payload is only an ID. Fetching the user here means no personal data sits in old payloads.
const user = await clerk.users.getUser(userId);
if (user.publicMetadata.role === "admin") {
logger.info("Skipping an admin account");
return { status: "skipped", reason: "admin" };
}
},
});

When we connect Clerk, the task receives only a user ID, not the whole Clerk payload, and fetches everything else itself. It always works with the user as they are now.

Admins sign up too. They join by invitation with the admin role already on their account, which is how the task tells them apart from customers.

Inside run, below the admin check, read the sign-up answers and the user’s email. A user without them has nothing for the agent to work with.


// src/trigger/onboard-new-user.ts
const answers = signUpAnswersSchema.safeParse(user.unsafeMetadata);
const email = user.primaryEmailAddress?.emailAddress;
if (!answers.success || !email) {
logger.warn("User has no sign-up answers or email", { userId });
return { status: "skipped", reason: "missing sign-up answers" };
}
// The agent goes here.

You can try the task before Clerk is connected. Find your test user’s ID under Users in Clerk. Then, in the Trigger.dev dashboard, open Tasks, click Test next to onboard-new-user, use this payload with that ID, and click Run test.


{ "userId": "user_..." }

The run finishes as Completed, with no output yet, because the agent isn’t there. To see the admin check work, run it again with your admin account’s ID. That run’s output is { "status": "skipped", "reason": "admin" }.

A completed onboard-new-user run for the Clerk onboarding agent in Trigger.dev, with the log “Skipping an admin account” and the output status skipped, reason admin

Receive Clerk’s user.created webhook

Now let’s have Clerk start that task every time someone signs up. Create src/trigger/clerk-webhook.ts with a Clerk endpoint.


// src/trigger/clerk-webhook.ts
import { idempotencyKeys, webhook, webhooks } from "@trigger.dev/sdk";
import type { WebhookEvent } from "@clerk/backend";
import { onboardNewUser } from "./onboard-new-user";
// Verifies Clerk's signature on every delivery before anything runs.
export const clerk = webhooks.endpoint.define({
id: "clerk",
source: webhooks.clerk<WebhookEvent>(),
});

Trigger.dev also stores each delivery before it answers Clerk, and answers a retried event as a duplicate. If you’re curious how that plumbing works, the Trigger.dev team wrote up how they built webhooks.

Below the endpoint, add the webhook task that starts the onboarding task.


// src/trigger/clerk-webhook.ts
export const clerkUserCreated = webhook({
id: "clerk-user-created",
endpoint: clerk,
filter: "event.type == 'user.created'",
onEvent: async ({ event }) => {
// Global scope: one onboarding per user, even if the event is resent later.
const idempotencyKey = await idempotencyKeys.create(`onboard-${event.data.id}`, {
scope: "global",
});
await onboardNewUser.trigger({ userId: event.data.id }, { idempotencyKey });
},
});

The filter means only user.created events start a run, and it narrows the event’s type, so event.data.id is typed. The idempotency key covers the last gap. Trigger.dev already drops Clerk’s automatic retries, but someone could resend the event from Clerk’s dashboard later. A key passed to trigger() inside a run is scoped to that run by default, so scope: "global" is what makes it one onboarding per user, for as long as the key is kept (30 days by default).

Next, connect the two dashboards.

  1. In Trigger.dev, open Webhooks, select the clerk endpoint, and copy its URL.
  2. In Clerk, open Webhooks, add an endpoint with that URL, and subscribe it to user.created.
  3. Copy Clerk’s signing secret, which starts with whsec_, and paste it into Set signing secret on the Trigger.dev endpoint.
The clerk webhook endpoint in Trigger.dev, with its webhook URL under Connect Clerk's Webhooks page with the Trigger.dev endpoint URL added

Until the signing secret is set, Trigger.dev rejects every delivery, so if sign-ups aren’t starting runs, check this first.

Now sign up a test customer. In Trigger.dev, open the clerk endpoint’s Deliveries tab and the new delivery. Its timeline shows the delivery arriving and the run it started.

A succeeded user.created delivery on the clerk endpoint in Trigger.dev, with Clerk's event and the run it started in the timeline

That run has Clerk's user.created event as its payload, and a trigger() call starting onboard-new-user.

A completed clerk-user-created run in Trigger.dev, with Clerk's user.created event as its payload and a trigger() call

My own admin sign-up ended up being my first real test. The webhook fired, the task ran, and it stopped with {"status":"skipped","reason":"admin"}, exactly as it should.

Give the agent tools to read the site and save the workspace

Now that the agent has a real person to work on, it needs to learn about their business. Install the AI SDK with its Gemini provider and OpenTelemetry adapter, then add your Gemini key to .env.local as GOOGLE_GENERATIVE_AI_API_KEY.


pnpm add ai @ai-sdk/google @ai-sdk/otel

Unless a snippet says otherwise, everything from here on goes in src/trigger/onboard-new-user.ts. Add these imports below the existing ones, for the AI SDK, readPage and isSameSite, and the starter’s workspace functions.


// src/trigger/onboard-new-user.ts
import { generateText, hasToolCall, isStepCount, registerTelemetry, tool } from "ai";
import { google } from "@ai-sdk/google";
import { OpenTelemetry } from "@ai-sdk/otel";
import { isSameSite, readPage } from "../lib/read-page";
import {
brandProfileSchema,
brandVoiceSchema,
completeWorkspace,
customerProfileSchema,
failWorkspace,
startWorkspace,
} from "../lib/workspaces";

Now set up the model, above const clerk. The first line makes every model call and tool call show up in the run trace, through its built-in LLM observability. You’ll want that the first time the agent does something surprising.


// src/trigger/onboard-new-user.ts
// Turns every AI SDK call below into a span in the run trace, with its prompts and tool calls.
registerTelemetry(new OpenTelemetry());
// || rather than ??, because the starter leaves GEMINI_MODEL empty
const model = google(process.env.GEMINI_MODEL || "gemini-3.8-flash");
// Free-tier Gemini often answers "high demand" for a few seconds; back off and retry instead of failing.
const MODEL_RETRIES = 5;
const MAX_PAGES = 5;

Below const clerk, add the shape of what the agent saves: the brand profile, brand voice, and customer profiles. The schemas for each already exist in the starter.


// src/trigger/onboard-new-user.ts
const workspaceSchema = z.object({
brandProfile: brandProfileSchema,
brandVoice: brandVoiceSchema,
customerProfiles: z.array(customerProfileSchema).min(1).max(2),
});

The agent also writes a two-sentence note for whoever approves the welcome email, saying what the business does and how sure the agent is about it. Add it to workspaceSchema, below customerProfiles.


// src/trigger/onboard-new-user.ts
noteForAdmin: z
.string()
.describe(
[
"A note that helps the Brandnote admin decide, in a few seconds, whether to approve this customer's welcome as it is or edit it first.",
"Two short sentences in plain words, written to the admin about the customer (they, their).",
"Sentence 1: what the business does and who for.",
"Sentence 2: how sure you are. If something was unclear, say what and which part of the email to check, e.g. \"Their site had little text, so the customer profiles and the line about what they do are a best guess; check that paragraph.\" If everything was clear: \"Their site was clear, so the welcome should be accurate.\"",
"Don't judge the role or anything else they gave at sign-up, don't summarize the email, don't copy their site's wording, don't address the customer, and don't list the pages or tools you used.",
].join(" "),
),

Now replace the // The agent goes here. line with this setup. The task marks the workspace as “Setting up” and keeps track of the pages the agent reads and what it saves.


// src/trigger/onboard-new-user.ts
const { businessName, website, audience } = answers.data;
await startWorkspace({ userId, businessName, website, audience });
// 1. Research the site and set up the workspace.
const pagesRead: string[] = [];
let saved: z.infer<typeof workspaceSchema> | undefined;

Below let saved, add the agent itself, a generateText call saved as research. It reads the link first, decides what else to read, and stops once it has saved the workspace.


// src/trigger/onboard-new-user.ts
const research = await generateText({
model,
maxRetries: MODEL_RETRIES,
system: [
"You are Brandnote's onboarding agent. You set up a new customer's brand from their website.",
"Read the link they gave first. Then pick the other pages on the same site that say most about what they sell, who they sell to and how they sound, such as About, Pricing, a product page or a case study.",
`Read at most ${MAX_PAGES} pages in total. Skip blog archives, legal pages and log-in pages.`,
"Base everything on what the pages say. Don't invent facts, customers or numbers.",
"When you have enough, call saveWorkspace once.",
].join("\n"),
prompt: `Business name: ${businessName}\nLink: ${website}`,
tools: {
},
stopWhen: [hasToolCall("saveWorkspace"), isStepCount(MAX_PAGES + 3)],
});
if (!saved) {
throw new Error(`The agent stopped without saving a workspace: ${research.finishReason}`);
}
// The welcome email goes here.

The agent gets two tools, readPage to read the site and saveWorkspace to save what it learns. Inside tools, add readPage first. It fetches one page of the user’s site and returns its text and links, so the agent can decide what to read next, like the About or Pricing page. It fetches whatever website a new user enters, so before you open sign-ups to the public, limit it to public addresses, including after redirects.


// src/trigger/onboard-new-user.ts
readPage: tool({
description:
"Read one page on the customer's site. Returns its text and the links on it.",
inputSchema: z.object({ url: z.url() }),
execute: async ({ url }) => {
if (!isSameSite(url, website)) {
return { error: `Only pages on ${new URL(website).hostname} can be read.` };
}
if (pagesRead.length >= MAX_PAGES) {
return { error: "Page limit reached. Save the workspace with what you have." };
}
try {
const page = await readPage(url);
pagesRead.push(page.url);
return page;
} catch (error) {
return { error: error instanceof Error ? error.message : "Couldn't read the page" };
}
},
}),

The two checks at the top of execute keep the agent on the customer’s own site and stop it after MAX_PAGES pages. Clear limits like these are one of the lessons in 7 things the Trigger.dev team wished they’d known before building an AI chat agent.

Below readPage, still inside tools, add saveWorkspace. The agent calls it once it has read enough, to save the brand profile, brand voice, and customer profiles to the customer’s workspace.


// src/trigger/onboard-new-user.ts
saveWorkspace: tool({
description: "Save the customer's brand profile, brand voice and customer profiles.",
inputSchema: workspaceSchema,
execute: async (workspace) => {
await completeWorkspace(userId, { ...workspace, pagesRead });
saved = workspace;
return { saved: true };
},
}),

On Gemini’s free tier, my first real run failed with “This model is currently experiencing high demand.” A busy model is normal, so plan for it. MODEL_RETRIES already gives each model call more tries. Add a retry policy and an onFailure hook to the task’s options, between schema and run.


// src/trigger/onboard-new-user.ts
retry: { maxAttempts: 4, minTimeoutInMs: 10_000, maxTimeoutInMs: 60_000, factor: 2 },
// Runs once every attempt has failed, so the user doesn't wait on "setting up" forever.
onFailure: async ({ payload }) => {
await failWorkspace(payload.userId);
},

Now a busy model slows a run down instead of failing it, and a run that really can’t finish says so instead of leaving someone on “Setting up” forever.

Sign up with another test customer and open the run. You’ll see the agent work through the site page by page, then save.

The run trace for the Clerk onboarding agent's onboard-new-user task, with Gemini calls and readPage tool calls step by step, ending in saveWorkspace

Write a personalized welcome email from a template

With the workspace saved, the agent has everything it needs to write a welcome email that sounds like it knows the person. Add Output to the ai import, and import the welcome templates from the starter.


// src/trigger/onboard-new-user.ts
import { generateText, hasToolCall, isStepCount, Output, registerTelemetry, tool } from "ai";
import { HOW_WE_HELP, WELCOME_RULES, WELCOME_STRUCTURE } from "../lib/welcome-templates";

Below workspaceSchema, add the shape of the email.


// src/trigger/onboard-new-user.ts
const welcomeSchema = z.object({
subject: z.string(),
body: z
.string()
.describe('The email in plain text, from the greeting to "Welcome aboard,". The signature is added after it.'),
});

Replace the // The welcome email goes here. line with the call that writes the email. The template’s structure and rules go in as the system prompt. For now the task returns the subject, so you can check it in the run’s output.


// src/trigger/onboard-new-user.ts
// 2. Write the welcome. Picking the audience's wording is plain code; writing inside it is the agent's job.
const workspaceUrl = `${process.env.APP_URL ?? "http://localhost:3000"}/workspace`;
const { output: welcome } = await generateText({
model,
maxRetries: MODEL_RETRIES,
output: Output.object({ schema: welcomeSchema }),
system: [
"You write Brandnote's welcome emails to new customers. Follow this structure, in order:",
...WELCOME_STRUCTURE,
"Rules:",
...WELCOME_RULES,
].join("\n"),
prompt: [
`First name: ${user.firstName ?? "(not given)"}`,
`Business: ${businessName} (${website})`,
`How we help: ${HOW_WE_HELP[audience]}`,
`Workspace link: ${workspaceUrl}`,
`What we set up from their website: ${JSON.stringify({
brandProfile: saved.brandProfile,
brandVoice: saved.brandVoice,
customerProfiles: saved.customerProfiles,
})}`,
].join("\n"),
});
return { status: "drafted", subject: welcome.subject };

The How we help line is where the role comes in. HOW_WE_HELP is already in the starter, so there’s nothing to add here. It maps each role to its line, and HOW_WE_HELP[audience] picks the one for the person’s role.


// src/lib/welcome-templates.ts
export const HOW_WE_HELP: Record<AudienceId, string> = {
founder:
"as a founder or business owner, their time goes fast. Brandnote helps them write posts, pitches and announcements that sound like them every time, without starting from a blank page.",
in_house:
"Brandnote keeps everyone on their team writing in one consistent voice, whoever is writing.",
agency:
"Brandnote sets up each client's brand in minutes, so they can start on the client work sooner.",
freelancer:
"Brandnote gets each client's brand right before they write the first draft.",
other: "Brandnote gives them a ready brand profile and voice, so everything they write sounds like them.",
};

Getting a prompt right is often trial and error, and the more specific your instructions are, the better the response. My first version gave the agent the workspace and asked for a welcome email. What came back read like a report, opening with “Brandnote has already read your website…”. Nothing told the model what a welcome email should look like. Writing the shape down in WELCOME_STRUCTURE fixed it.

WELCOME_STRUCTURE, also in src/lib/welcome-templates.ts, tells the agent to write every welcome email in this order:

  1. Welcome them by first name.
  2. Say what we see they do, in our own words.
  3. Say how Brandnote helps them, using the line their role picked.
  4. Say what’s already set up for them, with a link to their workspace.
  5. Sign off.

If your agent’s emails read like summaries, give it a template and the order you want things said in, not just the facts.

Wait for an admin to approve it

An agent writing to your customers on its own is a lot of trust on day one, so every welcome email waits for a person. Add wait to the @trigger.dev/sdk import and WELCOME_SIGNATURE to the welcome templates import, then import the draft functions from the starter.


// src/trigger/onboard-new-user.ts
import { logger, schemaTask, wait } from "@trigger.dev/sdk";
import {
HOW_WE_HELP,
WELCOME_RULES,
WELCOME_SIGNATURE,
WELCOME_STRUCTURE,
} from "../lib/welcome-templates";
import {
markWelcomeDraftFailed,
saveWelcomeDraft,
type WelcomeApproval,
} from "../lib/welcome-drafts";

Now replace the return { status: "drafted", ... } line with a wait token, which is what the run pauses on.


// src/trigger/onboard-new-user.ts
// 3. Wait for the admin. The run is paused while it waits, so a draft can sit for days.
const token = await wait.createToken({
timeout: "7d",
idempotencyKey: `welcome-approval-${userId}`,
});

Below the token, save the draft with the token’s ID so the admin page can find it. The signature is added here, so the agent never has to write it. Then wait.forToken pauses the run until someone approves the draft.


// src/trigger/onboard-new-user.ts
const draft = await saveWelcomeDraft({
userId,
email,
businessName,
audience,
subject: welcome.subject,
body: `${welcome.body.trim()}\n\n${WELCOME_SIGNATURE}`,
agentNote: saved.noteForAdmin,
tokenId: token.id,
});
const approval = await wait.forToken<WelcomeApproval>(token);
if (!approval.ok) {
await markWelcomeDraftFailed(draft.id);
return { status: "expired", draftId: draft.id };
}
// Sending goes here.

While the run is paused, nothing else in the task runs. If nobody approves it within seven days, the token times out, approval.ok is false, and the draft is marked failed.

The other half lives in the approve action, src/app/admin/actions.ts. Add the WelcomeApproval type to its welcome drafts import, and import wait.


// src/app/admin/actions.ts
import {
approveWelcomeDraft,
getWelcomeDraft,
type WelcomeApproval,
} from "@/lib/welcome-drafts";
import { wait } from "@trigger.dev/sdk";

Then, above await approveWelcomeDraft, complete the token with whatever the admin edited.


// src/app/admin/actions.ts
// Resume the paused agent first, so a failed resume never leaves a draft marked approved but unsent.
if (draft.tokenId) {
await wait.completeToken<WelcomeApproval>(draft.tokenId, { subject, body });
}

Ada's AI-written welcome email draft for a new Clerk sign-up on the /admin page, with the agent's note above the editable subject and email, and an Approve and send button

This is the part I like the most. On Trigger.dev Cloud, a waiting run is paused, and you aren’t charged for the time it spends paused. A draft can sit there over a weekend and not cost anything.

When you run this locally, the waiting run lives inside your trigger dev process. One of mine was canceled with TASK_RUN_STALLED_EXECUTING_WITH_WAITPOINTS after the CLI lost its connection, so keep it running from sign-up until the welcome email is sent and the run shows as completed. Deployed runs don’t have this problem: Trigger.dev Cloud snapshots a waiting run and shuts its machine down, so nothing on your side has to stay running.

Send the approved email

When the admin approves the draft on the /admin page, the run picks up exactly where it paused, with the approved subject and body in approval.output. Add markWelcomeDraftSent to the welcome drafts import, and import sendEmail from the starter.


// src/trigger/onboard-new-user.ts
import {
markWelcomeDraftFailed,
markWelcomeDraftSent,
saveWelcomeDraft,
type WelcomeApproval,
} from "../lib/welcome-drafts";
import { sendEmail } from "../lib/email";

Then replace the // Sending goes here. line with the send.


// src/trigger/onboard-new-user.ts
// 4. Send what the admin approved, edits included.
await sendEmail({
to: email,
toName: user.firstName ?? businessName,
subject: approval.output.subject,
text: approval.output.body,
});
await markWelcomeDraftSent(draft.id, approval.output);
return { status: "sent", draftId: draft.id, pagesRead };

markWelcomeDraftSent records in Supabase what was sent and when. Try it with a new sign-up. Within a few seconds of approving, the draft moves to “Sent” on the /admin page, and the welcome email lands in the new user’s inbox.

The personalized welcome email in the new Clerk user’s inbox, signed by Sam, Founder, Brandnote, with a link to their workspace

And that’s it, your onboarding agent is complete. If anything doesn’t work as expected, compare your code with the main branch of the Brandnote repo.

Extending this project

The same pattern works whenever a sign-up should start some work: a webhook starts an agent, the agent does the work, and a person checks it before anything goes out. A few ideas:

  • Research beyond their website with a search API.
  • Draft their first post in the brand voice the agent already worked out.
  • Draft replies when they answer the welcome email, with the same approval step.
  • Follow up if they don’t come back. Wait for Clerk’s session.created event, which fires when they sign in again, and send a follow-up if it doesn’t arrive within a week.
  • Skip approval for trusted roles once you’ve approved enough of their drafts without changes.

Conclusion

Every new user now gets a welcome email written for them, and your team only checks it before it goes out. Trigger.dev receives Clerk’s webhook, runs the agent, waits days for approval if needed, and keeps every page the agent read and every call it made in the run trace.

To set this up in your own account, follow the docs guide.

Resources

From the Trigger.dev docs:

Other resources:

Deploy your first agent today

Get set up in minutes, either on your own or with your coding assistant.

Start for free