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.

Add email invitation modal

Tim Wilson4dee4f4614d9
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx
index 8fb9847778..e4d56e9063 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useInviteReferralModal } from "@/ui/modals/invite-referral-modal";
import { Button } from "@dub/ui";
import { Mail } from "lucide-react";
@@ -7,17 +8,19 @@ const subject = "Create a free account on Dub!";
const body = (url: string) =>
`Use my referral link to get started with Dub: ${url}`;
-export function InviteButton({ url }: { url: string }) {
+export function InviteButton() {
+ const { InviteReferralModal, setShowInviteReferralModal } =
+ useInviteReferralModal();
+
return (
- <Button
- text="Invite via email"
- icon={<Mail className="size-4" />}
- className="h-9 rounded-lg"
- onClick={() =>
- window.open(
- `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body(url))}`,
- )
- }
- />
+ <>
+ <InviteReferralModal />
+ <Button
+ text="Invite via email"
+ icon={<Mail className="size-4" />}
+ className="h-9 rounded-lg"
+ onClick={() => setShowInviteReferralModal(true)}
+ />
+ </>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx
index 5dd1153f06..ba7fefe581 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page.tsx
@@ -1,14 +1,17 @@
import { EventType } from "@/lib/analytics/types";
import { dub } from "@/lib/dub";
+import { getWorkspace } from "@/lib/fetchers";
import { EventListSkeleton } from "@dub/blocks";
import { CopyButton, Logo } from "@dub/ui";
import { Check, CircleWarning } from "@dub/ui/src/icons";
-import { getPrettyUrl } from "@dub/utils";
+import { getPrettyUrl, linkConstructor } from "@dub/utils";
import {
ClicksCount,
LeadsCount,
+ LinkSchema,
SalesCount,
} from "dub/dist/commonjs/models/components";
+import { redirect } from "next/navigation";
import { Suspense } from "react";
import { ActivityList } from "./activity-list";
import { EventTabs } from "./event-tabs";
@@ -25,20 +28,29 @@ export default async function ReferralsPage({
params: { slug: string };
searchParams: { event?: string; page?: string };
}) {
- const linkUrl = `https://refer.dub.co/${slug}`;
const event = (searchParams.event ?? "clicks") as EventType;
const page = parseInt(searchParams.page ?? "0") || 0;
+ const workspace = await getWorkspace({ slug });
+
+ if (!workspace) {
+ return redirect(`/${slug}/settings`);
+ }
+
let errorCode = null;
+ let link: LinkSchema | null = null;
try {
- await dub.links.get({
- domain: "refer.dub.co",
- key: slug,
+ link = await dub.links.get({
+ externalId: `ext_ws_${workspace.id}`,
});
} catch (e) {
errorCode = e?.error?.code ?? "error";
}
+ const linkUrl = link
+ ? linkConstructor({ domain: link.domain, key: link.key })
+ : null;
+
return (
<ReferralsPageClient>
<div>
@@ -78,7 +90,7 @@ export default async function ReferralsPage({
{/* Referral link + invite button */}
<div className="mt-8">
- {!errorCode ? (
+ {linkUrl && !errorCode ? (
<div className="grid gap-1.5">
<p className="text-xs text-gray-500">Referral Link</p>
<div className="grid grid-cols-1 gap-x-2 gap-y-2 sm:max-w-sm sm:grid-cols-[1fr_auto] xl:max-w-md">
@@ -92,7 +104,7 @@ export default async function ReferralsPage({
className="p-1.5 text-gray-500"
/>
</div>
- <InviteButton url={linkUrl} />
+ <InviteButton />
</div>
</div>
) : errorCode === "not_found" ? (
diff --git a/apps/web/emails/referral-invite.tsx b/apps/web/emails/referral-invite.tsx
new file mode 100644
index 0000000000..a72b3fd7fd
--- /dev/null
+++ b/apps/web/emails/referral-invite.tsx
@@ -0,0 +1,84 @@
+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 function ReferralInvite({
+ email = "[email protected]",
+ appName = "Dub.co",
+ url = "https://dub.co",
+ workspaceUser = "Brendon Urie",
+ workspaceUserEmail = "[email protected]",
+}: {
+ email: string;
+ appName: string;
+ url: string;
+ workspaceUser: string | null;
+ workspaceUserEmail: string | null;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Sign up for {appName}</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img
+ src={DUB_WORDMARK}
+ height="40"
+ alt={appName}
+ className="mx-auto my-0"
+ />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Sign up for {appName}
+ </Heading>
+ {workspaceUser && workspaceUserEmail ? (
+ <Text className="text-sm leading-6 text-black">
+ <strong>{workspaceUser}</strong> (
+ <Link
+ className="text-blue-600 no-underline"
+ href={`mailto:${workspaceUserEmail}`}
+ >
+ {workspaceUserEmail}
+ </Link>
+ ) has invited you to start using {appName}!
+ </Text>
+ ) : (
+ <Text className="text-sm leading-6 text-black">
+ You have been invited to start using {appName}!
+ </Text>
+ )}
+ <Section className="mb-8 text-center">
+ <Link
+ className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ href={url}
+ >
+ Learn More
+ </Link>
+ </Section>
+ <Text className="text-sm leading-6 text-black">
+ or copy and paste this URL into your browser:
+ </Text>
+ <Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">
+ {url.replace(/^https?:\/\//, "")}
+ </Text>
+ <Footer email={email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/apps/web/lib/actions/generate-referral-link.ts b/apps/web/lib/actions/generate-referral-link.ts
index bc2faa936c..8ca704a78c 100644
--- a/apps/web/lib/actions/generate-referral-link.ts
+++ b/apps/web/lib/actions/generate-referral-link.ts
@@ -1,6 +1,6 @@
"use server";
-import { nanoid } from "@dub/utils";
+import { linkConstructor, nanoid } from "@dub/utils";
import { z } from "zod";
import { dub } from "../dub";
import { authActionClient } from "./safe-action";
@@ -38,7 +38,12 @@ export const generateReferralLink = authActionClient
trackConversion: true,
});
- return { url: `https://${createdLink.domain}/${createdLink.key}` };
+ return {
+ url: linkConstructor({
+ domain: createdLink.domain,
+ key: createdLink.key,
+ }),
+ };
} catch (e) {
console.error("Failed to generate referral link.", e);
}
diff --git a/apps/web/lib/actions/send-invite-referral-email.ts b/apps/web/lib/actions/send-invite-referral-email.ts
new file mode 100644
index 0000000000..dcd3509876
--- /dev/null
+++ b/apps/web/lib/actions/send-invite-referral-email.ts
@@ -0,0 +1,63 @@
+"use server";
+
+import { linkConstructor } from "@dub/utils";
+import { sendEmail } from "emails";
+import { ReferralInvite } from "emails/referral-invite";
+import { z } from "zod";
+import { dub } from "../dub";
+import { ratelimit } from "../upstash";
+import { emailSchema } from "../zod/schemas/auth";
+import { authActionClient } from "./safe-action";
+
+// Generate a new client secret for an integration
+export const sendInviteReferralEmail = authActionClient
+ .schema(
+ z.object({
+ workspaceId: z.string(),
+ email: emailSchema,
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace } = ctx;
+ const { email } = parsedInput;
+
+ // Allow 5 emails / workspace / minute
+ const { success: successWorkspace } = await ratelimit(5, "1 m").limit(
+ `invite-referral-email:${workspace.id}`,
+ );
+
+ // Allow 2 emails to a specific address / 2 hours (not one / hour to allow one quick retry)
+ const { success: successEmail } = await ratelimit(2, "2 h").limit(
+ `invite-referral-email:${email}`,
+ );
+
+ if (!successWorkspace || !successEmail)
+ throw new Error("Failed to send: rate limit exceeded");
+
+ try {
+ const link = await dub.links.get({
+ externalId: `ext_ws_${workspace.id}`,
+ });
+
+ const url = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+
+ return await sendEmail({
+ subject: `You've been invited to start using ${process.env.NEXT_PUBLIC_APP_NAME}`,
+ email,
+ react: ReferralInvite({
+ email,
+ appName: process.env.NEXT_PUBLIC_APP_NAME as string,
+ url,
+ workspaceUser: ctx.user.name || null,
+ workspaceUserEmail: ctx.user.email || null,
+ }),
+ });
+ } catch (e) {
+ console.error("Failed to send invitation email", e);
+ }
+
+ throw new Error("Failed to send invitation email");
+ });
diff --git a/apps/web/ui/modals/invite-referral-modal.tsx b/apps/web/ui/modals/invite-referral-modal.tsx
new file mode 100644
index 0000000000..224640c28f
--- /dev/null
+++ b/apps/web/ui/modals/invite-referral-modal.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { sendInviteReferralEmail } from "@/lib/actions/send-invite-referral-email";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Button, Logo, Modal, useMediaQuery } from "@dub/ui";
+import { useAction } from "next-safe-action/hooks";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { toast } from "sonner";
+
+function InviteReferralModal({
+ showInviteReferralModal,
+ setShowInviteReferralModal,
+}: {
+ showInviteReferralModal: boolean;
+ setShowInviteReferralModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const [email, setEmail] = useState("");
+ const { id: workspaceId } = useWorkspace();
+ const { isMobile } = useMediaQuery();
+
+ const { execute, isExecuting } = useAction(sendInviteReferralEmail, {
+ onSuccess: () => {
+ toast.success("Invitation sent.");
+ setShowInviteReferralModal(false);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError?.serverError);
+ },
+ });
+
+ return (
+ <Modal
+ showModal={showInviteReferralModal}
+ setShowModal={setShowInviteReferralModal}
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
+ <Logo />
+ <h3 className="text-lg font-medium">Invite via Email</h3>
+ <p className="text-center text-sm text-gray-500">
+ Invite a friend or colleague to use Dub with your referral link.
+ </p>
+ </div>
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ execute({ email, workspaceId: workspaceId! });
+ }}
+ className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-16"
+ >
+ <div>
+ <label htmlFor="email" className="block text-sm text-gray-700">
+ Email
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="email"
+ name="email"
+ id="email"
+ placeholder="[email protected]"
+ autoFocus={!isMobile}
+ autoComplete="off"
+ required
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ />
+ </div>
+ <p className="mt-2 text-xs text-gray-500">
+ Your name and email address will be shared in this invitation.
+ </p>
+ </div>
+ <Button loading={isExecuting} text="Send invite" />
+ </form>
+ </Modal>
+ );
+}
+
+export function useInviteReferralModal() {
+ const [showInviteReferralModal, setShowInviteReferralModal] = useState(false);
+
+ const InviteReferralModalCallback = useCallback(() => {
+ return (
+ <InviteReferralModal
+ showInviteReferralModal={showInviteReferralModal}
+ setShowInviteReferralModal={setShowInviteReferralModal}
+ />
+ );
+ }, [showInviteReferralModal, setShowInviteReferralModal]);
+
+ return useMemo(
+ () => ({
+ setShowInviteReferralModal,
+ InviteReferralModal: InviteReferralModalCallback,
+ }),
+ [setShowInviteReferralModal, InviteReferralModalCallback],
+ );
+}