Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Move welcome-user email onto defineJob

Kiran Kca645fc4a1cb
diff --git a/.agents/skills/jobs-define-job/SKILL.md b/.agents/skills/jobs-define-job/SKILL.md
new file mode 100644
index 0000000000..36388828d8
--- /dev/null
+++ b/.agents/skills/jobs-define-job/SKILL.md
@@ -0,0 +1,130 @@
+---
+name: jobs-define-job
+description: Add or migrate background jobs with defineJob, register them in jobLoaders, and dispatch via job.dispatch/dispatchBatch instead of qstash.publishJSON to a cron URL. Use when adding a QStash worker, converting a POST /api/cron route into a job, or when the user mentions defineJob, job handlers, /api/jobs/process, or background jobs.
+---
+
+# Background jobs: use defineJob
+
+Payload-driven QStash work goes through `defineJob`. Do **not** add a new HTTP route under `/api/jobs` — every job is executed by the existing [`apps/web/app/api/jobs/process/[jobName]/route.ts`](apps/web/app/api/jobs/process/[jobName]/route.ts).
+
+Keep using `withCron` for Vercel GET schedules and for cron scanners that have no job envelope. See the `cron-use-with-cron` skill for those.
+
+## File layout
+
+```
+apps/web/lib/jobs/
+├── index.ts # defineJob — do not edit unless changing the framework
+├── registry.ts # jobLoaders — register every new job here
+├── send-jobs.ts # envelope + QStash request builder
+└── handlers/
+ └── {name}-job.ts # one file per job
+```
+
+## 1. Create the handler
+
+Add `apps/web/lib/jobs/handlers/{name}-job.ts`. The `name` must be kebab-case and end in `-job` (enforced by `jobNameSchema`: `/^[a-z][a-z0-9]*(-[a-z0-9]+)*-job$/`).
+
+```ts
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const inputSchema = z.object({
+ programId: z.string(),
+ partnerId: z.string(),
+});
+
+export const unbanPartnerJob = defineJob({
+ name: "unban-partner-job",
+ schema: inputSchema,
+ defaults: {
+ retries: 3, // optional; QStash retries on 5xx
+ // queue: "unban-partner", // optional; named QStash queue
+ // flowControl: { key: "unban-partner", parallelism: 20 },
+ },
+ async handle(input) {
+ // skip (permanent / not found) → return (process route returns 2xx, QStash does not retry)
+ // transient failure → throw (process route returns 500, QStash retries)
+ },
+});
+```
+
+Export the const as camelCase `{name}Job` matching the kebab `name`.
+
+Reference handlers:
+
+- Simple skip/work: `unban-partner-job.ts`, `create-tremendous-campaign-job.ts`
+- Self-pagination: `folder-deleted-job.ts`, `domain-deleted-job.ts`, `partner-search-sync-job.ts`
+- `defaults.flowControl`: `partner-search-sync-job.ts`
+
+## 2. Register it
+
+Add a **static** `import()` in [`apps/web/lib/jobs/registry.ts`](apps/web/lib/jobs/registry.ts) `jobLoaders`. The object key must equal `defineJob({ name })`. Webpack code-splits each handler.
+
+```ts
+"unban-partner-job": () =>
+ import("./handlers/unban-partner-job").then((m) => m.unbanPartnerJob),
+```
+
+Do not register by editing the process route. `loadJob` throws if `job.name !==` the registry key.
+
+## 3. Dispatch from call sites
+
+Import the handler (not `qstash`) and call `dispatch` / `dispatchBatch`:
+
+```ts
+import { unbanPartnerJob } from "@/lib/jobs/handlers/unban-partner-job";
+
+await unbanPartnerJob.dispatch(
+ { workspaceId, programId, partnerId },
+ { label: partnerId },
+);
+
+await folderDeletedJob.dispatchBatch(
+ folderIds.map((folderId) => ({ folderId })),
+ ({ folderId }) => ({ label: folderId }),
+);
+```
+
+Per-dispatch options merge over `defaults`: `delay`, `notBefore`, `deduplicationId`, `retries`, `queue`, `flowControl`, `label`.
+
+Failed QStash publish is persisted to the jobs outbox automatically — do not catch-and-swallow unless even the outbox persist failing must not fail the source mutation (see `queue-partner-search-sync.ts`).
+
+Self-pagination: call `theJob.dispatch(nextPayload, { delay: 1 })` from `handle` (see `folder-deleted-job`, `partner-search-sync-job`).
+
+Do not call `job.execute` from app code. That is only for the process route (and cron drain shims below).
+
+## 4. Convert an existing cron worker
+
+1. Move the `withCron` body into `handle`. Replace `logAndRespond("skip…")` with `console.info` / `console.error` + `return`.
+2. Register + switch every `qstash.publishJSON` / `enqueueJSON` / `enqueueBatchJobs` targeting that cron URL to `job.dispatch` / `dispatchBatch`.
+3. Keep a thin POST shim at the old `/api/cron/...` URL that parses the **old** body (not the job envelope) and calls `job.execute(payload)`. That drains in-flight QStash messages. Do not add a shim for brand-new jobs.
+4. Delete cron-only helpers that moved with the handler.
+
+## Handle semantics
+
+| Outcome | What to do | HTTP from process route | QStash |
+| --- | --- | --- | --- |
+| Work done | `return` | 200 | stop |
+| Skip (not found, already done, env not configured) | `console.*` + `return` | 200 | stop |
+| Bad payload | throw `ZodError` (schema.parse) | 200 | stop (non-retryable) |
+| Transient failure | `throw` | 500 | retry |
+
+Unknown job names and invalid envelopes also return 2xx so QStash does not retry forever.
+
+## Do not use defineJob for
+
+- Vercel GET crons in `apps/web/vercel.json`
+- Scanners that only fan out work (the worker they enqueue can be a job)
+- Importers that republish continuation state to the same URL
+- `/api/cron/queue/retry` (job replay infrastructure)
+- Path-param identity (`/api/cron/links/[linkId]/…`) unless the id moves into the payload
+- Outbound webhook forwarding and postbacks
+
+## Do not
+
+- Add a new `/api/jobs/...` route or a new `/api/cron/...` POST worker for payload-driven work.
+- Call `qstash.publishJSON` / `enqueueJSON` / `enqueueBatchJobs` with `/api/jobs/process/...` — use `dispatch`.
+- Register jobs with a dynamic `import()` that webpack cannot statically analyze, or a key that differs from `defineJob({ name })`.
+- Name a job without the `-job` suffix.
+- Use `job.execute` at dispatch call sites.
+- Run `pnpm build` after adding a job.
diff --git a/apps/web/app/(ee)/api/cron/welcome-user/route.ts b/apps/web/app/(ee)/api/cron/welcome-user/route.ts
index 20defda49e..16974e01c1 100644
--- a/apps/web/app/(ee)/api/cron/welcome-user/route.ts
+++ b/apps/web/app/(ee)/api/cron/welcome-user/route.ts
@@ -1,108 +1,11 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { generateUnsubscribeToken } from "@/lib/email/unsubscribe-token";
-import { prisma } from "@/lib/prisma";
-import { sendEmail } from "@dub/email";
-import WelcomeEmail from "@dub/email/templates/welcome-email";
-import WelcomeEmailPartner from "@dub/email/templates/welcome-email-partner";
-import { APP_DOMAIN, PARTNERS_DOMAIN } from "@dub/utils";
+import { withCron } from "@/lib/cron/with-cron";
+import { welcomeUserJob } from "@/lib/jobs/handlers/welcome-user-job";
+import { logAndRespond } from "../utils";
export const dynamic = "force-dynamic";
-/*
- This route is used to send a welcome email to new users + subscribe them to the corresponding Resend audience
- It is called by QStash 45 minutes after a user is created.
-
- Trial sequence: users who later start a paid-plan trial also receive marketing emails from
- `/api/cron/trial-emails` when due; that flow is additive (this welcome is not skipped).
-*/
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- const { userId } = JSON.parse(rawBody);
-
- const user = await prisma.user.findUnique({
- where: {
- id: userId,
- },
- select: {
- name: true,
- email: true,
- partners: true,
- projects: {
- select: {
- project: {
- select: {
- slug: true,
- name: true,
- logo: true,
- plan: true,
- trialEndsAt: true,
- defaultProgramId: true,
- },
- },
- },
- orderBy: {
- createdAt: "asc",
- },
- take: 1,
- },
- },
- });
-
- if (!user) {
- return new Response("User not found. Skipping...", { status: 200 });
- }
-
- // this shouldn't happen but just in case
- if (!user.email) {
- return new Response("User email not found. Skipping...", { status: 200 });
- }
-
- const isPartner = user.partners.length > 0;
-
- const unsubscribeUrl = `${isPartner ? PARTNERS_DOMAIN : APP_DOMAIN}/unsubscribe/${generateUnsubscribeToken(user.email)}`;
-
- if (isPartner) {
- await sendEmail({
- to: user.email,
- replyTo: "[email protected]",
- subject: "Welcome to Dub Partners!",
- react: WelcomeEmailPartner({
- email: user.email,
- name: user.name,
- unsubscribeUrl,
- }),
- variant: "marketing",
- });
-
- // only send WelcomeEmail if the user has a workspace that:
- // - is not in a trial
- // - hasn't created a program yet
- } else if (
- user.projects.length > 0 &&
- user.projects[0].project.trialEndsAt === null &&
- user.projects[0].project.defaultProgramId === null
- ) {
- await sendEmail({
- to: user.email,
- replyTo: "[email protected]",
- subject: "Welcome to Dub!",
- react: WelcomeEmail({
- email: user.email,
- workspace: user.projects[0].project,
- unsubscribeUrl,
- }),
- variant: "marketing",
- });
- }
-
- return new Response("Welcome email sent and user subscribed.", {
- status: 200,
- });
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
+// POST /api/cron/welcome-user
+export const POST = withCron(async ({ rawBody }) => {
+ await welcomeUserJob.execute(JSON.parse(rawBody));
+ return logAndRespond("Welcome email sent and user subscribed.");
+});
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index bc91909d70..d4a3f7e93e 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -1,5 +1,6 @@
import { isBlacklistedEmail } from "@/lib/edge-config";
import { jackson } from "@/lib/jackson";
+import { welcomeUserJob } from "@/lib/jobs/handlers/welcome-user-job";
import { prisma } from "@/lib/prisma";
import { isStored, storage } from "@/lib/storage";
import { UserProps } from "@/lib/types";
@@ -7,7 +8,6 @@ import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendEmail } from "@dub/email";
import LoginLink from "@dub/email/templates/login-link";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
@@ -21,7 +21,6 @@ import GoogleProvider from "next-auth/providers/google";
import { createId } from "../api/create-id";
import { isProduction } from "../api/environment";
import { isSamlEnforcedForEmailDomain } from "../api/workspaces/is-saml-enforced-for-email-domain";
-import { qstash } from "../cron";
import { completeProgramApplications } from "../partners/complete-program-applications";
import {
consumeAdminImpersonation,
@@ -610,11 +609,15 @@ export const authOptions: NextAuthOptions = {
// track lead if dub_id cookie is present
trackDubLead(user),
// trigger welcome workflow 45 minutes after the user signed up
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/welcome-user`,
- delay: 45 * 60,
- body: { userId: user.id },
- }),
+ welcomeUserJob.dispatch(
+ {
+ userId: user.id,
+ },
+ {
+ delay: 45 * 60,
+ label: user.id,
+ },
+ ),
]),
);
}
diff --git a/apps/web/lib/jobs/handlers/welcome-user-job.ts b/apps/web/lib/jobs/handlers/welcome-user-job.ts
new file mode 100644
index 0000000000..b6b9c72973
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/welcome-user-job.ts
@@ -0,0 +1,101 @@
+import { generateUnsubscribeToken } from "@/lib/email/unsubscribe-token";
+import { prisma } from "@/lib/prisma";
+import { sendEmail } from "@dub/email";
+import WelcomeEmail from "@dub/email/templates/welcome-email";
+import WelcomeEmailPartner from "@dub/email/templates/welcome-email-partner";
+import { APP_DOMAIN, PARTNERS_DOMAIN } from "@dub/utils";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const inputSchema = z.object({
+ userId: z.string(),
+});
+
+// This job is used to send a welcome email to new users + subscribe them to the corresponding Resend audience
+// It is dispatched 45 minutes after a user is created.
+
+// Trial sequence: users who later start a paid-plan trial also receive marketing emails from
+// `/api/cron/trial-emails` when due; that flow is additive (this welcome is not skipped).
+export const welcomeUserJob = defineJob({
+ name: "welcome-user-job",
+ schema: inputSchema,
+ async handle(input) {
+ const { userId } = input;
+
+ const user = await prisma.user.findUnique({
+ where: {
+ id: userId,
+ },
+ select: {
+ name: true,
+ email: true,
+ partners: true,
+ projects: {
+ select: {
+ project: {
+ select: {
+ slug: true,
+ name: true,
+ logo: true,
+ plan: true,
+ trialEndsAt: true,
+ defaultProgramId: true,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ take: 1,
+ },
+ },
+ });
+
+ if (!user) {
+ console.error(`User ${userId} not found.`);
+ return;
+ }
+
+ if (!user.email) {
+ console.error(`User ${userId} email not found.`);
+ return;
+ }
+
+ const isPartner = user.partners.length > 0;
+ const unsubscribeUrl = `${isPartner ? PARTNERS_DOMAIN : APP_DOMAIN}/unsubscribe/${generateUnsubscribeToken(user.email)}`;
+
+ if (isPartner) {
+ await sendEmail({
+ variant: "marketing",
+ to: user.email,
+ replyTo: "[email protected]",
+ subject: "Welcome to Dub Partners!",
+ react: WelcomeEmailPartner({
+ email: user.email,
+ name: user.name,
+ unsubscribeUrl,
+ }),
+ });
+
+ // only send WelcomeEmail if the user has a workspace that:
+ // - is not in a trial
+ // - hasn't created a program yet
+ } else if (
+ user.projects.length > 0 &&
+ user.projects[0].project.trialEndsAt === null &&
+ user.projects[0].project.defaultProgramId === null
+ ) {
+ await sendEmail({
+ variant: "marketing",
+ to: user.email,
+ replyTo: "[email protected]",
+ subject: "Welcome to Dub!",
+ react: WelcomeEmail({
+ email: user.email,
+ workspace: user.projects[0].project,
+ unsubscribeUrl,
+ }),
+ });
+ }
+ },
+});
diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.ts
index 078257b5c9..b1912a01c3 100644
--- a/apps/web/lib/jobs/registry.ts
+++ b/apps/web/lib/jobs/registry.ts
@@ -34,6 +34,9 @@ const jobLoaders = {
import("./handlers/partner-search-sync-job").then(
(m) => m.partnerSearchSyncJob,
),
+
+ "welcome-user-job": () =>
+ import("./handlers/welcome-user-job").then((m) => m.welcomeUserJob),
} as const satisfies Record<string, () => Promise<JobDefinition>>;
const jobCache = new Map<string, JobDefinition>();