The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
use scheduledAt API + remove flodesk
Steven Tey20c17fd0a1d6
diff --git a/apps/web/app/api/admin/ban/route.ts b/apps/web/app/api/admin/ban/route.tsindex ff8e6cfc4a..7f422d9bdb 100644--- a/apps/web/app/api/admin/ban/route.ts+++ b/apps/web/app/api/admin/ban/route.ts@@ -1,8 +1,8 @@import { deleteWorkspaceAdmin } from "@/lib/api/workspaces";import { withAdmin } from "@/lib/auth";import { updateConfig } from "@/lib/edge-config";-import { unsubscribe } from "@/lib/flodesk";import { prisma } from "@/lib/prisma";+import { unsubscribe } from "@/lib/resend";import { isStored, storage } from "@/lib/storage";import { R2_URL } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -62,7 +62,7 @@ export const POST = withAdmin(async ({ req }) => {user.image &&isStored(user.image) &&storage.delete(user.image.replace(`${R2_URL}/`, "")),- unsubscribe(email),+ unsubscribe({ email }),updateConfig({key: "emails",value: email,diff --git a/apps/web/app/api/callback/flodesk/route.ts b/apps/web/app/api/callback/flodesk/route.tsdeleted file mode 100644index 62e9bfe44d..0000000000--- a/apps/web/app/api/callback/flodesk/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { prisma } from "@/lib/prisma";-import { log } from "@dub/utils";-import { NextRequest, NextResponse } from "next/server";--export async function POST(req: NextRequest) {- const { searchParams } = new URL(req.url);-- const token = searchParams.get("token") as string;-- if (token !== process.env.FLODESK_WEBHOOK_SECRET) {- return new Response("Unauthorized", { status: 401 });- }-- const payload = await req.json();-- // parse the payload- const { subscriber } = payload;-- if (!subscriber.email) {- return new Response("Invalid payload", { status: 400 });- }-- await Promise.all([- prisma.user.update({- where: {- email: subscriber.email,- },- data: {- subscribed: false,- },- }),- log({- message: `*${subscriber.email}* unsubscribed from the newsletter (*Flodesk*).`,- type: "subscribers",- }),- ]);-- return NextResponse.json({ success: true });-}diff --git a/apps/web/app/api/cron/emails/cancellation-feedback/route.ts b/apps/web/app/api/cron/emails/cancellation-feedback/route.tsdeleted file mode 100644index f03ada7f4f..0000000000--- a/apps/web/app/api/cron/emails/cancellation-feedback/route.ts+++ /dev/null@@ -1,58 +0,0 @@-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";-import { sendEmail } from "emails";--export const dynamic = "force-dynamic";--const cancellationReasonMap = {- customer_service: "you had a bad experience with our customer service",- low_quality: "the product didn't meet your expectations",- missing_features: "you were expecting more features",- switched_service: "you switched to a different service",- too_complex: "the product was too complex",- too_expensive: "the product was too expensive",- unused: "you didn't use the product",-};--export async function POST(req: Request) {- try {- const body = await req.json();- await verifyQstashSignature(req, body);-- const { owners, reason } = body as {- owners: {- name: string | null;- email: string | null;- }[];- reason?:- | "customer_service"- | "low_quality"- | "missing_features"- | "other"- | "switched_service"- | "too_complex"- | "too_expensive"- | "unused";- };-- const reasonText = reason ? cancellationReasonMap[reason] : "";-- await Promise.all(- owners.map(- (owner) =>- owner.email &&- sendEmail({- email: owner.email,- from: "Steven Tey <[email protected]>",- replyToFromEmail: true,- subject: "Feedback for Dub.co?",- text: `Hey ${owner.name ? owner.name.split(" ")[0] : "there"}!\n\nSaw you canceled your Dub subscription${reasonText ? ` and mentioned that ${reasonText}` : ""} – do you mind sharing if there's anything we could've done better on our side?\n\nWe're always looking to improve our product offering so any feedback would be greatly appreciated!\n\nThank you so much in advance!\n\nBest,\nSteven Tey\nFounder, Dub.co`,- }),- ),- );-- return new Response("Feedback email sent.", { status: 200 });- } catch (error) {- return handleAndReturnErrorResponse(error);- }-}diff --git a/apps/web/app/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/api/stripe/webhook/customer-subscription-deleted.tsindex e38f3fee23..36151ae249 100644--- a/apps/web/app/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/api/stripe/webhook/customer-subscription-deleted.ts@@ -1,10 +1,10 @@-import { qstash } from "@/lib/cron";import { prisma } from "@/lib/prisma";import { recordLink } from "@/lib/tinybird";import { redis } from "@/lib/upstash";-import { APP_DOMAIN_WITH_NGROK, FREE_PLAN, log } from "@dub/utils";+import { FREE_PLAN, log } from "@dub/utils";import { NextResponse } from "next/server";import Stripe from "stripe";+import { sendCancellationFeedback } from "./utils";export async function customerSubscriptionDeleted(event: Stripe.Event) {const subscriptionDeleted = event.data.object as Stripe.Subscription;@@ -132,13 +132,8 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {type: "cron",mention: true,}),- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/emails/cancellation-feedback`,- // artificially delay anywhere between 3-5 hours to make it feel more like a human- delay: Math.floor(Math.random() * 60 * 60 * 3) + 3 * 60 * 60,- body: {- owners: workspaceUsers,- },+ sendCancellationFeedback({+ owners: workspaceUsers,}),]);}diff --git a/apps/web/app/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/api/stripe/webhook/customer-subscription-updated.tsindex e604e27ec3..00bd060457 100644--- a/apps/web/app/api/stripe/webhook/customer-subscription-updated.ts+++ b/apps/web/app/api/stripe/webhook/customer-subscription-updated.ts@@ -1,8 +1,8 @@-import { qstash } from "@/lib/cron";import { prisma } from "@/lib/prisma";-import { APP_DOMAIN_WITH_NGROK, getPlanFromPriceId, log } from "@dub/utils";+import { getPlanFromPriceId, log } from "@dub/utils";import { NextResponse } from "next/server";import Stripe from "stripe";+import { sendCancellationFeedback } from "./utils";export async function customerSubscriptionUpdated(event: Stripe.Event) {const subscriptionUpdated = event.data.object as Stripe.Subscription;@@ -94,14 +94,9 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {const owners = workspace.users.map(({ user }) => user);const cancelReason = subscriptionUpdated.cancellation_details?.feedback;- await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/emails/cancellation-feedback`,- // artificially delay anywhere between 3-5 hours to make it feel more like a human- delay: Math.floor(Math.random() * 60 * 60 * 3) + 3 * 60 * 60,- body: {- owners,- reason: cancelReason,- },+ await sendCancellationFeedback({+ owners,+ reason: cancelReason,});}}diff --git a/apps/web/app/api/stripe/webhook/utils.ts b/apps/web/app/api/stripe/webhook/utils.tsnew file mode 100644index 0000000000..029d7292e5--- /dev/null+++ b/apps/web/app/api/stripe/webhook/utils.ts@@ -0,0 +1,45 @@+import { sendEmail } from "emails";+import Stripe from "stripe";++const cancellationReasonMap = {+ customer_service: "you had a bad experience with our customer service",+ low_quality: "the product didn't meet your expectations",+ missing_features: "you were expecting more features",+ switched_service: "you switched to a different service",+ too_complex: "the product was too complex",+ too_expensive: "the product was too expensive",+ unused: "you didn't use the product",+};++export async function sendCancellationFeedback({+ owners,+ reason,+}: {+ owners: {+ name: string | null;+ email: string | null;+ }[];+ reason?: Stripe.Subscription.CancellationDetails.Feedback | null;+}) {+ const reasonText = reason ? cancellationReasonMap[reason] : "";++ return await Promise.all(+ owners.map(+ (owner) =>+ owner.email &&+ sendEmail({+ email: owner.email,+ from: "Steven Tey <[email protected]>",+ replyToFromEmail: true,+ subject: "Feedback for Dub.co?",+ text: `Hey ${owner.name ? owner.name.split(" ")[0] : "there"}!\n\nSaw you canceled your Dub subscription${reasonText ? ` and mentioned that ${reasonText}` : ""} – do you mind sharing if there's anything we could've done better on our side?\n\nWe're always looking to improve our product offering so any feedback would be greatly appreciated!\n\nThank you so much in advance!\n\nBest,\nSteven Tey\nFounder, Dub.co`,+ // artificially delay anywhere between 2-4 hours to make it feel more like a human+ scheduledAt: new Date(+ Date.now() ++ 1000 * 60 * 60 * 2 ++ Math.floor(Math.random() * 1000 * 60 * 60 * 2),+ ).toISOString(),+ }),+ ),+ );+}diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.tsindex 0412391902..8fc5215d67 100644--- a/apps/web/app/api/user/route.ts+++ b/apps/web/app/api/user/route.ts@@ -1,7 +1,7 @@import { DubApiError } from "@/lib/api/errors";import { withSession } from "@/lib/auth";-import { unsubscribe } from "@/lib/flodesk";import { prisma } from "@/lib/prisma";+import { unsubscribe } from "@/lib/resend";import { storage } from "@/lib/storage";import { redis } from "@/lib/upstash";import { R2_URL, nanoid, trim } from "@dub/utils";@@ -165,7 +165,7 @@ export const DELETE = withSession(async ({ session }) => {user.image &&user.image.startsWith(`${R2_URL}/avatars/${session.user.id}`) &&storage.delete(user.image.replace(`${R2_URL}/`, "")),- unsubscribe(session.user.email),+ unsubscribe({ email: session.user.email }),]);return NextResponse.json(response);}diff --git a/apps/web/app/api/user/subscribe/route.ts b/apps/web/app/api/user/subscribe/route.tsindex 89beb4cb13..5626a0503a 100644--- a/apps/web/app/api/user/subscribe/route.ts+++ b/apps/web/app/api/user/subscribe/route.ts@@ -1,7 +1,6 @@import { withSession } from "@/lib/auth";-import { subscribe, unsubscribe } from "@/lib/flodesk";import { prisma } from "@/lib/prisma";-import { log } from "@dub/utils";+import { subscribe, unsubscribe } from "@/lib/resend";import { NextResponse } from "next/server";// GET /api/user/subscribe – get a specific user@@ -43,10 +42,6 @@ export const POST = withSession(async ({ session }) => {},}),subscribe({ email: session.user.email, name: session.user.name }),- log({- message: `*${session.user.email}* resubscribed to the newsletter. Manual addition required.`,- type: "alerts",- }),]);return NextResponse.json(user);@@ -69,7 +64,7 @@ export const DELETE = withSession(async ({ session }) => {subscribed: true,},}),- unsubscribe(session.user.email),+ unsubscribe({ email: session.user.email }),]);return NextResponse.json(user);diff --git a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsxdeleted file mode 100644index 87d2bc3f60..0000000000--- a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx+++ /dev/null@@ -1,23 +0,0 @@-"use client";--import UpdateSubscription from "@/ui/account/update-subscription";-import { Logo } from "@dub/ui";-import { APP_NAME, HOME_DOMAIN } from "@dub/utils";-import Link from "next/link";--export default function UnsubscribeForm() {- return (- <div className="flex h-screen flex-col items-center justify-center space-y-6 text-center">- <Link href={HOME_DOMAIN} target="_blank">- <Logo className="h-12 w-12" />- </Link>- <h1 className="font-display text-4xl font-bold">Email Preferences</h1>- <p className="text-lg text-gray-600">- Configure your email preferences for {APP_NAME}.- </p>- <div className="rounded-lg border border-gray-200 bg-white px-6 py-3">- <UpdateSubscription />- </div>- </div>- );-}diff --git a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/page.tsx b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/page.tsxdeleted file mode 100644index 55c051d488..0000000000--- a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/page.tsx+++ /dev/null@@ -1,10 +0,0 @@-import { Suspense } from "react";-import UnsubscribeForm from "./form";--export default function UnsubscribePage() {- return (- <Suspense>- <UnsubscribeForm />- </Suspense>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsxindex edcde616ef..f444f61eca 100644--- a/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx@@ -2,6 +2,7 @@import DeleteAccountSection from "@/ui/account/delete-account";import UpdateDefaultWorkspace from "@/ui/account/update-default-workspace";+import UpdateSubscription from "@/ui/account/update-subscription";import UploadAvatar from "@/ui/account/upload-avatar";import UserId from "@/ui/account/user-id";import { Form } from "@dub/ui";@@ -52,8 +53,7 @@ export default function SettingsPageClient() {defaultValue: session?.user?.email || undefined,placeholder: "[email protected]",}}- helpText="Must be a valid email address."- // helpText={<UpdateSubscription />} TODO: enable this once we can subscribe folks programmatically+ helpText={<UpdateSubscription />}handleSubmit={(data) =>fetch("/api/user", {method: "PATCH",diff --git a/apps/web/emails/components/footer.tsx b/apps/web/emails/components/footer.tsxindex 3081283b3e..5e97b42170 100644--- a/apps/web/emails/components/footer.tsx+++ b/apps/web/emails/components/footer.tsx@@ -10,7 +10,22 @@ export default function Footer({notificationSettingsUrl?: string;}) {if (marketing) {- return null;+ return (+ <Tailwind>+ <Hr className="mx-0 my-6 w-full border border-gray-200" />+ <Text className="text-[12px] leading-6 text-gray-500">+ We send out product update emails once a month – no spam, no nonsense.+ <br />+ Don't want to get these emails?{" "}+ <Link+ className="text-gray-700 underline"+ href="https://app.dub.co/account/settings"+ >+ Unsubscribe here.+ </Link>+ </Text>+ </Tailwind>+ );}return (diff --git a/apps/web/emails/index.ts b/apps/web/emails/index.tsindex 0bba22641a..adacaa3413 100644--- a/apps/web/emails/index.ts+++ b/apps/web/emails/index.ts@@ -1,8 +1,5 @@-import { JSXElementConstructor, ReactElement } from "react";--import { Resend } from "resend";--export const client = new Resend(process.env.RESEND_API_KEY);+import { resend } from "@/lib/resend";+import { CreateEmailOptions } from "resend";export const sendEmail = async ({email,@@ -12,18 +9,15 @@ export const sendEmail = async ({replyToFromEmail,text,react,+ scheduledAt,marketing,-}: {+}: Omit<CreateEmailOptions, "to" | "from"> & {email: string;- subject: string;from?: string;- bcc?: string;replyToFromEmail?: boolean;- text?: string;- react?: ReactElement<any, string | JSXElementConstructor<any>>;marketing?: boolean;}) => {- if (process.env.NODE_ENV === "development" && !client) {+ if (process.env.NODE_ENV === "development" && !resend) {// Set up a fake email client for developmentconsole.info(`Email to ${email} with subject ${subject} sent from ${@@ -31,30 +25,32 @@ export const sendEmail = async ({}`,);return Promise.resolve();- } else if (!client) {+ } else if (!resend) {console.error("Resend is not configured. You need to add a RESEND_API_KEY in your .env file for emails to work.",);return Promise.resolve();}- return client.emails.send({+ return resend.emails.send({+ to: email,from:from ||(marketing- ? "[email protected]"- : process.env.NEXT_PUBLIC_IS_DUB- ? "[email protected]"- : `${process.env.NEXT_PUBLIC_APP_NAME} <system@${process.env.NEXT_PUBLIC_APP_DOMAIN}>`),- to: email,+ ? "Steven from Dub.co <[email protected]>"+ : "Dub.co <[email protected]>"),bcc: bcc,...(!replyToFromEmail && {- replyTo: process.env.NEXT_PUBLIC_IS_DUB- ? "[email protected]"- : `support@${process.env.NEXT_PUBLIC_APP_DOMAIN}`,+ replyTo: "[email protected]",}),subject: subject,text: text,react: react,+ scheduledAt,+ ...(marketing && {+ headers: {+ "List-Unsubscribe": "https://app.dub.co/account/settings",+ },+ }),});};diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.tsindex cb68673121..2f35d10b85 100644--- a/apps/web/lib/auth/options.ts+++ b/apps/web/lib/auth/options.ts@@ -1,6 +1,11 @@+import { dub } from "@/lib/dub";import { isBlacklistedEmail } from "@/lib/edge-config";import jackson from "@/lib/jackson";import { prisma } from "@/lib/prisma";+import { subscribe } from "@/lib/resend";+import { isStored, storage } from "@/lib/storage";+import { UserProps } from "@/lib/types";+import { ratelimit } from "@/lib/upstash";import { PrismaAdapter } from "@next-auth/prisma-adapter";import { waitUntil } from "@vercel/functions";import { sendEmail } from "emails";@@ -14,11 +19,6 @@ import EmailProvider from "next-auth/providers/email";import GithubProvider from "next-auth/providers/github";import GoogleProvider from "next-auth/providers/google";import { cookies } from "next/headers";-import { dub } from "../dub";-import { subscribe } from "../flodesk";-import { isStored, storage } from "../storage";-import { UserProps } from "../types";-import { ratelimit } from "../upstash";import {exceededLoginAttemptsThreshold,incrementLoginAttempts,@@ -445,6 +445,8 @@ export const authOptions: NextAuthOptions = {email,name: user.name || null,}),+ // send the welcome email 5 minutes after the user signed up+ scheduledAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(),marketing: true,}),]),diff --git a/apps/web/lib/flodesk.ts b/apps/web/lib/flodesk.tsdeleted file mode 100644index ce69a6d69f..0000000000--- a/apps/web/lib/flodesk.ts+++ /dev/null@@ -1,32 +0,0 @@-export async function subscribe({- email,- name,-}: {- email: string;- name?: string | null;-}) {- return fetch("https://api.flodesk.com/v1/subscribers", {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Basic ${process.env.FLODESK_API_KEY}`,- },- body: JSON.stringify({- email,- ...(name && {- first_name: name.split(" ")[0],- last_name: name.split(" ").slice(1).join(" "),- }),- }),- }).then((res) => res.json());-}--export async function unsubscribe(email: string) {- return fetch(`https://api.flodesk.com/v1/subscribers/${email}/unsubscribe`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Basic ${process.env.FLODESK_API_KEY}`,- },- }).then((res) => res.json());-}diff --git a/apps/web/lib/resend.ts b/apps/web/lib/resend.tsnew file mode 100644index 0000000000..8f0c76a760--- /dev/null+++ b/apps/web/lib/resend.ts@@ -0,0 +1,33 @@+import { Resend } from "resend";++export const resend = new Resend(process.env.RESEND_API_KEY);++export async function subscribe({+ email,+ name,+}: {+ email: string;+ name?: string | null;+}) {+ const [firstName, ...lastName] = name ? name.split(" ") : [];++ if (!process.env.RESEND_API_KEY || !process.env.RESEND_AUDIENCE_ID) {+ console.error("Resend API key or audience ID not found");+ return;+ }++ return await resend.contacts.create({+ email,+ firstName,+ lastName: lastName.length > 0 ? lastName.join(" ") : undefined,+ unsubscribed: false,+ audienceId: process.env.RESEND_AUDIENCE_ID as string,+ });+}++export async function unsubscribe({ email }: { email: string }) {+ return await resend.contacts.remove({+ email,+ audienceId: process.env.RESEND_AUDIENCE_ID as string,+ });+}diff --git a/apps/web/scripts/send-emails.tsx b/apps/web/scripts/send-emails.tsxindex 0f0573cd04..7575c17f4a 100644--- a/apps/web/scripts/send-emails.tsx+++ b/apps/web/scripts/send-emails.tsx@@ -1,6 +1,5 @@+import { sendCancellationFeedback } from "app/api/stripe/webhook/utils";import "dotenv-flow/config";-import { sendEmail } from "emails";-import FailedPayment from "emails/failed-payment";const attemptCount = 2;const amountDue = 2400;@@ -14,24 +13,27 @@ const workspace = {};async function main() {- const res = await sendEmail({- email: user.email as string,- from: "[email protected]",- subject: `${- attemptCount == 2- ? "2nd notice: "- : attemptCount == 3- ? "3rd notice: "- : ""- }Your payment for Dub.co failed`,- react: (- <FailedPayment- attemptCount={attemptCount}- amountDue={amountDue}- user={user}- workspace={workspace}- />- ),+ // const res = await sendEmail({+ // email: user.email as string,+ // from: "[email protected]",+ // subject: `${+ // attemptCount == 2+ // ? "2nd notice: "+ // : attemptCount == 3+ // ? "3rd notice: "+ // : ""+ // }Your payment for Dub.co failed`,+ // react: (+ // <FailedPayment+ // attemptCount={attemptCount}+ // amountDue={amountDue}+ // user={user}+ // workspace={workspace}+ // />+ // ),+ // });+ const res = await sendCancellationFeedback({+ owners: [user],});console.log({ res });diff --git a/apps/web/ui/account/update-subscription.tsx b/apps/web/ui/account/update-subscription.tsxindex 1bb0091c3d..b2618ba4e2 100644--- a/apps/web/ui/account/update-subscription.tsx+++ b/apps/web/ui/account/update-subscription.tsx@@ -22,7 +22,7 @@ export default function UpdateSubscription() {};return (- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-x-2"><Switchchecked={data?.subscribed}loading={isLoading}@@ -30,7 +30,7 @@ export default function UpdateSubscription() {update(() => subscribe(checked), { subscribed: checked });}}/>- <p className="text-sm text-gray-500">Subscribed to updates</p>+ <p className="text-sm text-gray-500">Subscribed to product updates</p></div>);}diff --git a/apps/web/ui/analytics/feedback/action.ts b/apps/web/ui/analytics/feedback/action.tsindex fda3eeea85..96fc610d33 100644--- a/apps/web/ui/analytics/feedback/action.ts+++ b/apps/web/ui/analytics/feedback/action.ts@@ -1,13 +1,13 @@"use server";-import { client } from "emails";+import { resend } from "@/lib/resend";import FeedbackEmail from "emails/feedback-email";export async function submitFeedback(data: FormData) {const email = data.get("email") as string;const feedback = data.get("feedback") as string;- return await client.emails.send({+ return await resend.emails.send({from: "[email protected]",to: "[email protected]",...(email && { replyTo: email }),