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.

refactor resend webhooks

Kiran K45233856e452
diff --git a/apps/web/app/api/resend/webhook/contact-updated.ts b/apps/web/app/api/resend/webhook/contact-updated.ts
new file mode 100644
index 0000000000..f5b4dd4b17
--- /dev/null
+++ b/apps/web/app/api/resend/webhook/contact-updated.ts
@@ -0,0 +1,26 @@
+import { prisma } from "@dub/prisma";
+
+export async function contactUpdated({
+ email,
+ unsubscribed,
+}: {
+ email: string;
+ unsubscribed: boolean;
+}) {
+ if (!email) {
+ return;
+ }
+
+ console.log(
+ `${email} ${unsubscribed ? "unsubscribed from" : "subscribed to"} mailing list. Updating user...`,
+ );
+
+ await prisma.user.update({
+ where: {
+ email,
+ },
+ data: {
+ subscribed: !unsubscribed,
+ },
+ });
+}
diff --git a/apps/web/app/api/resend/webhook/email-opened.ts b/apps/web/app/api/resend/webhook/email-opened.ts
new file mode 100644
index 0000000000..9f2a8138c9
--- /dev/null
+++ b/apps/web/app/api/resend/webhook/email-opened.ts
@@ -0,0 +1,44 @@
+import { prisma } from "@dub/prisma";
+
+export async function emailOpened({
+ tags,
+ email_id: emailId,
+}: {
+ tags?: Record<string, string>;
+ email_id: string;
+}) {
+ // Ignore if not a message notification
+ if (!tags || tags.type !== "message-notification") {
+ return;
+ }
+
+ console.log(
+ `Updating notification email read statuses for email ${emailId}...`,
+ );
+
+ await prisma.$transaction([
+ prisma.notificationEmail.updateMany({
+ where: {
+ emailId,
+ openedAt: null,
+ },
+ data: {
+ openedAt: new Date(),
+ },
+ }),
+
+ prisma.message.updateMany({
+ where: {
+ readInEmail: null,
+ emails: {
+ some: {
+ emailId,
+ },
+ },
+ },
+ data: {
+ readInEmail: new Date(),
+ },
+ }),
+ ]);
+}
diff --git a/apps/web/app/api/resend/webhook/route.ts b/apps/web/app/api/resend/webhook/route.ts
index 138053c536..7d28e22a27 100644
--- a/apps/web/app/api/resend/webhook/route.ts
+++ b/apps/web/app/api/resend/webhook/route.ts
@@ -1,106 +1,45 @@
-import { prisma } from "@dub/prisma";
import crypto from "crypto";
import { NextResponse } from "next/server";
+import { contactUpdated } from "./contact-updated";
+import { emailOpened } from "./email-opened";
+// POST /api/resend/webhook – listen to Resend webhooks
export const POST = async (req: Request) => {
const rawBody = await req.text();
- const svix_id = req.headers.get("svix-id");
- const svix_timestamp = req.headers.get("svix-timestamp");
- const svix_signature = req.headers.get("svix-signature")?.split("v1,")[1];
+ const svixId = req.headers.get("svix-id");
+ const svixTimestamp = req.headers.get("svix-timestamp");
+ const svixSignature = req.headers.get("svix-signature")?.split("v1,")[1];
const secret = process.env.RESEND_WEBHOOK_SECRET;
- if (!secret || !svix_id || !svix_timestamp || !svix_signature) {
- return NextResponse.json({ message: "Invalid request" }, { status: 400 });
+ if (!secret || !svixId || !svixTimestamp || !svixSignature) {
+ return NextResponse.json({ message: "Invalid request." }, { status: 400 });
}
- const signedContent = `${svix_id}.${svix_timestamp}.${rawBody}`;
+ const signedContent = `${svixId}.${svixTimestamp}.${rawBody}`;
// Need to base64 decode the secret
const secretBytes = Buffer.from(secret.split("_")[1], "base64");
- const signature = crypto
- .createHmac("sha256", secretBytes)
+ const computedSignature = crypto
+ .createHmac("sha256", new Uint8Array(secretBytes))
.update(signedContent)
.digest("base64");
- if (signature !== svix_signature) {
- return NextResponse.json({ message: "Invalid signature" }, { status: 400 });
+ if (computedSignature !== svixSignature) {
+ return NextResponse.json({ message: "Invalid signature." }, { status: 400 });
}
const { type, data } = JSON.parse(rawBody) || {};
switch (type) {
case "contact.updated":
- await handleContactUpdated(data);
+ await contactUpdated(data);
break;
case "email.opened":
- await handleEmailOpened(data);
+ await emailOpened(data);
break;
}
- return NextResponse.json({ message: "Webhook received" });
+ return NextResponse.json({ message: "Webhook processed." });
};
-
-async function handleContactUpdated({
- email,
- unsubscribed,
-}: {
- email: string;
- unsubscribed: boolean;
-}) {
- console.log(
- `${email} ${unsubscribed ? "unsubscribed from" : "subscribed to"} mailing list. Updating user...`,
- );
-
- if (email) {
- await prisma.user.update({
- where: {
- email,
- },
- data: {
- subscribed: !unsubscribed,
- },
- });
- }
-}
-
-async function handleEmailOpened({
- tags,
- email_id: emailId,
-}: {
- tags?: Record<string, string>;
- email_id: string;
-}) {
- // Ignore if not a message notification
- if (!tags || tags.type !== "message-notification") return;
-
- console.log(
- `Updating notification email read statuses for email ${emailId}...`,
- );
-
- await Promise.all([
- prisma.notificationEmail.updateMany({
- where: {
- emailId,
- openedAt: null,
- },
- data: {
- openedAt: new Date(),
- },
- }),
- prisma.message.updateMany({
- where: {
- readInEmail: null,
- emails: {
- some: {
- emailId,
- },
- },
- },
- data: {
- readInEmail: new Date(),
- },
- }),
- ]);
-}