The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Referrals Embed link creation flow
Kiran Kb7450af80f3f
diff --git a/apps/web/app/api/embed/referrals/analytics/route.ts b/apps/web/app/api/embed/referrals/analytics/route.tsindex 6b45dfb476..5526fd0a7f 100644--- a/apps/web/app/api/embed/referrals/analytics/route.ts+++ b/apps/web/app/api/embed/referrals/analytics/route.ts@@ -3,13 +3,13 @@ import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";import { NextResponse } from "next/server";// GET /api/embed/referrals/analytics – get timeseries analytics for a partner-export const GET = withReferralsEmbedToken(async ({ programId, partnerId }) => {+export const GET = withReferralsEmbedToken(async ({ programEnrollment }) => {const analytics = await getAnalytics({event: "composite",groupBy: "timeseries",interval: "1y",- programId,- partnerId,+ programId: programEnrollment.programId,+ partnerId: programEnrollment.partnerId,});return NextResponse.json(analytics);diff --git a/apps/web/app/api/embed/referrals/earnings/route.ts b/apps/web/app/api/embed/referrals/earnings/route.tsindex 07c73d8e90..a3239e9ebb 100644--- a/apps/web/app/api/embed/referrals/earnings/route.ts+++ b/apps/web/app/api/embed/referrals/earnings/route.ts@@ -7,7 +7,7 @@ import { NextResponse } from "next/server";// GET /api/embed/referrals/earnings – get commissions for a partner from an embed tokenexport const GET = withReferralsEmbedToken(- async ({ programId, partnerId, searchParams }) => {+ async ({ programEnrollment, searchParams }) => {const { page } = z.object({ page: z.coerce.number().optional().default(1) }).parse(searchParams);@@ -17,8 +17,8 @@ export const GET = withReferralsEmbedToken(earnings: {gt: 0,},- programId,- partnerId,+ programId: programEnrollment.programId,+ partnerId: programEnrollment.partnerId,},select: {id: true,diff --git a/apps/web/app/api/embed/referrals/leaderboard/route.ts b/apps/web/app/api/embed/referrals/leaderboard/route.tsindex 42f3be4a71..64a4b4a9f7 100644--- a/apps/web/app/api/embed/referrals/leaderboard/route.ts+++ b/apps/web/app/api/embed/referrals/leaderboard/route.ts@@ -5,7 +5,7 @@ import { NextResponse } from "next/server";import z from "node_modules/zod/lib";// GET /api/embed/referrals/leaderboard – get leaderboard for a program-export const GET = withReferralsEmbedToken(async ({ programId }) => {+export const GET = withReferralsEmbedToken(async ({ program }) => {const partners = await prisma.$queryRaw`SELECTp.id,@@ -26,11 +26,11 @@ export const GET = withReferralsEmbedToken(async ({ programId }) => {SUM(sales) as totalSales,SUM(saleAmount) as totalSaleAmountFROM Link- WHERE programId = ${programId}+ WHERE programId = ${program.id}GROUP BY partnerId) metrics ON metrics.partnerId = pe.partnerIdWHERE- pe.programId = ${programId}+ pe.programId = ${program.id}AND pe.status = 'approved'ORDER BYtotalSaleAmount DESC,diff --git a/apps/web/app/api/embed/referrals/links/route.ts b/apps/web/app/api/embed/referrals/links/route.tsnew file mode 100644index 0000000000..01acbc4291--- /dev/null+++ b/apps/web/app/api/embed/referrals/links/route.ts@@ -0,0 +1,89 @@+import { DubApiError, ErrorCodes } from "@/lib/api/errors";+import { createLink, processLink } from "@/lib/api/links";+import { parseRequestBody } from "@/lib/api/utils";+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";+import { LinkSchema } from "@/lib/zod/schemas/links";+import { createPartnerLinkSchema } from "@/lib/zod/schemas/partners";+import { getApexDomain } from "@dub/utils";+import { NextResponse } from "next/server";++// TODO: Move this to a constant+const PARTNER_LINKS_LIMIT = 5;++// POST /api/embed/referrals/links – create links for a partner+export const POST = withReferralsEmbedToken(+ async ({ req, programEnrollment, program, links }) => {+ const { url, key } = createPartnerLinkSchema+ .pick({ url: true, key: true })+ .parse(await parseRequestBody(req));++ if (programEnrollment.status === "banned") {+ throw new DubApiError({+ code: "forbidden",+ message: "You are banned from this program hence cannot create links.",+ });+ }++ if (!program.domain || !program.url) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "This program needs a domain and URL set before creating a link.",+ });+ }++ if (links.length >= PARTNER_LINKS_LIMIT) {+ throw new DubApiError({+ code: "bad_request",+ message: `You have reached the limit of ${PARTNER_LINKS_LIMIT} program links.`,+ });+ }++ if (url && getApexDomain(url) !== getApexDomain(program.url)) {+ throw new DubApiError({+ code: "bad_request",+ message: `The provided URL domain (${getApexDomain(url)}) does not match the program's domain (${getApexDomain(program.url)}).`,+ });+ }++ // TODO:+ // Under which workspace user the link should be created?++ const { link, error, code } = await processLink({+ payload: {+ key: key || undefined,+ url: url || program.url,+ domain: program.domain,+ programId: program.id,+ folderId: program.defaultFolderId,+ tenantId: programEnrollment.tenantId,+ partnerId: programEnrollment.partnerId,+ trackConversion: true,+ },+ workspace: {+ id: program.workspaceId,+ plan: "business",+ },+ userId: "cm1ypncqa0000tc44pfgxp6qs", //session.user.id,+ skipFolderChecks: true, // can't be changed by the partner+ skipProgramChecks: true, // can't be changed by the partner+ skipExternalIdChecks: true, // can't be changed by the partner+ });++ if (error != null) {+ throw new DubApiError({+ code: code as ErrorCodes,+ message: error,+ });+ }++ const partnerLink = LinkSchema.pick({+ id: true,+ domain: true,+ key: true,+ url: true,+ }).parse(await createLink(link));++ return NextResponse.json(partnerLink, { status: 201 });+ },+);diff --git a/apps/web/app/api/partner-profile/programs/[programId]/links/route.ts b/apps/web/app/api/partner-profile/programs/[programId]/links/route.tsindex 0df215f9e9..f0bf0f7293 100644--- a/apps/web/app/api/partner-profile/programs/[programId]/links/route.ts+++ b/apps/web/app/api/partner-profile/programs/[programId]/links/route.ts@@ -80,7 +80,7 @@ export const POST = withPartnerProfile(id: program.workspaceId,plan: "business",},- userId: session.user.id,+ userId: session.user.id, // TODO: Hm, this is the partner user, not the workspace user?skipFolderChecks: true, // can't be changed by the partnerskipProgramChecks: true, // can't be changed by the partnerskipExternalIdChecks: true, // can't be changed by the partnerdiff --git a/apps/web/app/app.dub.co/embed/referrals/create-link.tsx b/apps/web/app/app.dub.co/embed/referrals/create-link.tsxnew file mode 100644index 0000000000..f15f18711e--- /dev/null+++ b/apps/web/app/app.dub.co/embed/referrals/create-link.tsx@@ -0,0 +1,187 @@+import { mutateSuffix } from "@/lib/swr/mutate";+import {+ Button,+ InfoTooltip,+ SimpleTooltipContent,+ useCopyToClipboard,+ useMediaQuery,+} from "@dub/ui";+import { linkConstructor, TAB_ITEM_ANIMATION_SETTINGS } from "@dub/utils";+import { motion } from "framer-motion";+import { useMemo, useState } from "react";+import { useForm } from "react-hook-form";++interface Props {+ destinationDomain: string;+ shortLinkDomain: string;+}++interface FormData {+ url: string;+ key: string;+}++export function ReferralsEmbedCreateLink({+ destinationDomain,+ shortLinkDomain,+}: Props) {+ const { isMobile } = useMediaQuery();+ const [, copyToClipboard] = useCopyToClipboard();+ const [isSubmitting, setIsSubmitting] = useState(false);++ const { watch, register, handleSubmit } = useForm<FormData>();++ const [key, url] = watch("key", "url");++ const onSubmit = async (data: FormData) => {+ setIsSubmitting(true);++ try {+ const response = await fetch("/api/embed/referrals/links", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...data,+ url: linkConstructor({+ domain: destinationDomain,+ key: data.url,+ }),+ }),+ });++ const result = await response.json();++ // TODO:+ // Display success or error message++ if (!response.ok) {+ const { error } = result;+ return;+ }++ await mutateSuffix("/links");+ } finally {+ setIsSubmitting(false);+ }+ };++ const saveDisabled = useMemo(+ () => Boolean(isSubmitting || !key || !url),+ [isSubmitting, key, url],+ );++ return (+ <motion.div+ className="border-border-subtle relative rounded-md border"+ {...TAB_ITEM_ANIMATION_SETTINGS}+ >+ <form+ onSubmit={handleSubmit(onSubmit)}+ className="max-h-[26rem] overflow-auto"+ >+ <div className="flex items-center justify-between border-b border-neutral-200 px-4 py-3">+ <span className="text-base font-semibold">New link</span>+ <div className="flex items-center gap-x-2">+ <Button+ text="Cancel"+ variant="secondary"+ type="button"+ className="h-9"+ />+ <Button+ text="Create link"+ variant="primary"+ loading={isSubmitting}+ disabled={saveDisabled}+ className="h-9"+ />+ </div>+ </div>++ <div className="space-y-6 p-6">+ <div>+ <div className="flex items-center gap-2">+ <label+ htmlFor="url"+ className="block text-sm font-medium text-neutral-700"+ >+ Destination URL+ </label>+ <InfoTooltip+ content={+ <SimpleTooltipContent+ title="The URL your users will get redirected to when they visit your referral link."+ cta="Learn more."+ href="https://dub.co/help/article/how-to-create-link"+ />+ }+ />+ </div>+ <div className="mt-2 flex rounded-md">+ <span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">+ {destinationDomain}+ </span>+ <input+ type="text"+ placeholder="about"+ className="block w-full rounded-r-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ {...register("url", { required: false })}+ autoFocus={!isMobile}+ onPaste={(e: React.ClipboardEvent<HTMLInputElement>) => {+ e.preventDefault();++ // if pasting in a URL, extract the pathname+ const text = e.clipboardData.getData("text/plain");++ try {+ const url = new URL(text);+ e.currentTarget.value = url.pathname.slice(1);+ } catch (err) {+ e.currentTarget.value = text;+ }+ }}+ />+ </div>+ </div>++ <div>+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <label+ htmlFor="short-link"+ className="block text-sm font-medium"+ >+ Short link+ </label>+ <InfoTooltip+ content={+ <SimpleTooltipContent+ title="The URL that will be shared with your users. Keep it short and memorable!"+ cta="Learn more."+ href="https://dub.co/help/article/how-to-create-link"+ />+ }+ />+ </div>+ </div>+ <div className="mt-2 flex rounded-md">+ <span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">+ {shortLinkDomain}+ </span>+ <input+ type="text"+ placeholder="another-link"+ className="block w-full rounded-r-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ {...register("key", { required: true })}+ />+ </div>+ </div>+ </div>+ </form>++ <div className="from-bg-default pointer-events-none absolute -bottom-px left-0 h-16 w-full rounded-b-lg bg-gradient-to-t sm:bottom-0" />+ </motion.div>+ );+}diff --git a/apps/web/app/app.dub.co/embed/referrals/links-list.tsx b/apps/web/app/app.dub.co/embed/referrals/links-list.tsxnew file mode 100644index 0000000000..8587796ca1--- /dev/null+++ b/apps/web/app/app.dub.co/embed/referrals/links-list.tsx@@ -0,0 +1,104 @@+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";+import { Link } from "@dub/prisma/client";+import { Button, CopyButton, Table, Users, useTable } from "@dub/ui";+import { Pen2, Plus2 } from "@dub/ui/icons";+import { getPrettyUrl, TAB_ITEM_ANIMATION_SETTINGS } from "@dub/utils";+import { motion } from "framer-motion";++export function ReferralsEmbedLinksList({ links }: { links: Link[] }) {+ const { table, ...tableProps } = useTable({+ data: links,+ columns: [+ {+ id: "link",+ header: "Link",+ minSize: 200,+ cell: ({ row }) => {+ return (+ <div className="flex items-center gap-2">+ <CopyButton value={row.original.shortLink} />+ <span className="text-sm">+ {getPrettyUrl(row.original.shortLink)}+ </span>+ </div>+ );+ },+ },+ {+ id: "clicks",+ header: "Clicks",+ minSize: 80,+ maxSize: 100,+ cell: ({ row }) => row.original.clicks,+ },+ {+ id: "leads",+ header: "Leads",+ minSize: 80,+ maxSize: 100,+ cell: ({ row }) => row.original.leads,+ },+ {+ id: "sales",+ header: "Sales",+ minSize: 80,+ maxSize: 100,+ cell: ({ row }) => row.original.sales,+ },+ {+ id: "actions",+ header: () => (+ <Button+ variant="primary"+ className="h-7 w-7 p-1.5"+ icon={<Plus2 className="text-white" />}+ />+ ),+ minSize: 60,+ maxSize: 80,+ cell: ({ row }) => {+ return (+ <Button+ variant="secondary"+ className="h-7 w-7 p-1.5"+ icon={<Pen2 className="size-4" />}+ />+ );+ },+ },+ ],+ defaultColumn: {+ minSize: 60,+ },+ emptyState: (+ <AnimatedEmptyState+ title="No links found"+ description="No referral links found for you."+ cardContent={() => (+ <>+ <Users className="text-content-default size-4" />+ <div className="bg-bg-emphasis h-2.5 w-24 min-w-0 rounded-sm" />+ </>+ )}+ className="border-none md:min-h-fit"+ />+ ),+ thClassName: "border-l-0",+ tdClassName: "border-l-0",+ resourceName: (plural) => `link${plural ? "s" : ""}`,+ });++ return (+ <motion.div+ className="border-border-subtle relative rounded-md border"+ {...TAB_ITEM_ANIMATION_SETTINGS}+ >+ <Table+ {...tableProps}+ table={table}+ containerClassName="border-none max-h-[26rem] overflow-auto"+ />+ <div className="from-bg-default pointer-events-none absolute -bottom-px left-0 h-16 w-full rounded-b-lg bg-gradient-to-t sm:bottom-0" />+ </motion.div>+ );+}diff --git a/apps/web/app/app.dub.co/embed/referrals/links.tsx b/apps/web/app/app.dub.co/embed/referrals/links.tsxnew file mode 100644index 0000000000..2e16a3500f--- /dev/null+++ b/apps/web/app/app.dub.co/embed/referrals/links.tsx@@ -0,0 +1,25 @@+import { Link } from "@dub/prisma/client";+import { ReferralsEmbedCreateLink } from "./create-link";+import { ReferralsEmbedLinksList } from "./links-list";++interface Props {+ links: Link[];+ destinationDomain: string;+ shortLinkDomain: string;+}++export default function ReferralsEmbedLinks({+ links,+ destinationDomain,+ shortLinkDomain,+}: Props) {+ return (+ <div className="flex flex-col space-y-6">+ <ReferralsEmbedCreateLink+ destinationDomain={destinationDomain}+ shortLinkDomain={shortLinkDomain}+ />+ <ReferralsEmbedLinksList links={links} />+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/embed/referrals/page-client.tsx b/apps/web/app/app.dub.co/embed/referrals/page-client.tsxindex 8f86d8dee4..735686dbd8 100644--- a/apps/web/app/app.dub.co/embed/referrals/page-client.tsx+++ b/apps/web/app/app.dub.co/embed/referrals/page-client.tsx@@ -18,13 +18,14 @@ import {useLocalStorage,Wordmark,} from "@dub/ui";-import { cn, getPrettyUrl } from "@dub/utils";+import { cn, getDomainWithoutWWW, getPrettyUrl } from "@dub/utils";import { AnimatePresence } from "framer-motion";import { useEffect, useMemo, useState } from "react";import { ReferralsEmbedActivity } from "./activity";import { ReferralsEmbedEarnings } from "./earnings";import { ReferralsEmbedFAQ } from "./faq";import { ReferralsEmbedLeaderboard } from "./leaderboard";+import ReferralsEmbedLinks from "./links";import { ReferralsEmbedPayouts } from "./payouts";import { ReferralsEmbedQuickstart } from "./quickstart";import { ReferralsEmbedResources } from "./resources";@@ -75,6 +76,7 @@ export function ReferralsEmbedPageClient({() => [...(showQuickstart ? ["Quickstart"] : []),"Earnings",+ "Links",...(programEmbedData?.leaderboard?.mode === "disabled"? []: ["Leaderboard"]),@@ -91,6 +93,11 @@ export function ReferralsEmbedPageClient({if (!tabs.includes(selectedTab)) setSelectedTab(tabs[0]);}, [tabs, selectedTab]);+ const shortLinkDomain = program.domain || "";+ const destinationDomain = program.url+ ? getDomainWithoutWWW(program.url)!+ : "";+return (<divstyle={@@ -220,6 +227,12 @@ export function ReferralsEmbedPageClient({/>) : selectedTab === "Earnings" ? (<ReferralsEmbedEarnings salesCount={stats.sales} />+ ) : selectedTab === "Links" ? (+ <ReferralsEmbedLinks+ links={links}+ destinationDomain={destinationDomain}+ shortLinkDomain={shortLinkDomain}+ />) : selectedTab === "Leaderboard" &&programEmbedData?.leaderboard?.mode !== "disabled" ? (<ReferralsEmbedLeaderboard />diff --git a/apps/web/lib/embed/referrals/auth.ts b/apps/web/lib/embed/referrals/auth.tsindex ad53a4d074..cfc77aa4e3 100644--- a/apps/web/lib/embed/referrals/auth.ts+++ b/apps/web/lib/embed/referrals/auth.ts@@ -1,7 +1,7 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { ratelimit } from "@/lib/upstash";import { prisma } from "@dub/prisma";-import { Link, Program } from "@dub/prisma/client";+import { Link, Program, ProgramEnrollment } from "@dub/prisma/client";import { getSearchParams } from "@dub/utils";import { AxiomRequest, withAxiom } from "next-axiom";import { cookies } from "next/headers";@@ -14,8 +14,7 @@ interface WithReferralsEmbedTokenHandler {params,searchParams,program,- programId,- partnerId,+ programEnrollment,links,embedToken,}: {@@ -23,8 +22,7 @@ interface WithReferralsEmbedTokenHandler {params: Record<string, string>;searchParams: Record<string, string>;program: Program;- programId: string;- partnerId: string;+ programEnrollment: ProgramEnrollment;links: Link[];embedToken: string;}): Promise<Response>;@@ -85,7 +83,7 @@ export const withReferralsEmbedToken = (});}- const programEnrollment =+ const { program, links, ...programEnrollment } =await prisma.programEnrollment.findUniqueOrThrow({where: {partnerId_programId: { partnerId, programId },@@ -100,10 +98,9 @@ export const withReferralsEmbedToken = (req,params,searchParams,- program: programEnrollment.program,- programId,- partnerId: programEnrollment.partnerId,- links: programEnrollment.links,+ program,+ programEnrollment,+ links,embedToken: tokenFromCookie,});} catch (error) {diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.tsindex b4328cb106..8a8183262d 100644--- a/packages/ui/src/icons/nucleo/index.ts+++ b/packages/ui/src/icons/nucleo/index.ts@@ -152,6 +152,7 @@ export * from "./percentage-arrow-down";export * from "./photo";export * from "./plug2";export * from "./plus";+export * from "./plus2";export * from "./post";export * from "./pyramid";export * from "./qrcode";diff --git a/packages/ui/src/icons/nucleo/plus2.tsx b/packages/ui/src/icons/nucleo/plus2.tsxnew file mode 100644index 0000000000..4cfc32ee44--- /dev/null+++ b/packages/ui/src/icons/nucleo/plus2.tsx@@ -0,0 +1,20 @@+import { SVGProps } from "react";++export function Plus2(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ width="16"+ height="16"+ viewBox="0 0 16 16"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <path+ d="M8 3V13M13 8L3 8"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </svg>+ );+}\ No newline at end of file