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.

use public token

Kiran K6f2ac076f30a
diff --git a/apps/web/app/api/referrals/tokens/route.ts b/apps/web/app/api/referrals/tokens/route.ts
index 8643ad9046..aeb2952b6d 100644
--- a/apps/web/app/api/referrals/tokens/route.ts
+++ b/apps/web/app/api/referrals/tokens/route.ts
@@ -1,16 +1,10 @@
-import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
-import {
- REFERRAL_PUBLIC_TOKEN_EXPIRY,
- REFERRAL_PUBLIC_TOKEN_LENGTH,
-} from "@/lib/referrals/constants";
+import { createPublicToken } from "@/lib/referrals/token";
import {
createReferralTokenSchema,
referralTokenSchema,
} from "@/lib/zod/schemas/referrals";
-import { nanoid } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/referrals/tokens - create a new referral token for the given link
@@ -19,29 +13,9 @@ export const POST = withWorkspace(async ({ workspace, req }) => {
await parseRequestBody(req),
);
- const link = await prisma.link.findUniqueOrThrow({
- where: {
- id: linkId,
- projectId: workspace.id,
- },
- });
-
- if (!link.trackConversion) {
- throw new DubApiError({
- code: "forbidden",
- message: "Conversion tracking is not enabled for this link.",
- });
- }
-
- const referralToken = await prisma.referralPublicToken.create({
- data: {
- linkId,
- expires: new Date(Date.now() + REFERRAL_PUBLIC_TOKEN_EXPIRY),
- publicToken: nanoid(REFERRAL_PUBLIC_TOKEN_LENGTH),
- },
- });
+ const token = await createPublicToken({ linkId, workspaceId: workspace.id });
- return NextResponse.json(referralTokenSchema.parse(referralToken), {
+ return NextResponse.json(referralTokenSchema.parse(token), {
status: 201,
});
});
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts
new file mode 100644
index 0000000000..66a31c301b
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts
@@ -0,0 +1,26 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withWorkspace } from "@/lib/auth";
+import { createPublicToken } from "@/lib/referrals/token";
+import { referralTokenSchema } from "@/lib/zod/schemas/referrals";
+import { NextResponse } from "next/server";
+
+// GET /api/workspaces/[idOrSlug]/referrals-token - create a new referral token for the workspace
+export const POST = withWorkspace(async ({ workspace }) => {
+ const { referralLinkId, id } = workspace;
+
+ if (!referralLinkId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Referral link not found for this workspace.",
+ });
+ }
+
+ const token = await createPublicToken({
+ linkId: referralLinkId,
+ workspaceId: id,
+ });
+
+ return NextResponse.json(referralTokenSchema.parse(token), {
+ status: 201,
+ });
+});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
index acac0c8944..aa637d4dd2 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
@@ -1,19 +1,63 @@
"use client";
+import { EventType } from "@/lib/analytics/types";
import useWorkspace from "@/lib/swr/use-workspace";
import { redirect } from "next/navigation";
-import { ReactNode } from "react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { Referrals } from "./referrals";
+
+// TODO:
+// event and page should be part of iframe
+interface ReferralsPageClientProps {
+ event: EventType | undefined;
+ page: string | undefined;
+}
export default function ReferralsPageClient({
- children,
-}: {
- children: ReactNode;
-}) {
+ event,
+ page,
+}: ReferralsPageClientProps) {
const { slug, flags } = useWorkspace();
+ const [publicToken, setPublicToken] = useState<string | null>(null);
+
+ // Get publicToken from server when component mounts
+ const createPublicToken = async () => {
+ const response = await fetch(`/api/workspaces/${slug}/referrals-token`, {
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ throw toast.error("Failed to create public token");
+ }
+
+ const { publicToken } = (await response.json()) as {
+ publicToken: string;
+ };
+
+ setPublicToken(publicToken);
+ };
+
+ useEffect(() => {
+ createPublicToken();
+ }, []);
if (!flags?.referrals) {
redirect(`/${slug}/settings`);
}
- return <>{children}</>;
+ if (!publicToken) {
+ return null;
+ }
+
+ return (
+ <>
+ <Referrals
+ slug={slug!}
+ event={event}
+ page={page}
+ publicToken={publicToken}
+ />
+ </>
+ );
}
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 6f8534e57e..3c0e349ab6 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,108 +1,16 @@
import { EventType } from "@/lib/analytics/types";
-import {
- REFERRAL_CLICKS_QUOTA_BONUS,
- REFERRAL_CLICKS_QUOTA_BONUS_MAX,
- REFERRAL_REVENUE_SHARE,
-} from "@/lib/referrals/constants";
-import { Wordmark } from "@dub/ui";
-import { Check } from "@dub/ui/src/icons";
-import { nFormatter } from "@dub/utils";
-import { Suspense } from "react";
-import { EventTabs } from "./event-tabs";
-import { Events } from "./events";
-import { HeroBackground } from "./hero-background";
import ReferralsPageClient from "./page-client";
-import ReferralLink, { ReferralLinkSkeleton } from "./referral-link";
-import { Stats } from "./stats";
-
-export const revalidate = 0;
export default function ReferralsPage({
- params: { slug },
searchParams,
}: {
- params: { slug: string };
searchParams: { event?: EventType; page?: string };
}) {
- const event = searchParams.event || "clicks";
- const page = searchParams.page || "1";
+ const { event, page } = searchParams;
return (
- <ReferralsPageClient>
- <div>
- <div className="relative">
- <div className="relative overflow-hidden rounded-xl border border-gray-200 p-4 sm:p-9">
- <Suspense>
- <HeroBackground slug={slug} />
- </Suspense>
-
- <div className="relative">
- <h1 className="text-xl font-semibold text-black sm:text-2xl">
- Refer and earn
- </h1>
-
- {/* Benefits */}
- <div className="mt-6 flex flex-col gap-6">
- {[
- {
- title: `${nFormatter(REFERRAL_REVENUE_SHARE * 100)}% recurring revenue`,
- description: "per paying customer (up to 1 year)",
- },
- {
- title: `${nFormatter(REFERRAL_CLICKS_QUOTA_BONUS)} extra clicks quota per month`,
- description: `per signup (up to ${nFormatter(REFERRAL_CLICKS_QUOTA_BONUS_MAX, { full: true })} total)`,
- },
- ].map(({ title, description }) => (
- <div className="flex items-center gap-3">
- <div className="flex size-9 items-center justify-center rounded-full border border-gray-200 bg-gradient-to-t from-gray-100 to-white">
- <div className="rounded-full bg-green-500 p-0.5">
- <Check className="size-3.5 text-white" />
- </div>
- </div>
- <div>
- <p className="text-base font-medium text-gray-800">
- {title}
- </p>
- <p className="text-xs text-gray-500">{description}</p>
- </div>
- </div>
- ))}
- </div>
-
- {/* Referral link + invite button or empty/error states */}
- <Suspense fallback={<ReferralLinkSkeleton />}>
- <ReferralLink slug={slug} />
- </Suspense>
- </div>
- </div>
-
- {/* Powered by Dub Conversions */}
- <a
- href="https://d.to/conversions"
- target="_blank"
- className="mt-2 flex items-center justify-center gap-2 rounded-lg border-gray-100 bg-white p-2 transition-colors hover:border-gray-200 active:bg-gray-50 md:absolute md:bottom-3 md:right-3 md:mt-0 md:translate-x-0 md:border md:drop-shadow-sm"
- >
- <Wordmark className="h-4" />
- <p className="text-xs text-gray-800">
- Powered by <span className="font-medium">Dub Conversions</span>
- </p>
- </a>
- </div>
-
- {/* Stats */}
- <div className="mt-8">
- <Stats />
- </div>
-
- {/* Events */}
- <div className="mt-12">
- <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
- <h2 className="text-xl font-semibold text-gray-800">Activity</h2>
- <EventTabs />
- </div>
- <Events event={event} page={page} />
- </div>
- </div>
- </ReferralsPageClient>
+ <>
+ <ReferralsPageClient event={event} page={page} />
+ </>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx
index 7be3b58c09..abc64d83dc 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx
@@ -1,11 +1,10 @@
-import { getReferralLink } from "@/lib/actions/get-referral-link";
import { CopyButton } from "@dub/ui";
import { getPrettyUrl } from "@dub/utils";
import { GenerateButton } from "./generate-button";
import { InviteButton } from "./invite-button";
export default async function ReferralLink({ slug }: { slug: string }) {
- const { shortLink } = (await getReferralLink(slug)) || {};
+ const shortLink = "demo";
return (
<div className="mt-8">
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referrals.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referrals.tsx
new file mode 100644
index 0000000000..10d924c046
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referrals.tsx
@@ -0,0 +1,115 @@
+"use client";
+
+import { EventType } from "@/lib/analytics/types";
+import {
+ REFERRAL_CLICKS_QUOTA_BONUS,
+ REFERRAL_CLICKS_QUOTA_BONUS_MAX,
+ REFERRAL_REVENUE_SHARE,
+} from "@/lib/referrals/constants";
+import { DubProvider } from "@dub/blocks";
+import { Wordmark } from "@dub/ui";
+import { Check } from "@dub/ui/src/icons";
+import { nFormatter } from "@dub/utils";
+import { Suspense } from "react";
+import { EventTabs } from "./event-tabs";
+import { Events } from "./events";
+import { HeroBackground } from "./hero-background";
+import ReferralLink, { ReferralLinkSkeleton } from "./referral-link";
+import { Stats } from "./stats";
+
+interface ReferralsProps {
+ slug: string;
+ event: EventType | undefined;
+ page: string | undefined;
+ publicToken: string | undefined | null;
+}
+
+export const Referrals = ({
+ slug,
+ event,
+ page,
+ publicToken,
+}: ReferralsProps) => {
+ if (!publicToken) {
+ return <ReferralLinkSkeleton />;
+ }
+
+ return (
+ <DubProvider publicToken={publicToken}>
+ <div>
+ <div className="relative">
+ <div className="relative overflow-hidden rounded-xl border border-gray-200 p-4 sm:p-9">
+ <Suspense>
+ <HeroBackground slug={slug} />
+ </Suspense>
+
+ <div className="relative">
+ <h1 className="text-xl font-semibold text-black sm:text-2xl">
+ Refer and earn
+ </h1>
+
+ {/* Benefits */}
+ <div className="mt-6 flex flex-col gap-6">
+ {[
+ {
+ title: `${nFormatter(REFERRAL_REVENUE_SHARE * 100)}% recurring revenue`,
+ description: "per paying customer (up to 1 year)",
+ },
+ {
+ title: `${nFormatter(REFERRAL_CLICKS_QUOTA_BONUS)} extra clicks quota per month`,
+ description: `per signup (up to ${nFormatter(REFERRAL_CLICKS_QUOTA_BONUS_MAX, { full: true })} total)`,
+ },
+ ].map(({ title, description }) => (
+ <div className="flex items-center gap-3">
+ <div className="flex size-9 items-center justify-center rounded-full border border-gray-200 bg-gradient-to-t from-gray-100 to-white">
+ <div className="rounded-full bg-green-500 p-0.5">
+ <Check className="size-3.5 text-white" />
+ </div>
+ </div>
+ <div>
+ <p className="text-base font-medium text-gray-800">
+ {title}
+ </p>
+ <p className="text-xs text-gray-500">{description}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Referral link + invite button or empty/error states */}
+ <Suspense fallback={<ReferralLinkSkeleton />}>
+ <ReferralLink slug={slug} />
+ </Suspense>
+ </div>
+ </div>
+
+ {/* Powered by Dub Conversions */}
+ <a
+ href="https://d.to/conversions"
+ target="_blank"
+ className="mt-2 flex items-center justify-center gap-2 rounded-lg border-gray-100 bg-white p-2 transition-colors hover:border-gray-200 active:bg-gray-50 md:absolute md:bottom-3 md:right-3 md:mt-0 md:translate-x-0 md:border md:drop-shadow-sm"
+ >
+ <Wordmark className="h-4" />
+ <p className="text-xs text-gray-800">
+ Powered by <span className="font-medium">Dub Conversions</span>
+ </p>
+ </a>
+ </div>
+
+ {/* Stats */}
+ <div className="mt-8">
+ <Stats />
+ </div>
+
+ {/* Events */}
+ <div className="mt-12">
+ <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
+ <h2 className="text-xl font-semibold text-gray-800">Activity</h2>
+ <EventTabs />
+ </div>
+ <Events event={event || "clicks"} page={page || "1"} />
+ </div>
+ </div>
+ </DubProvider>
+ );
+};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx
index 50f919fc35..2925b93fca 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/stats.tsx
@@ -40,6 +40,8 @@ export const Stats = () => {
const loading = isLoadingSales || isLoadingTotalEvents;
+ console.log({ sales, totalEvents });
+
return (
<div className="grid grid-cols-1 gap-x-4 gap-y-4 md:grid-cols-2 lg:gap-x-6">
{loading ? (
diff --git a/apps/web/app/app.dub.co/embed/page.tsx b/apps/web/app/app.dub.co/embed/page.tsx
new file mode 100644
index 0000000000..23e123c025
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/page.tsx
@@ -0,0 +1,3 @@
+export default function EmbedPage() {
+ return <div>Embed Page</div>;
+}
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index 9b8daa6330..a173b09390 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -12,6 +12,10 @@ export default async function AppMiddleware(req: NextRequest) {
const user = await getUserViaToken(req);
const isWorkspaceInvite = req.nextUrl.searchParams.get("invite");
+ if (path.startsWith("/embed")) {
+ return NextResponse.rewrite(new URL(`/app.dub.co${fullPath}`, req.url));
+ }
+
// if there's no user and the path isn't /login or /register, redirect to /login
if (
!user &&
diff --git a/apps/web/lib/referrals/auth.ts b/apps/web/lib/referrals/auth.ts
index f7a6448486..cb19197e1f 100644
--- a/apps/web/lib/referrals/auth.ts
+++ b/apps/web/lib/referrals/auth.ts
@@ -33,9 +33,10 @@ export const withAuth = (handler: WithAuthHandler) => {
let link: Link | undefined = undefined;
let tokenFromHeader: string | undefined = undefined;
- const rateLimit = 100;
+ const rateLimit = 60;
const searchParams = getSearchParams(req.url);
- const authorizationHeader = req.headers.get("Authorization");
+
+ // const authorizationHeader = req.headers.get("Authorization");
// if (!authorizationHeader) {
// throw new DubApiError({
@@ -61,11 +62,19 @@ export const withAuth = (handler: WithAuthHandler) => {
// });
// }
- tokenFromHeader = "i2yisemInUCWbWnEXB1WR4b3ROe2lLccYulj";
+ // Read token from query params
+ const tokenFromQuery = searchParams["publicToken"];
+
+ if (!tokenFromQuery) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Missing public token.",
+ });
+ }
const publicToken = await prisma.referralPublicToken.findUnique({
where: {
- publicToken: tokenFromHeader,
+ publicToken: tokenFromQuery,
},
});
@@ -86,7 +95,7 @@ export const withAuth = (handler: WithAuthHandler) => {
const { success, limit, reset, remaining } = await ratelimit(
rateLimit,
"1 m",
- ).limit(tokenFromHeader);
+ ).limit(tokenFromQuery);
headers = {
"Retry-After": reset.toString(),
diff --git a/apps/web/lib/referrals/token.ts b/apps/web/lib/referrals/token.ts
new file mode 100644
index 0000000000..04e8638ec4
--- /dev/null
+++ b/apps/web/lib/referrals/token.ts
@@ -0,0 +1,37 @@
+import { prisma } from "@/lib/prisma";
+import { nanoid } from "@dub/utils";
+import { DubApiError } from "../api/errors";
+import {
+ REFERRAL_PUBLIC_TOKEN_EXPIRY,
+ REFERRAL_PUBLIC_TOKEN_LENGTH,
+} from "./constants";
+
+export const createPublicToken = async ({
+ linkId,
+ workspaceId,
+}: {
+ linkId: string;
+ workspaceId: string;
+}) => {
+ const link = await prisma.link.findUniqueOrThrow({
+ where: {
+ id: linkId,
+ projectId: workspaceId,
+ },
+ });
+
+ if (!link.trackConversion) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Conversion tracking is not enabled for this link.",
+ });
+ }
+
+ return await prisma.referralPublicToken.create({
+ data: {
+ linkId,
+ expires: new Date(Date.now() + REFERRAL_PUBLIC_TOKEN_EXPIRY),
+ publicToken: nanoid(REFERRAL_PUBLIC_TOKEN_LENGTH),
+ },
+ });
+};
diff --git a/packages/blocks/src/context.tsx b/packages/blocks/src/context.tsx
new file mode 100644
index 0000000000..44b818ed41
--- /dev/null
+++ b/packages/blocks/src/context.tsx
@@ -0,0 +1,27 @@
+import React, { createContext, useContext } from "react";
+
+interface DubContextType {
+ publicToken: string;
+}
+
+const DubContext = createContext<DubContextType | undefined>(undefined);
+
+export const DubProvider: React.FC<
+ DubContextType & { children: React.ReactNode }
+> = ({ publicToken, children }) => {
+ return (
+ <DubContext.Provider value={{ publicToken }}>
+ {children}
+ </DubContext.Provider>
+ );
+};
+
+export const useDub = () => {
+ const context = useContext(DubContext);
+
+ if (context === undefined) {
+ throw new Error("useDub must be used within a DubProvider");
+ }
+
+ return context;
+};
diff --git a/packages/blocks/src/hooks/use-analytics.ts b/packages/blocks/src/hooks/use-analytics.ts
index daa44ed860..24086cda7a 100644
--- a/packages/blocks/src/hooks/use-analytics.ts
+++ b/packages/blocks/src/hooks/use-analytics.ts
@@ -1,5 +1,6 @@
import { fetcher } from "@dub/utils";
import useSWR from "swr";
+import { useDub } from "../context";
import { EventType } from "../types";
interface UseAnalyticsParams {
@@ -13,10 +14,13 @@ export const useAnalytics = ({
interval,
groupBy,
}: UseAnalyticsParams) => {
+ const { publicToken } = useDub();
+
const searchParams = new URLSearchParams({
event,
interval,
groupBy,
+ publicToken,
});
const { error, data, isLoading } = useSWR(
diff --git a/packages/blocks/src/hooks/use-events.ts b/packages/blocks/src/hooks/use-events.ts
index 5ea3bfbd96..b575a758c7 100644
--- a/packages/blocks/src/hooks/use-events.ts
+++ b/packages/blocks/src/hooks/use-events.ts
@@ -1,5 +1,6 @@
import { fetcher } from "@dub/utils";
import useSWR from "swr";
+import { useDub } from "../context";
import { EventType } from "../types";
interface UseEventsParams {
@@ -9,10 +10,13 @@ interface UseEventsParams {
}
export const useEvents = ({ event, interval, page }: UseEventsParams) => {
+ const { publicToken } = useDub();
+
const searchParams = new URLSearchParams({
event,
interval,
page,
+ publicToken,
});
const { error, data, isLoading } = useSWR<[]>(
diff --git a/packages/blocks/src/index.ts b/packages/blocks/src/index.ts
index 3a7736b51e..cfba1d9737 100644
--- a/packages/blocks/src/index.ts
+++ b/packages/blocks/src/index.ts
@@ -1,6 +1,7 @@
// styles
import "./styles.css";
+export * from "./context";
export * from "./empty-state";
export * from "./event-list";
export * from "./gauge";