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.

Improve embed token handling

Kiran K1ff9452d2ade
diff --git a/apps/web/app/app.dub.co/embed/referrals/activity.tsx b/apps/web/app/app.dub.co/embed/referrals/activity.tsx
index 56e28fb16f..521aa9e73d 100644
--- a/apps/web/app/app.dub.co/embed/referrals/activity.tsx
+++ b/apps/web/app/app.dub.co/embed/referrals/activity.tsx
@@ -1,3 +1,4 @@
+import { useEmbedToken } from "@/lib/swr/use-embed-token";
import { CursorRays } from "@/ui/layout/sidebar/icons/cursor-rays";
import { InfoTooltip, MiniAreaChart } from "@dub/ui";
import { cn, currencyFormatter, nFormatter } from "@dub/utils";
@@ -17,9 +18,11 @@ export function ReferralsEmbedActivity({
sales: number;
saleAmount: number;
}) {
+ const token = useEmbedToken();
+
const isEmpty = clicks === 0 && leads === 0 && sales === 0;
const { data: analytics } = useSWR<AnalyticsTimeseries[]>(
- !isEmpty && "/api/embed/referrals/analytics",
+ !isEmpty && `/api/embed/referrals/analytics?token=${token}`,
fetcher,
{
keepPreviousData: true,
diff --git a/apps/web/app/app.dub.co/embed/referrals/earnings.tsx b/apps/web/app/app.dub.co/embed/referrals/earnings.tsx
index feeb622819..79dab345a1 100644
--- a/apps/web/app/app.dub.co/embed/referrals/earnings.tsx
+++ b/apps/web/app/app.dub.co/embed/referrals/earnings.tsx
@@ -1,4 +1,5 @@
import { REFERRALS_EMBED_EARNINGS_LIMIT } from "@/lib/partners/constants";
+import { useEmbedToken } from "@/lib/swr/use-embed-token";
import { PartnerEarningsResponse } from "@/lib/types";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
import { Gift, StatusBadge, Table, usePagination, useTable } from "@dub/ui";
@@ -13,11 +14,13 @@ import { motion } from "framer-motion";
import useSWR from "swr";
export function ReferralsEmbedEarnings({ salesCount }: { salesCount: number }) {
+ const token = useEmbedToken();
+
const { pagination, setPagination } = usePagination(
REFERRALS_EMBED_EARNINGS_LIMIT,
);
const { data: earnings, isLoading } = useSWR<PartnerEarningsResponse[]>(
- `/api/embed/referrals/earnings?page=${pagination.pageIndex}`,
+ `/api/embed/referrals/earnings?page=${pagination.pageIndex}&token=${token}`,
fetcher,
{
keepPreviousData: true,
diff --git a/apps/web/app/app.dub.co/embed/referrals/leaderboard.tsx b/apps/web/app/app.dub.co/embed/referrals/leaderboard.tsx
index dc173b060d..c84c337b4b 100644
--- a/apps/web/app/app.dub.co/embed/referrals/leaderboard.tsx
+++ b/apps/web/app/app.dub.co/embed/referrals/leaderboard.tsx
@@ -1,3 +1,4 @@
+import { useEmbedToken } from "@/lib/swr/use-embed-token";
import z from "@/lib/zod";
import { LeaderboardPartnerSchema } from "@/lib/zod/schemas/partners";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
@@ -12,9 +13,11 @@ import { motion } from "framer-motion";
import useSWR from "swr";
export function ReferralsEmbedLeaderboard() {
+ const token = useEmbedToken();
+
const { data: partners, isLoading } = useSWR<
z.infer<typeof LeaderboardPartnerSchema>[]
- >("/api/embed/referrals/leaderboard", fetcher, {
+ >(`/api/embed/referrals/leaderboard?token=${token}`, fetcher, {
keepPreviousData: true,
});
diff --git a/apps/web/app/app.dub.co/embed/referrals/token.tsx b/apps/web/app/app.dub.co/embed/referrals/token.tsx
index d49d6bf7e2..d65b147ded 100644
--- a/apps/web/app/app.dub.co/embed/referrals/token.tsx
+++ b/apps/web/app/app.dub.co/embed/referrals/token.tsx
@@ -1,12 +1,15 @@
"use client";
+import { useEmbedToken } from "@/lib/swr/use-embed-token";
import { fetcher } from "@dub/utils";
import { useEffect } from "react";
import useSWR from "swr";
export const ReferralsReferralsEmbedToken = () => {
+ const token = useEmbedToken();
+
const { error } = useSWR<{ token: number }>(
- "/api/embed/referrals/token",
+ `/api/embed/referrals/token?token=${token}`,
fetcher,
{
revalidateOnFocus: true,
diff --git a/apps/web/lib/embed/constants.ts b/apps/web/lib/embed/constants.ts
index 0f29254cb9..ac7bc0c964 100644
--- a/apps/web/lib/embed/constants.ts
+++ b/apps/web/lib/embed/constants.ts
@@ -1,11 +1,3 @@
// Embed public token
export const EMBED_PUBLIC_TOKEN_PREFIX = "dub_embed_";
export const EMBED_PUBLIC_TOKEN_EXPIRY = 24 * 60 * 60; // 24 hours
-
-// Referrals embed token
-export const REFERRALS_EMBED_PUBLIC_TOKEN_COOKIE_NAME =
- "dub_referrals_embed_token";
-
-// Analytics embed token
-export const ANALYTICS_EMBED_PUBLIC_TOKEN_COOKIE_NAME =
- "dub_analytics_embed_token";
diff --git a/apps/web/lib/embed/referrals/auth.ts b/apps/web/lib/embed/referrals/auth.ts
index ad53a4d074..38f1527274 100644
--- a/apps/web/lib/embed/referrals/auth.ts
+++ b/apps/web/lib/embed/referrals/auth.ts
@@ -4,8 +4,6 @@ import { prisma } from "@dub/prisma";
import { Link, Program } from "@dub/prisma/client";
import { getSearchParams } from "@dub/utils";
import { AxiomRequest, withAxiom } from "next-axiom";
-import { cookies } from "next/headers";
-import { REFERRALS_EMBED_PUBLIC_TOKEN_COOKIE_NAME } from "../constants";
import { referralsEmbedToken } from "./token-class";
interface WithReferralsEmbedTokenHandler {
@@ -43,13 +41,9 @@ export const withReferralsEmbedToken = (
try {
const rateLimit = 60;
const searchParams = getSearchParams(req.url);
+ const embedToken = searchParams.token;
- const cookieStore = cookies();
- const tokenFromCookie = cookieStore.get(
- REFERRALS_EMBED_PUBLIC_TOKEN_COOKIE_NAME,
- )?.value;
-
- if (!tokenFromCookie) {
+ if (!embedToken) {
throw new DubApiError({
code: "unauthorized",
message: "Embed public token not found in the request.",
@@ -57,7 +51,7 @@ export const withReferralsEmbedToken = (
}
const { programId, partnerId } =
- (await referralsEmbedToken.get(tokenFromCookie)) ?? {};
+ (await referralsEmbedToken.get(embedToken)) ?? {};
if (!programId || !partnerId) {
throw new DubApiError({
@@ -69,7 +63,7 @@ export const withReferralsEmbedToken = (
const { success, limit, reset, remaining } = await ratelimit(
rateLimit,
"1 m",
- ).limit(tokenFromCookie);
+ ).limit(embedToken);
headers = {
"Retry-After": reset.toString(),
@@ -104,7 +98,7 @@ export const withReferralsEmbedToken = (
programId,
partnerId: programEnrollment.partnerId,
links: programEnrollment.links,
- embedToken: tokenFromCookie,
+ embedToken,
});
} catch (error) {
req.log.error(error);
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index 19d27fe575..c8f71afdea 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -1,6 +1,5 @@
import { parse } from "@/lib/middleware/utils";
import { NextRequest, NextResponse } from "next/server";
-import EmbedMiddleware from "./embed";
import NewLinkMiddleware from "./new-link";
import { appRedirect } from "./utils/app-redirect";
import { getDefaultWorkspace } from "./utils/get-default-workspace";
@@ -12,10 +11,6 @@ import WorkspacesMiddleware from "./workspaces";
export default async function AppMiddleware(req: NextRequest) {
const { path, fullPath, searchParamsString } = parse(req);
- if (path.startsWith("/embed")) {
- return EmbedMiddleware(req);
- }
-
const user = await getUserViaToken(req);
const isWorkspaceInvite =
req.nextUrl.searchParams.get("invite") || path.startsWith("/invites/");
diff --git a/apps/web/lib/middleware/embed.ts b/apps/web/lib/middleware/embed.ts
deleted file mode 100644
index 1199e0b5b7..0000000000
--- a/apps/web/lib/middleware/embed.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { NextRequest, NextResponse } from "next/server";
-import { REFERRALS_EMBED_PUBLIC_TOKEN_COOKIE_NAME } from "../embed/constants";
-import { referralsEmbedToken } from "../embed/referrals/token-class";
-import { parse } from "./utils";
-
-export default async function EmbedMiddleware(req: NextRequest) {
- const { path, fullPath } = parse(req);
-
- const token = req.nextUrl.searchParams.get("token");
-
- const embedTokenClass = path.endsWith("/referrals")
- ? referralsEmbedToken
- : null; // future: add class for analytics embed token
-
- if (token && embedTokenClass) {
- const tokenData = await embedTokenClass.get(token);
-
- if (tokenData) {
- return NextResponse.rewrite(new URL(`/app.dub.co${fullPath}`, req.url), {
- headers: {
- "Set-Cookie": `${REFERRALS_EMBED_PUBLIC_TOKEN_COOKIE_NAME}=${token}; HttpOnly; Secure; SameSite=None; Path=/`,
- },
- });
- }
- }
-
- return NextResponse.redirect(new URL("/", req.url));
-}
diff --git a/apps/web/lib/swr/use-embed-token.ts b/apps/web/lib/swr/use-embed-token.ts
new file mode 100644
index 0000000000..44a9efb42b
--- /dev/null
+++ b/apps/web/lib/swr/use-embed-token.ts
@@ -0,0 +1,7 @@
+import { useSearchParams } from "next/navigation";
+
+export const useEmbedToken = () => {
+ const searchParams = useSearchParams();
+
+ return searchParams.get("token");
+};