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.

send email notifications on email domain status changes (#3300)

Kiran Kacec214917f7
diff --git a/apps/web/app/(ee)/api/cron/email-domains/update/route.ts b/apps/web/app/(ee)/api/cron/email-domains/update/route.ts
index 2fb8577904..b3b4c88d3d 100644
--- a/apps/web/app/(ee)/api/cron/email-domains/update/route.ts
+++ b/apps/web/app/(ee)/api/cron/email-domains/update/route.ts
@@ -1,8 +1,6 @@
-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { withCron } from "@/lib/cron/with-cron";
import { resend } from "@dub/email/resend/client";
import { prisma } from "@dub/prisma";
-import { log } from "@dub/utils";
import { z } from "zod";
import { logAndRespond } from "../../utils";
@@ -14,60 +12,44 @@ export const dynamic = "force-dynamic";
// POST /api/cron/email-domains/update
// Update the Resend domain to enable click tracking
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
+export const POST = withCron(async ({ rawBody }) => {
+ const { domainId } = schema.parse(JSON.parse(rawBody));
- await verifyQstashSignature({ req, rawBody });
-
- const { domainId } = schema.parse(JSON.parse(rawBody));
-
- if (!resend) {
- return logAndRespond("Resend is not configured. Skipping update...");
- }
-
- const domainRecord = await prisma.emailDomain.findUnique({
- where: {
- id: domainId,
- },
- select: {
- slug: true,
- resendDomainId: true,
- },
- });
-
- if (!domainRecord) {
- return logAndRespond(`Domain ${domainId} not found. Skipping update...`);
- }
-
- if (!domainRecord.resendDomainId) {
- return logAndRespond(
- `Resend domain ID is not found for domain ${domainRecord.slug}. Skipping update...`,
- );
- }
+ if (!resend) {
+ return logAndRespond("Resend is not configured. Skipping update...");
+ }
- const { error } = await resend.domains.update({
- id: domainRecord.resendDomainId,
- openTracking: true,
- clickTracking: false,
- tls: "enforced",
- });
+ const domainRecord = await prisma.emailDomain.findUnique({
+ where: {
+ id: domainId,
+ },
+ select: {
+ slug: true,
+ resendDomainId: true,
+ },
+ });
+
+ if (!domainRecord) {
+ return logAndRespond(`Domain ${domainId} not found. Skipping update...`);
+ }
- // This will be retried by QStash if it fails.
- if (error) {
- throw new DubApiError({
- code: "bad_request",
- message: error.message,
- });
- }
+ if (!domainRecord.resendDomainId) {
+ return logAndRespond(
+ `Resend domain ID is not found for domain ${domainRecord.slug}. Skipping update...`,
+ );
+ }
- return logAndRespond(`Domain ${domainRecord.slug} updated successfully.`);
- } catch (error) {
- await log({
- message: `Resend email domain update failed with error ${JSON.stringify(error)}`,
- type: "errors",
- });
+ const { error } = await resend.domains.update({
+ id: domainRecord.resendDomainId,
+ openTracking: true,
+ clickTracking: false,
+ tls: "enforced",
+ });
- return handleAndReturnErrorResponse(error);
+ // This will be retried by QStash if it fails.
+ if (error) {
+ throw new Error(error.message);
}
-}
+
+ return logAndRespond(`Domain ${domainRecord.slug} updated successfully.`);
+});
diff --git a/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts b/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts
index f6cd99b409..6dc11559d8 100644
--- a/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts
+++ b/apps/web/app/(ee)/api/cron/email-domains/verify/route.ts
@@ -1,64 +1,52 @@
-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { getWorkspaceUsers } from "@/lib/api/get-workspace-users";
+import { withCron } from "@/lib/cron/with-cron";
+import { sendBatchEmail } from "@dub/email";
import { resend } from "@dub/email/resend/client";
+import EmailDomainStatusChanged from "@dub/email/templates/email-domain-status-changed";
import { prisma } from "@dub/prisma";
import { EmailDomain } from "@dub/prisma/client";
-import { log } from "@dub/utils";
-import { NextResponse } from "next/server";
import { logAndRespond } from "../../utils";
export const dynamic = "force-dynamic";
// GET /api/cron/email-domains/verify
// Runs every hour (0 * * * *)
-export async function GET(req: Request) {
- try {
- await verifyVercelSignature(req);
-
- if (!resend) {
- throw new DubApiError({
- code: "internal_server_error",
- message: "Resend is not configured.",
- });
- }
+export const GET = withCron(async () => {
+ if (!resend) {
+ return logAndRespond("Resend is not configured. Skipping verification...");
+ }
- const domains = await prisma.emailDomain.findMany({
- where: {
- resendDomainId: {
- not: null,
- },
- },
- orderBy: {
- lastChecked: "asc",
+ const domains = await prisma.emailDomain.findMany({
+ where: {
+ resendDomainId: {
+ not: null,
},
- take: 10,
- });
-
- if (domains.length === 0) {
- return logAndRespond(
- "No email domains to check the verification status.",
- );
- }
-
- const results = await Promise.allSettled(
- domains.map((domain) => verifyEmailDomain(domain)),
- );
+ },
+ orderBy: {
+ lastChecked: "asc",
+ },
+ take: 10,
+ });
- return NextResponse.json(results);
- } catch (error) {
- await log({
- message:
- "Email domains verification cron failed. Error: " + error.message,
- type: "errors",
- });
+ if (domains.length === 0) {
+ return logAndRespond("No email domains to check the verification status.");
+ }
- return handleAndReturnErrorResponse(error);
+ for (const domain of domains) {
+ try {
+ await verifyEmailDomain(domain);
+ } catch (error) {
+ console.error(`Failed to verify domain ${domain.slug}:`, error);
+ }
}
-}
+ return logAndRespond("Email domains verification status checked.");
+});
+
+// Checks the verification status of an email domain
async function verifyEmailDomain(domain: EmailDomain) {
if (!domain.resendDomainId) {
- return null;
+ return;
}
const { data: resendDomain, error } = await resend!.domains.get(
@@ -66,10 +54,10 @@ async function verifyEmailDomain(domain: EmailDomain) {
);
if (error) {
- return null;
+ return;
}
- await prisma.emailDomain.update({
+ const updatedDomain = await prisma.emailDomain.update({
where: {
id: domain.id,
},
@@ -79,19 +67,63 @@ async function verifyEmailDomain(domain: EmailDomain) {
},
});
- const statusChanged = resendDomain.status !== domain.status;
+ const statusChanged = updatedDomain.status !== domain.status;
+
+ // Do nothing if the status has not changed
+ if (!statusChanged) {
+ console.log(
+ `Email domain ${domain.slug} status has not changed. Skipping email notification...`,
+ );
+
+ return;
+ }
+
+ console.log(
+ `Email domain ${domain.slug} status changed from ${domain.status} to ${updatedDomain.status}`,
+ );
+
+ const { users, ...workspace } = await getWorkspaceUsers({
+ role: "owner",
+ workspaceId: domain.workspaceId,
+ notificationPreference: "domainConfigurationUpdates",
+ });
- if (statusChanged) {
- await log({
- message: `Email domain *${domain.slug}* status changed to *${resendDomain.status}*`,
- type: "cron",
- });
+ if (users.length === 0) {
+ console.log(
+ `No workspace owners found for domain ${domain.slug}. Skipping email notification...`,
+ );
+ return;
}
- // TODO:
- // Send email notification
+ const subject =
+ updatedDomain.status === "verified"
+ ? "Your email domain has been verified"
+ : updatedDomain.status === "failed"
+ ? "Your email domain verification has failed"
+ : "Your email domain status has changed";
+
+ const resendResponse = await sendBatchEmail(
+ users.map((user) => ({
+ variant: "notifications",
+ subject,
+ to: user.email,
+ react: EmailDomainStatusChanged({
+ domain: domain.slug,
+ oldStatus: domain.status,
+ newStatus: updatedDomain.status,
+ email: user.email,
+ workspace: {
+ slug: workspace.slug,
+ name: workspace.name,
+ },
+ }),
+ })),
+ );
- return {
- domain,
- };
+ if (resendResponse.error) {
+ console.error(
+ `Failed to send email notification for domain ${domain.slug}:`,
+ resendResponse.error,
+ );
+ }
}
diff --git a/packages/email/src/templates/email-domain-status-changed.tsx b/packages/email/src/templates/email-domain-status-changed.tsx
new file mode 100644
index 0000000000..c88a9332f4
--- /dev/null
+++ b/packages/email/src/templates/email-domain-status-changed.tsx
@@ -0,0 +1,137 @@
+import { DUB_WORDMARK } from "@dub/utils";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { Footer } from "../components/footer";
+
+export type EmailDomainStatus =
+ | "pending"
+ | "verified"
+ | "failed"
+ | "temporary_failure"
+ | "not_started";
+
+export default function EmailDomainStatusChanged({
+ email = "[email protected]",
+ domain = "example.com",
+ workspace = { slug: "acme", name: "Acme" },
+ oldStatus = "pending",
+ newStatus = "verified",
+}: {
+ email: string;
+ domain: string;
+ workspace: { slug: string; name: string };
+ oldStatus: EmailDomainStatus;
+ newStatus: EmailDomainStatus;
+}) {
+ const isVerified = newStatus === "verified";
+ const isFailed = newStatus === "failed" || newStatus === "temporary_failure";
+ const isPending = newStatus === "pending" || newStatus === "not_started";
+
+ const heading = isVerified
+ ? "Your email domain has been successfully verified"
+ : isFailed
+ ? "Your email domain verification has failed"
+ : "Your email domain status has changed";
+
+ return (
+ <Html>
+ <Head />
+ <Preview>{heading}</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img src={DUB_WORDMARK} height="32" alt="Dub" />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-lg font-medium text-black">
+ {heading}
+ </Heading>
+
+ {isVerified ? (
+ <Text className="text-sm leading-6 text-black">
+ Your email domain{" "}
+ <code className="text-purple-600">{domain}</code> for your Dub
+ workspace{" "}
+ <Link
+ href={`https://app.dub.co/${workspace.slug}`}
+ className="font-medium text-blue-600 no-underline"
+ >
+ {workspace.name}↗
+ </Link>{" "}
+ has been successfully verified. You can now send emails from
+ this domain.
+ </Text>
+ ) : isFailed ? (
+ <>
+ <Text className="text-sm leading-6 text-black">
+ Your email domain{" "}
+ <code className="text-purple-600">{domain}</code> for your Dub
+ workspace{" "}
+ <Link
+ href={`https://app.dub.co/${workspace.slug}`}
+ className="font-medium text-blue-600 no-underline"
+ >
+ {workspace.name}↗
+ </Link>{" "}
+ verification has failed. Please check your DNS records and try
+ again.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ Please ensure all required DNS records are correctly
+ configured in your domain settings. You can find the required
+ records in your email domain settings.
+ </Text>
+ </>
+ ) : (
+ <Text className="text-sm leading-6 text-black">
+ Your email domain{" "}
+ <code className="text-purple-600">{domain}</code> for your Dub
+ workspace{" "}
+ <Link
+ href={`https://app.dub.co/${workspace.slug}`}
+ className="font-medium text-blue-600 no-underline"
+ >
+ {workspace.name}↗
+ </Link>{" "}
+ status has changed from <strong>{oldStatus}</strong> to{" "}
+ <strong>{newStatus}</strong>.
+ </Text>
+ )}
+
+ {isPending && (
+ <Text className="text-sm leading-6 text-black">
+ We're still verifying your domain. This process may take a few
+ minutes. You'll receive another notification once verification
+ is complete.
+ </Text>
+ )}
+
+ <Section className="my-8">
+ <Link
+ className="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ href={`https://app.dub.co/${workspace.slug}/links/domains/email`}
+ >
+ View email domain
+ </Link>
+ </Section>
+ <Footer
+ email={email}
+ notificationSettingsUrl={`https://app.dub.co/${workspace.slug}/settings/notifications`}
+ />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/packages/email/src/templates/invalid-domain.tsx b/packages/email/src/templates/invalid-domain.tsx
index 8889d6fbdc..a0d47f97ee 100644
--- a/packages/email/src/templates/invalid-domain.tsx
+++ b/packages/email/src/templates/invalid-domain.tsx
@@ -24,7 +24,7 @@ export default function InvalidDomain({
domain: string;
workspaceSlug: string;
invalidDays: number;
-}): JSX.Element {
+}) {
return (
<Html>
<Head />