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 external program marketplace (#4053)

Pedro Ladeira977eab44d61e
diff --git a/apps/web/app/(ee)/api/marketplace/programs/counts/route.ts b/apps/web/app/(ee)/api/marketplace/programs/counts/route.ts
new file mode 100644
index 0000000000..91c59fc059
--- /dev/null
+++ b/apps/web/app/(ee)/api/marketplace/programs/counts/route.ts
@@ -0,0 +1,21 @@
+import { getNetworkProgramCounts } from "@/lib/fetchers/get-network-program-counts";
+import { parsePublicMarketplaceQuery } from "@/lib/marketplace/parse-public-marketplace-query";
+import { NextResponse } from "next/server";
+
+// cache filtered/searched count responses at the edge (public, not partner-scoped)
+export const revalidate = 3600;
+
+// GET /api/marketplace/programs/counts - public marketplace total + filter counts
+export async function GET(req: Request) {
+ const searchParams = Object.fromEntries(new URL(req.url).searchParams);
+ const { category, rewardType, search } =
+ parsePublicMarketplaceQuery(searchParams);
+
+ const counts = await getNetworkProgramCounts({
+ category,
+ rewardType,
+ search,
+ });
+
+ return NextResponse.json(counts);
+}
diff --git a/apps/web/app/(ee)/api/marketplace/programs/route.ts b/apps/web/app/(ee)/api/marketplace/programs/route.ts
new file mode 100644
index 0000000000..fb5361b927
--- /dev/null
+++ b/apps/web/app/(ee)/api/marketplace/programs/route.ts
@@ -0,0 +1,16 @@
+import { getPublicNetworkPrograms } from "@/lib/fetchers/get-public-network-programs";
+import { parsePublicMarketplaceQuery } from "@/lib/marketplace/parse-public-marketplace-query";
+import { NextResponse } from "next/server";
+
+// cache filtered/searched list responses at the edge (public, not partner-scoped)
+export const revalidate = 3600;
+
+// GET /api/marketplace/programs - public marketplace program list
+export async function GET(req: Request) {
+ const searchParams = Object.fromEntries(new URL(req.url).searchParams);
+ const params = parsePublicMarketplaceQuery(searchParams);
+
+ const programs = await getPublicNetworkPrograms(params);
+
+ return NextResponse.json(programs);
+}
diff --git a/apps/web/app/(ee)/api/network/programs/count/route.ts b/apps/web/app/(ee)/api/network/programs/count/route.ts
index 8c55c42c9e..1a98bd5a64 100644
--- a/apps/web/app/(ee)/api/network/programs/count/route.ts
+++ b/apps/web/app/(ee)/api/network/programs/count/route.ts
@@ -1,62 +1,23 @@
import { withPartnerProfile } from "@/lib/auth/partner";
+import { buildNetworkProgramCountWhereSql } from "@/lib/fetchers/get-network-program-counts";
import { prisma } from "@/lib/prisma";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import { getNetworkProgramsCountQuerySchema } from "@/lib/zod/schemas/program-network";
-import { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
-const rewardTypeMap = {
- sale: Prisma.sql`pg.saleRewardId IS NOT NULL`,
- lead: Prisma.sql`pg.leadRewardId IS NOT NULL`,
- click: Prisma.sql`pg.clickRewardId IS NOT NULL`,
- discount: Prisma.sql`pg.discountId IS NOT NULL`,
-};
-
// GET /api/network/programs/count - get the number of available programs in the network
export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
const { groupBy, category, rewardType, status, featured, search } =
getNetworkProgramsCountQuerySchema.parse(searchParams);
- const searchSql = search ? Prisma.sql`CONCAT('%', ${search}, '%')` : null;
- const commonWhereSql = Prisma.sql`
- p.addedToMarketplaceAt IS NOT NULL
- AND EXISTS (
- SELECT 1 FROM PartnerGroup pg
- WHERE
- pg.programId = p.id
- AND pg.slug = ${DEFAULT_PARTNER_GROUP.slug}
- AND pg.applicationFormPublishedAt IS NOT NULL
- ${
- rewardType && groupBy !== "rewardType"
- ? Prisma.sql`
- AND ${rewardTypeMap[rewardType]}`
- : Prisma.sql``
- }
- )
- ${
- category && groupBy !== "category"
- ? Prisma.sql`
- AND EXISTS (
- SELECT 1 FROM ProgramCategory pc
- WHERE pc.programId = p.id AND pc.category = ${category}
- )`
- : Prisma.sql``
- }
- ${
- status !== undefined && groupBy !== "status"
- ? Prisma.sql`
- AND ${status === null ? Prisma.sql`NOT` : Prisma.sql``} EXISTS (
- SELECT 1 FROM ProgramEnrollment pe
- WHERE
- pe.programId = p.id
- AND pe.partnerId = ${partner.id}
- ${status === null ? Prisma.sql`` : Prisma.sql`AND pe.status = ${status}`}
- )`
- : Prisma.sql``
- }
- ${featured !== undefined ? Prisma.sql`AND p.featuredOnMarketplaceAt IS ${featured ? Prisma.sql`NOT` : Prisma.sql``} NULL` : Prisma.sql``}
- ${searchSql ? Prisma.sql`AND (p.name LIKE ${searchSql} OR p.slug LIKE ${searchSql} OR p.domain LIKE ${searchSql})` : Prisma.sql``}
- `;
+ const commonWhereSql = buildNetworkProgramCountWhereSql({
+ category: groupBy === "category" ? undefined : category,
+ rewardType: groupBy === "rewardType" ? undefined : rewardType,
+ status: groupBy === "status" ? undefined : status,
+ partnerId: partner.id,
+ featured,
+ search,
+ });
if (groupBy === "category") {
const categories = (await prisma.$queryRaw`
@@ -97,7 +58,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
SELECT pe.status, COUNT(p.id) AS _count
FROM Program p
LEFT JOIN ProgramEnrollment pe ON p.id = pe.programId AND pe.partnerId = ${partner.id}
- WHERE p.addedToMarketplaceAt IS NOT NULL AND ${commonWhereSql}
+ WHERE ${commonWhereSql}
GROUP BY pe.status
ORDER BY _count DESC
`) as { status: string | null; _count: bigint }[];
diff --git a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/page.tsx b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/page.tsx
index 47657b0280..8e33725776 100644
--- a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/page.tsx
@@ -29,8 +29,14 @@ export default async function ApplicationPage(props: {
!program.group.applicationFormData ||
!program.group.applicationFormPublishedAt
) {
- // throw 404 if it's the default group, else redirect to the default group page
+ // for the default group:
+ // - if the program is found, redirect to the marketplace program page
+ // - otherwise, throw 404
+ // for other groups: redirect to the default group variant
if (partnerGroupSlug === DEFAULT_PARTNER_GROUP.slug) {
+ if (program) {
+ redirect(`/marketplace/${programSlug}`);
+ }
notFound();
} else {
redirect(`/${programSlug}/apply`);
diff --git a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/success/page.tsx b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/success/page.tsx
index 0c444317ec..4db7e547d9 100644
--- a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/success/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/apply/success/page.tsx
@@ -65,8 +65,14 @@ export default async function SuccessPage(props: {
!program.group.applicationFormData ||
!program.group.applicationFormPublishedAt
) {
- // throw 404 if it's the default group, else redirect to the default group page
+ // for the default group:
+ // - if the program is found, redirect to the marketplace program page
+ // - otherwise, throw 404
+ // for other groups: redirect to the default group variant
if (partnerGroupSlug === DEFAULT_PARTNER_GROUP.slug) {
+ if (program) {
+ redirect(`/marketplace/${programSlug}`);
+ }
notFound();
} else {
redirect(`/${programSlug}/apply`);
diff --git a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/page.tsx b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/page.tsx
index 0f0ef77054..bb084d4277 100644
--- a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/(default)/page.tsx
@@ -28,8 +28,14 @@ export default async function ApplyPage(props: {
!program.group.landerData ||
!program.group.landerPublishedAt
) {
- // throw 404 if it's the default group, else redirect to the default group page
+ // for the default group:
+ // - if the program is found, redirect to the marketplace program page
+ // - otherwise, throw 404
+ // for other groups: redirect to the default group variant
if (partnerGroupSlug === DEFAULT_PARTNER_GROUP.slug) {
+ if (program) {
+ redirect(`/marketplace/${programSlug}`);
+ }
notFound();
} else {
redirect(`/${programSlug}`);
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/marketplace/[[...segments]]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/marketplace/[[...segments]]/page.tsx
index fbdbd564eb..7d43179f19 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/marketplace/[[...segments]]/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/marketplace/[[...segments]]/page.tsx
@@ -1,14 +1,9 @@
import { MarketplaceRouter } from "@/ui/program-marketplace/marketplace-router";
-import {
- generateMarketplaceProgramStaticParams,
- revalidate,
-} from "@/ui/program-marketplace/pages/marketplace-program-page";
-
-export { revalidate };
-export async function generateStaticParams() {
- return generateMarketplaceProgramStaticParams();
-}
+export {
+ generateStaticParams,
+ revalidate,
+} from "@/ui/program-marketplace/utils/default-exports";
export default async function MarketplacePage(props: {
params: Promise<{ segments?: string[] }>;
diff --git a/apps/web/app/api/og/program/categories/route.tsx b/apps/web/app/api/og/program/categories/route.tsx
new file mode 100644
index 0000000000..4567056fc3
--- /dev/null
+++ b/apps/web/app/api/og/program/categories/route.tsx
@@ -0,0 +1,142 @@
+import { PROGRAM_CATEGORIES } from "@/lib/network/program-categories";
+import { DUB_WORDMARK } from "@dub/utils";
+import { ImageResponse } from "next/og";
+import { NextRequest } from "next/server";
+import { loadGoogleFont } from "../../load-google-font";
+
+const DARK_CELLS = [
+ [2, 3],
+ [5, 3],
+ [56, 7],
+ [53, 1],
+];
+
+// GET /api/og/program/categories?categorySlug=ai
+export async function GET(req: NextRequest) {
+ const categorySlug = req.nextUrl.searchParams.get("categorySlug");
+
+ if (!categorySlug) {
+ return new Response("Missing 'categorySlug' parameter", {
+ status: 400,
+ });
+ }
+
+ const category = PROGRAM_CATEGORIES.find(
+ ({ id }) => id.toLowerCase() === categorySlug.toLowerCase(),
+ );
+
+ if (!category) {
+ return new Response("Category not found", {
+ status: 404,
+ });
+ }
+
+ const interSemibold = await loadGoogleFont("Inter:wght@600");
+
+ return new ImageResponse(
+ (
+ <div
+ tw="flex flex-col bg-white w-full h-full"
+ style={{ fontFamily: "Inter" }}
+ >
+ {/* @ts-ignore */}
+ <svg tw="absolute inset-0 text-black/10" width="1200" height="630">
+ <defs>
+ <pattern
+ id="grid"
+ width={20}
+ height={20}
+ patternUnits="userSpaceOnUse"
+ >
+ <path
+ d={`M 20 0 L 0 0 0 20`}
+ fill="transparent"
+ stroke="currentColor"
+ strokeWidth={1}
+ />
+ </pattern>
+ <pattern
+ id="grid-large"
+ width={160}
+ height={160}
+ patternUnits="userSpaceOnUse"
+ >
+ <path
+ d={`M 160 0 L 0 0 0 160`}
+ fill="transparent"
+ stroke="currentColor"
+ strokeOpacity={0.5}
+ strokeWidth={1}
+ />
+ </pattern>
+ <linearGradient id="gradient" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor="#fff" stopOpacity={0} />
+ <stop offset="100%" stopColor="#fff" stopOpacity={1} />
+ </linearGradient>
+ </defs>
+ {DARK_CELLS.map(([x, y]) => (
+ <rect
+ key={`${x}-${y}`}
+ x={x * 20 + 1}
+ y={y * 20 + 1}
+ width={19}
+ height={19}
+ fill="black"
+ fillOpacity={0.02}
+ />
+ ))}
+ <rect fill="url(#grid)" width="1200" height="630" />
+ <rect fill="url(#grid-large)" width="1200" height="630" />
+ <rect fill="url(#gradient)" width="1200" height="630" />
+ </svg>
+
+ <div tw="relative flex flex-col mx-auto h-full bg-white w-[920px] px-16 py-20 overflow-hidden">
+ <div tw="flex items-center">
+ <img src={DUB_WORDMARK} height={56} />
+ <div tw="ml-4 h-10 w-px bg-neutral-300" />
+ <div tw="ml-4 text-left uppercase text-2xl text-neutral-500">
+ Program Marketplace
+ </div>
+ </div>
+ <div
+ tw="mt-32 text-5xl font-semibold text-neutral-800"
+ style={{
+ display: "block",
+ lineClamp: 2,
+ textOverflow: "ellipsis",
+ fontFamily: "Inter",
+ }}
+ >
+ {`${category.label} Affiliate Programs`}
+ </div>
+ <div tw="mt-10 flex">
+ <div
+ tw="w-full flex items-center rounded-md bg-neutral-100 border border-neutral-200 p-10 text-3xl"
+ style={{
+ display: "block",
+ lineClamp: 3,
+ textOverflow: "ellipsis",
+ }}
+ >
+ {category.listPageDescription}
+ </div>
+ </div>
+ </div>
+ </div>
+ ),
+ {
+ width: 1200,
+ height: 630,
+ fonts: interSemibold
+ ? [
+ {
+ name: "Inter",
+ data: interSemibold,
+ style: "normal",
+ weight: 600,
+ },
+ ]
+ : [],
+ },
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/layout.tsx
index 588a3e39d3..a904729284 100644
--- a/apps/web/app/app.dub.co/(dashboard)/layout.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/layout.tsx
@@ -5,6 +5,7 @@ import { NewsRSC } from "@/ui/layout/sidebar/news-rsc";
import { ReferButton } from "@/ui/layout/sidebar/refer-button";
import Toolbar from "@/ui/layout/toolbar/toolbar";
import { UpgradeBanner } from "@/ui/layout/upgrade-banner";
+import { ModalProvider } from "@/ui/modals/modal-provider";
import { constructMetadata } from "@dub/utils";
import { ReactNode } from "react";
@@ -13,7 +14,7 @@ export const metadata = constructMetadata();
export default async function Layout({ children }: { children: ReactNode }) {
return (
- <>
+ <ModalProvider>
<div className="min-h-screen w-full bg-white">
<UpgradeBanner />
<MainNav
@@ -30,6 +31,6 @@ export default async function Layout({ children }: { children: ReactNode }) {
</MainNav>
</div>
<Toolbar show={["onboarding"]} />
- </>
+ </ModalProvider>
);
}
diff --git a/apps/web/app/app.dub.co/layout.tsx b/apps/web/app/app.dub.co/layout.tsx
index c9900f4fa0..80208e877f 100644
--- a/apps/web/app/app.dub.co/layout.tsx
+++ b/apps/web/app/app.dub.co/layout.tsx
@@ -1,9 +1,8 @@
"use client";
-import { ModalProvider } from "@/ui/modals/modal-provider";
import { Analytics as DubAnalytics } from "@dub/analytics/react";
import { SessionProvider } from "next-auth/react";
-import { ReactNode } from "react";
+import { ReactNode, Suspense } from "react";
export default function AppLayout({ children }: { children: ReactNode }) {
return (
@@ -17,7 +16,7 @@ export default function AppLayout({ children }: { children: ReactNode }) {
refer: "refer.dub.co",
}}
/>
- <ModalProvider>{children}</ModalProvider>
+ <Suspense>{children}</Suspense>
</SessionProvider>
);
}
diff --git a/apps/web/app/app.dub.co/marketplace/[[...segments]]/page.tsx b/apps/web/app/app.dub.co/marketplace/[[...segments]]/page.tsx
new file mode 100644
index 0000000000..9067610d7e
--- /dev/null
+++ b/apps/web/app/app.dub.co/marketplace/[[...segments]]/page.tsx
@@ -0,0 +1,74 @@
+import { getNetworkProgram } from "@/lib/fetchers/get-network-program";
+import { PROGRAM_CATEGORIES_MAP } from "@/lib/network/program-categories";
+import { MarketplaceExternalRouter } from "@/ui/program-marketplace/external/marketplace-external-router";
+import { APP_DOMAIN, constructMetadata } from "@dub/utils";
+import { Category } from "@prisma/client";
+import { Metadata } from "next";
+
+export {
+ generateStaticParams,
+ revalidate,
+} from "@/ui/program-marketplace/utils/default-exports";
+
+export async function generateMetadata(props: {
+ params: Promise<{ segments?: string[] }>;
+}): Promise<Metadata> {
+ const { segments = [] } = await props.params;
+ const pathname = `/marketplace${segments.length > 0 ? `/${segments.join("/")}` : ""}`;
+
+ const currentYear = new Date().getFullYear();
+
+ let title = `Best SaaS affiliate programs in ${currentYear}`;
+ let description = `Browse and apply to the best SaaS affiliate programs on Dub's Partner Network.`;
+ let image = "https://assets.dub.co/og/marketplace.jpg";
+
+ if (segments.length === 1 && segments[0] === "all") {
+ title = `Top SaaS affiliate programs in ${currentYear}`;
+ } else if (
+ segments.length === 1 &&
+ segments[0] !== "all" &&
+ segments[0] !== "popular"
+ ) {
+ const program = await getNetworkProgram({ slug: segments[0] });
+
+ if (program) {
+ title = program.name;
+ description =
+ program.description ||
+ `Join the ${program.name} affiliate program on Dub's Program Marketplace.`;
+ image =
+ program.marketplaceHeaderImage ||
+ `${APP_DOMAIN}/api/og/program?slug=${program.slug}`;
+ }
+ } else if (segments.length === 2 && segments[0] === "c") {
+ const category = Object.values(Category).find(
+ (value) => value.toLowerCase() === segments[1],
+ );
+
+ if (category) {
+ // categoryMeta should always return a value, but just in case
+ const categoryMeta = PROGRAM_CATEGORIES_MAP[category];
+ const label = categoryMeta?.label ?? category.replaceAll("_", " ");
+ title = `Best ${label} Affiliate Programs in ${currentYear}`;
+ description =
+ categoryMeta?.listPageDescription ??
+ `Browse the best ${label} affiliate programs on Dub's Program Marketplace.`;
+ image = `${APP_DOMAIN}/api/og/program/categories?categorySlug=${category.toLowerCase()}`;
+ }
+ }
+
+ return constructMetadata({
+ title,
+ description,
+ image,
+ canonicalUrl: `https://dub.co${pathname.startsWith("/") ? pathname : `/${pathname}`}`,
+ });
+}
+
+export default async function MarketplaceExternalPage(props: {
+ params: Promise<{ segments?: string[] }>;
+}) {
+ const { segments = [] } = await props.params;
+
+ return <MarketplaceExternalRouter segments={segments} />;
+}
diff --git a/apps/web/app/app.dub.co/marketplace/layout.tsx b/apps/web/app/app.dub.co/marketplace/layout.tsx
new file mode 100644
index 0000000000..1a1f6c4f13
--- /dev/null
+++ b/apps/web/app/app.dub.co/marketplace/layout.tsx
@@ -0,0 +1,33 @@
+import { MarketplaceExternalHeader } from "@/ui/program-marketplace/external/marketplace-external-header";
+import { Footer } from "@dub/ui";
+import { PropsWithChildren } from "react";
+
+export default function MarketplaceExternalLayout({
+ children,
+}: PropsWithChildren) {
+ return (
+ <div className="flex min-h-screen flex-col bg-white">
+ <MarketplaceExternalHeader />
+ <div className="relative flex flex-1 flex-col">
+ <MarketplaceExternalGridLines />
+ <main className="flex-1">{children}</main>
+ <div className="relative z-10 h-px w-full bg-neutral-200" />
+ <Footer className="border-t-0 md:rounded-t-none" />
+ </div>
+ </div>
+ );
+}
+
+function MarketplaceExternalGridLines() {
+ return (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-0 z-0 flex justify-center"
+ >
+ <div className="relative h-full w-full max-w-screen-xl">
+ <div className="absolute inset-y-0 left-0 w-px bg-neutral-200 [mask-image:linear-gradient(to_bottom,transparent,#000_96px)]" />
+ <div className="absolute inset-y-0 right-0 w-px bg-neutral-200 [mask-image:linear-gradient(to_bottom,transparent,#000_96px)]" />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/sitemap.ts b/apps/web/app/sitemap.ts
index 29dd44013d..0871ace4bf 100644
--- a/apps/web/app/sitemap.ts
+++ b/apps/web/app/sitemap.ts
@@ -1,6 +1,10 @@
import { prisma } from "@/lib/prisma";
-import { PARTNERS_HOSTNAMES, SHORT_DOMAIN } from "@dub/utils";
-import { Prisma } from "@prisma/client";
+import {
+ getMarketplaceAllHref,
+ getMarketplaceCategoryHref,
+} from "@/ui/program-marketplace/utils/urls";
+import { isAppHostname, PARTNERS_HOSTNAMES, SHORT_DOMAIN } from "@dub/utils";
+import { Category, Prisma } from "@prisma/client";
import { MetadataRoute } from "next";
import { headers } from "next/headers";
@@ -8,7 +12,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const headersList = await headers();
let domain = headersList.get("host") as string;
- if (domain === "dub.localhost:8888" || domain.endsWith(".vercel.app")) {
+ if (domain === "dub.localhost:8888") {
// for local development and preview URLs
domain = SHORT_DOMAIN;
}
@@ -39,10 +43,48 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
}));
}
- return [
+ const entries: MetadataRoute.Sitemap = [
{
url: `https://${domain}`,
lastModified: new Date(),
},
];
+
+ if (isAppHostname(domain)) {
+ const marketplacePrograms = await prisma.program.findMany({
+ where: {
+ addedToMarketplaceAt: {
+ not: null,
+ },
+ },
+ select: {
+ slug: true,
+ updatedAt: true,
+ },
+ orderBy: {
+ slug: "asc",
+ },
+ });
+
+ entries.push(
+ {
+ url: "https://dub.co/marketplace",
+ lastModified: new Date(),
+ },
+ {
+ url: `https://dub.co${getMarketplaceAllHref()}`,
+ lastModified: new Date(),
+ },
+ ...Object.values(Category).map((category) => ({
+ url: `https://dub.co${getMarketplaceCategoryHref(category)}`,
+ lastModified: new Date(),
+ })),
+ ...marketplacePrograms.map((program) => ({
+ url: `https://dub.co/marketplace/${program.slug}`,
+ lastModified: program.updatedAt,
+ })),
+ );
+ }
+
+ return entries;
}
diff --git a/apps/web/lib/fetchers/get-network-program-counts.ts b/apps/web/lib/fetchers/get-network-program-counts.ts
new file mode 100644
index 0000000000..9a4cdd0712
--- /dev/null
+++ b/apps/web/lib/fetchers/get-network-program-counts.ts
@@ -0,0 +1,176 @@
+import { prisma } from "@/lib/prisma";
+import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
+import { getPublicNetworkProgramsQuerySchema } from "@/lib/zod/schemas/program-network";
+import { Category, Prisma, ProgramEnrollmentStatus } from "@prisma/client";
+import { cache } from "react";
+import * as z from "zod/v4";
+
+type RewardType = NonNullable<
+ z.infer<typeof getPublicNetworkProgramsQuerySchema>["rewardType"]
+>;
+
+const rewardTypeMap: Record<RewardType, Prisma.Sql> = {
+ sale: Prisma.sql`pg.saleRewardId IS NOT NULL`,
+ lead: Prisma.sql`pg.leadRewardId IS NOT NULL`,
+ click: Prisma.sql`pg.clickRewardId IS NOT NULL`,
+ discount: Prisma.sql`pg.discountId IS NOT NULL`,
+};
+
+type NetworkProgramWhereParams = {
+ category?: Category;
+ rewardType?: RewardType;
+ search?: string;
+ // partner-scoped (network) filters only
+ status?: ProgramEnrollmentStatus | null;
+ partnerId?: string;
+ featured?: boolean;
+};
+
+export function buildNetworkProgramCountWhereSql({
+ category,
+ rewardType,
+ search,
+ status,
+ partnerId,
+ featured,
+}: NetworkProgramWhereParams) {
+ const searchSql = search ? Prisma.sql`CONCAT('%', ${search}, '%')` : null;
+
+ return Prisma.sql`
+ p.addedToMarketplaceAt IS NOT NULL
+ AND EXISTS (
+ SELECT 1 FROM PartnerGroup pg
+ WHERE
+ pg.programId = p.id
+ AND pg.slug = ${DEFAULT_PARTNER_GROUP.slug}
+ AND pg.applicationFormPublishedAt IS NOT NULL
+ ${rewardType ? Prisma.sql`AND ${rewardTypeMap[rewardType]}` : Prisma.sql``}
+ )
+ ${
+ category
+ ? Prisma.sql`
+ AND EXISTS (
+ SELECT 1 FROM ProgramCategory pc
+ WHERE pc.programId = p.id AND pc.category = ${category}
+ )`
+ : Prisma.sql``
+ }
+ ${
+ status !== undefined && partnerId
+ ? Prisma.sql`
+ AND ${status === null ? Prisma.sql`NOT` : Prisma.sql``} EXISTS (
+ SELECT 1 FROM ProgramEnrollment pe
+ WHERE
+ pe.programId = p.id
+ AND pe.partnerId = ${partnerId}
+ ${status === null ? Prisma.sql`` : Prisma.sql`AND pe.status = ${status}`}
+ )`
+ : Prisma.sql``
+ }
+ ${
+ featured !== undefined
+ ? Prisma.sql`AND p.featuredOnMarketplaceAt IS ${featured ? Prisma.sql`NOT` : Prisma.sql``} NULL`
+ : Prisma.sql``
+ }
+ ${
+ searchSql
+ ? Prisma.sql`AND (p.name LIKE ${searchSql} OR p.slug LIKE ${searchSql} OR p.domain LIKE ${searchSql} OR p.url LIKE ${searchSql} OR p.description LIKE ${searchSql})`
+ : Prisma.sql``
+ }
+ `;
+}
+
+export async function getNetworkProgramTotalCount(
+ params: NetworkProgramWhereParams = {},
+) {
+ const whereSql = buildNetworkProgramCountWhereSql(params);
+
+ const result = (await prisma.$queryRaw`
+ SELECT COUNT(*) AS count FROM Program p
+ WHERE ${whereSql}
+ `) as { count: bigint }[];
+
+ return Number(result[0].count);
+}
+
+export async function getNetworkProgramCategoryCounts(
+ params: NetworkProgramWhereParams = {},
+) {
+ // category counts ignore the active category filter
+ const whereSql = buildNetworkProgramCountWhereSql({
+ ...params,
+ category: undefined,
+ });
+
+ const categories = (await prisma.$queryRaw`
+ SELECT pc.category, COUNT(p.id) AS _count
+ FROM ProgramCategory pc
+ JOIN Program p ON p.id = pc.programId
+ WHERE ${whereSql}
+ GROUP BY pc.category
+ ORDER BY _count DESC
+ `) as { category: Category; _count: bigint }[];
+
+ return categories.map(({ category, _count }) => ({
+ category,
+ count: Number(_count),
+ }));
+}
+
+export async function getNetworkProgramRewardTypeCounts(
+ params: NetworkProgramWhereParams = {},
+) {
+ // reward type counts ignore the active reward type filter
+ const whereSql = buildNetworkProgramCountWhereSql({
+ ...params,
+ rewardType: undefined,
+ });
+
+ const rewards = (await prisma.$queryRaw`
+ SELECT
+ COUNT(pg.clickRewardId) AS "click",
+ COUNT(pg.leadRewardId) AS "lead",
+ COUNT(pg.saleRewardId) AS "sale",
+ COUNT(pg.discountId) AS "discount"
+ FROM PartnerGroup pg
+ JOIN Program p ON p.id = pg.programId
+ WHERE pg.slug = ${DEFAULT_PARTNER_GROUP.slug} AND ${whereSql}
+ `) as { click: bigint; lead: bigint; sale: bigint; discount: bigint }[];
+
+ return (["sale", "lead", "click", "discount"] as const).map((type) => ({
+ type,
+ count: Number(rewards[0][type]),
+ }));
+}
+
+/**
+ * Public marketplace counts: total program count + per-category and
+ * per-reward-type filter counts in a single call. Wrapped in React `cache()`
+ * so it dedupes when invoked multiple times within one server render.
+ */
+export const getNetworkProgramCounts = cache(
+ async ({
+ category,
+ rewardType,
+ search,
+ }: Pick<
+ NetworkProgramWhereParams,
+ "category" | "rewardType" | "search"
+ > = {}) => {
+ const [total, categories, rewardTypes] = await Promise.all([
+ getNetworkProgramTotalCount({ category, rewardType, search }),
+ getNetworkProgramCategoryCounts({ rewardType, search }),
+ getNetworkProgramRewardTypeCounts({ category, search }),
+ ]);
+
+ return {
+ total,
+ categories,
+ rewardTypes,
+ };
+ },
+);
+
+export type NetworkProgramCounts = Awaited<
+ ReturnType<typeof getNetworkProgramCounts>
+>;
diff --git a/apps/web/lib/fetchers/get-public-network-programs.ts b/apps/web/lib/fetchers/get-public-network-programs.ts
new file mode 100644
index 0000000000..1f060a5228
--- /dev/null
+++ b/apps/web/lib/fetchers/get-public-network-programs.ts
@@ -0,0 +1,114 @@
+import { prisma } from "@/lib/prisma";
+import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
+import {
+ getPublicNetworkProgramsQuerySchema,
+ NetworkProgramSchema,
+ PROGRAM_NETWORK_MAX_PAGE_SIZE,
+} from "@/lib/zod/schemas/program-network";
+import { cache } from "react";
+import * as z from "zod/v4";
+
+export const getPublicNetworkPrograms = cache(
+ async (
+ params: Partial<z.infer<typeof getPublicNetworkProgramsQuerySchema>> = {},
+ ) => {
+ const {
+ category,
+ rewardType,
+ featured,
+ search,
+ sortBy = "popularity",
+ sortOrder = "desc",
+ page = 1,
+ pageSize = PROGRAM_NETWORK_MAX_PAGE_SIZE,
+ } = params;
+
+ const programs = await prisma.program.findMany({
+ where: {
+ addedToMarketplaceAt: {
+ not: null,
+ },
+ ...(featured && {
+ featuredOnMarketplaceAt: {
+ not: null,
+ },
+ }),
+ ...(search && {
+ OR: [
+ { name: { contains: search } },
+ { slug: { contains: search } },
+ { domain: { contains: search } },
+ { url: { contains: search } },
+ { description: { contains: search } },
+ ],
+ }),
+ ...(category && {
+ categories: {
+ some: {
+ category,
+ },
+ },
+ }),
+ ...(rewardType && {
+ groups: {
+ some: {
+ slug: DEFAULT_PARTNER_GROUP.slug,
+ ...(rewardType === "sale" && {
+ saleRewardId: { not: null },
+ }),
+ ...(rewardType === "lead" && {
+ leadRewardId: { not: null },
+ }),
+ ...(rewardType === "click" && {
+ clickRewardId: { not: null },
+ }),
+ ...(rewardType === "discount" && {
+ discountId: { not: null },
+ }),
+ },
+ },
+ }),
+ },
+ include: {
+ groups: {
+ where: {
+ slug: DEFAULT_PARTNER_GROUP.slug,
+ },
+ include: {
+ clickReward: true,
+ leadReward: true,
+ saleReward: true,
+ referralReward: true,
+ discount: true,
+ },
+ },
+ categories: true,
+ },
+ orderBy:
+ sortBy === "popularity"
+ ? { marketplaceRanking: "asc" }
+ : {
+ [sortBy === "recency" ? "addedToMarketplaceAt" : sortBy]:
+ sortOrder,
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ });
+
+ return z.array(NetworkProgramSchema).parse(
+ programs.map((program) => ({
+ ...program,
+ rewards:
+ program.groups.length > 0
+ ? [
+ program.groups[0].clickReward,
+ program.groups[0].leadReward,
+ program.groups[0].saleReward,
+ ].filter(Boolean)
+ : [],
+ discount: program.groups.length > 0 ? program.groups[0].discount : null,
+ categories: program.categories.map(({ category }) => category),
+ })),
+ );
+ },
+);
diff --git a/apps/web/lib/marketplace/parse-public-marketplace-query.ts b/apps/web/lib/marketplace/parse-public-marketplace-query.ts
new file mode 100644
index 0000000000..334993e4f2
--- /dev/null
+++ b/apps/web/lib/marketplace/parse-public-marketplace-query.ts
@@ -0,0 +1,34 @@
+import { getPublicNetworkProgramsQuerySchema } from "@/lib/zod/schemas/program-network";
+import { Category } from "@prisma/client";
+
+export const EXTERNAL_MARKETPLACE_PAGE_SIZE = 24;
+
+function pickString(value: string | string[] | undefined) {
+ return typeof value === "string" ? value : undefined;
+}
+
+export function parsePublicMarketplaceQuery(
+ searchParams: Record<string, string | string[] | undefined> = {},
+ fixedCategory?: Category,
+) {
+ const input = {
+ category: fixedCategory ?? pickString(searchParams.category),
+ rewardType: pickString(searchParams.rewardType),
+ search: pickString(searchParams.search),
+ sortBy: pickString(searchParams.sortBy),
+ sortOrder: pickString(searchParams.sortOrder),
+ page: pickString(searchParams.page),
+ pageSize: EXTERNAL_MARKETPLACE_PAGE_SIZE,
+ };
+
+ const parsed = getPublicNetworkProgramsQuerySchema.safeParse(input);
+
+ if (parsed.success) {
+ return parsed.data;
+ }
+
+ return getPublicNetworkProgramsQuerySchema.parse({
+ pageSize: EXTERNAL_MARKETPLACE_PAGE_SIZE,
+ ...(fixedCategory ? { category: fixedCategory } : {}),
+ });
+}
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index 27ec856707..634e0c0b85 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -13,6 +13,16 @@ import { isTopLevelSettingsRedirect } from "./utils/is-top-level-settings-redire
import { parse } from "./utils/parse";
import { WorkspacesMiddleware } from "./workspaces";
+const isPublicPath = (path: string) =>
+ ["/marketplace"].some((p) => path === p) ||
+ [
+ "/marketplace/",
+ "/share/",
+ "/deeplink/",
+ "/unsubscribe/",
+ "/auth/reset-password/",
+ ].some((p) => path.startsWith(p));
+
export async function AppMiddleware(req: NextRequest) {
const { path, fullPath, searchParamsString } = parse(req);
@@ -29,10 +39,7 @@ export async function AppMiddleware(req: NextRequest) {
path !== "/forgot-password" &&
path !== "/register" &&
path !== "/auth/saml" &&
- !path.startsWith("/auth/reset-password/") &&
- !path.startsWith("/share/") &&
- !path.startsWith("/deeplink/") &&
- !path.startsWith("/unsubscribe/")
+ !isPublicPath(path)
) {
return NextResponse.redirect(
new URL(
@@ -42,7 +49,7 @@ export async function AppMiddleware(req: NextRequest) {
);
// if there's a user
- } else if (user) {
+ } else if (user && !isPublicPath(path)) {
// /new is a special path that creates a new link (or workspace if the user doesn't have one yet)
if (path === "/new") {
return NewLinkMiddleware(req, user);
diff --git a/apps/web/lib/middleware/utils/app-redirect.ts b/apps/web/lib/middleware/utils/app-redirect.ts
index 234d8e3248..e3cc1f0376 100644
--- a/apps/web/lib/middleware/utils/app-redirect.ts
+++ b/apps/web/lib/middleware/utils/app-redirect.ts
@@ -7,7 +7,6 @@ const APP_REDIRECTS = {
"/welcome": "/onboarding/welcome",
"/campaigns": "/program/campaigns",
"/messages": "/program/messages",
- "/marketplace": "/program/network",
"/fraud": "/program/risks",
"/risks": "/program/risks",
};
diff --git a/apps/web/lib/network/program-categories.ts b/apps/web/lib/network/program-categories.ts
index 9640a15245..fbcd110359 100644
--- a/apps/web/lib/network/program-categories.ts
+++ b/apps/web/lib/network/program-categories.ts
@@ -9,6 +9,7 @@ import {
Icon,
MarketingTarget,
MoneyBill,
+ ShieldKeyhole,
Sparkle3,
User,
} from "@dub/ui/icons";
@@ -25,84 +26,84 @@ export const PROGRAM_CATEGORIES: {
label: "AI",
icon: Sparkle3,
listPageDescription:
- "Browse partner programs for AI tools and machine learning platforms.",
+ "Browse the best affiliate programs for AI tools, agents, and chatbots.",
},
{
id: Category.Development,
- label: "Development",
+ label: "DevTools",
icon: Code,
listPageDescription:
- "Browse partner programs for developer tools and software infrastructure.",
+ "Browse the best affiliate programs for developer tools, APIs, and no-code platforms.",
},
{
id: Category.Design,
label: "Design",
icon: Brush,
listPageDescription:
- "Browse partner programs for design tools and creative software.",
+ "Browse the best affiliate programs for graphic design tools and creative software.",
},
{
id: Category.Productivity,
label: "Productivity",
icon: CircleHalfDottedClock,
listPageDescription:
- "Browse partner programs for productivity software and modern work tools.",
+ "Browse the best affiliate programs for productivity apps, email tools, and collaboration software.",
},
{
id: Category.Finance,
- label: "Finance",
+ label: "FinTech",
icon: MoneyBill,
listPageDescription:
- "Browse partner programs for finance software and fintech platforms.",
+ "Browse the best affiliate programs for trading, crypto, and finance apps.",
},
{
id: Category.Marketing,
label: "Marketing",
icon: MarketingTarget,
listPageDescription:
- "Browse partner programs for marketing software and growth tools.",
+ "Browse the best affiliate programs for marketing software, email marketing, and SEO tools.",
},
{
id: Category.Ecommerce,
label: "Ecommerce",
icon: CreditCard,
listPageDescription:
- "Browse partner programs for ecommerce platforms and online retail tools.",
+ "Browse the best affiliate programs for online stores, newsletters, and ecommerce platforms.",
+ },
+ {
+ id: Category.Security,
+ label: "Security",
+ icon: ShieldKeyhole,
+ listPageDescription:
+ "Browse the best affiliate programs for cybersecurity software and privacy tools.",
},
- // {
- // id: Category.Security,
- // label: "Security",
- // icon: ShieldKeyhole,
- // listPageDescription:
- // "Browse partner programs for security software and privacy tools.",
- // },
{
id: Category.Education,
label: "Education",
icon: BookOpen,
listPageDescription:
- "Browse partner programs for education platforms and learning tools.",
+ "Browse the best affiliate programs for edtech, learning tools, and education software.",
},
{
id: Category.Health,
- label: "Health",
+ label: "Healthcare",
icon: Heart,
listPageDescription:
- "Browse partner programs for health software and wellness tools.",
+ "Browse the best affiliate programs for healthtech, wellness apps, and health software.",
},
{
id: Category.Consumer,
label: "Consumer",
icon: User,
listPageDescription:
- "Browse partner programs for consumer apps and lifestyle products.",
+ "Browse the best affiliate programs for consumer apps and lifestyle software.",
},
{
id: Category.Support,
label: "Support",
icon: Headset,
listPageDescription:
- "Browse partner programs for customer support and help desk tools.",
+ "Browse the best affiliate programs for customer support software and agentic tools.",
},
];
diff --git a/apps/web/lib/swr/use-workspace.ts b/apps/web/lib/swr/use-workspace.ts
index bdc652b822..c404e59e88 100644
--- a/apps/web/lib/swr/use-workspace.ts
+++ b/apps/web/lib/swr/use-workspace.ts
@@ -10,8 +10,13 @@ export default function useWorkspace({
}: {
swrOpts?: SWRConfiguration;
} = {}) {
- let { slug } = useParams() as { slug: string | null };
+ let { slug } = useParams() as { slug: string | string[] | null };
const searchParams = useSearchParams();
+ // catch-all routes (e.g. /marketplace/[[...slug]]) surface `slug` as an array,
+ // which is never a workspace slug - ignore it so we don't fetch /api/workspaces/<segment>
+ if (Array.isArray(slug)) {
+ slug = null;
+ }
if (!slug) {
slug = searchParams.get("slug") || searchParams.get("workspace");
}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-apply-button.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-apply-button.tsx
new file mode 100644
index 0000000000..e89c0941be
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-apply-button.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import { Button } from "@dub/ui";
+import { PARTNERS_DOMAIN } from "@dub/utils";
+import { useSession } from "next-auth/react";
+
+export function MarketplaceExternalApplyButton({
+ programSlug,
+}: {
+ programSlug: string;
+}) {
+ const { data: session } = useSession();
+ return (
+ <a
+ href={
+ session
+ ? `${PARTNERS_DOMAIN}/marketplace/${programSlug}`
+ : `${PARTNERS_DOMAIN}/${programSlug}/apply`
+ }
+ target="_blank"
+ className="inline-block w-fit"
+ >
+ <Button
+ text="Apply"
+ className="h-10 w-fit rounded-lg px-6 text-sm font-medium"
+ />
+ </a>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-filters.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-filters.tsx
new file mode 100644
index 0000000000..5d474d4f4f
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-filters.tsx
@@ -0,0 +1,181 @@
+import { PROGRAM_CATEGORIES_MAP } from "@/lib/network/program-categories";
+import {
+ MARKETPLACE_REWARD_TYPES,
+ type MarketplaceRewardType,
+} from "@/ui/program-marketplace/utils/constants";
+import { buildExternalMarketplaceFilterHref } from "@/ui/program-marketplace/utils/urls";
+import { Check } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Category } from "@prisma/client";
+import Link from "next/link";
+import type { ReactNode } from "react";
+
+export function MarketplaceExternalFilterSidebar({
+ basePath,
+ activeCategory,
+ activeRewardType,
+ categoryCounts,
+ rewardTypeCounts,
+ search,
+ sortBy,
+ sortOrder,
+}: {
+ basePath: string;
+ activeCategory?: Category;
+ activeRewardType?: MarketplaceRewardType;
+ categoryCounts: { category: Category; count: number }[];
+ rewardTypeCounts: {
+ type: MarketplaceRewardType;
+ count: number;
+ }[];
+ search?: string;
+ sortBy?: string;
+ sortOrder?: string;
+}) {
+ const buildHref = (params: {
+ category?: Category | null;
+ rewardType?: MarketplaceRewardType | null;
+ }) =>
+ buildExternalMarketplaceFilterHref({
+ basePath,
+ activeRewardType,
+ search,
+ sortBy,
+ sortOrder,
+ ...params,
+ });
+
+ return (
+ <aside className="w-full shrink-0 lg:w-56">
+ <div className="flex flex-col gap-6">
+ <FilterSection title="Reward type">
+ {rewardTypeCounts.map(({ type, count }) => (
+ <FilterLink
+ key={type}
+ href={buildHref({
+ rewardType: activeRewardType === type ? null : type,
+ })}
+ active={activeRewardType === type}
+ count={count}
+ >
+ {MARKETPLACE_REWARD_TYPES[type]}
+ </FilterLink>
+ ))}
+ </FilterSection>
+
+ <FilterSection title="Category">
+ {categoryCounts.map(({ category, count }) => (
+ <FilterLink
+ key={category}
+ href={buildHref({
+ category: activeCategory === category ? null : category,
+ })}
+ active={activeCategory === category}
+ count={count}
+ >
+ {PROGRAM_CATEGORIES_MAP[category]?.label ??
+ category.replaceAll("_", " ")}
+ </FilterLink>
+ ))}
+ </FilterSection>
+ </div>
+ </aside>
+ );
+}
+
+export function MarketplaceExternalFilterSidebarSkeleton() {
+ return (
+ <aside className="w-full shrink-0 lg:w-56">
+ <div className="flex flex-col gap-6">
+ {[4, 6].map((rows, sectionIndex) => (
+ <div key={sectionIndex} className="flex flex-col gap-1">
+ <div className="px-2 py-2">
+ <div className="h-4 w-20 animate-pulse rounded bg-neutral-200" />
+ </div>
+ <div className="flex flex-col gap-1">
+ {[...Array(rows)].map((_, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-3 px-2 py-2"
+ aria-hidden
+ >
+ <div className="size-4 shrink-0 animate-pulse rounded border border-neutral-200 bg-neutral-200" />
+ <div className="h-3 flex-1 animate-pulse rounded bg-neutral-200" />
+ <div className="h-3 w-4 shrink-0 animate-pulse rounded bg-neutral-200" />
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ </aside>
+ );
+}
+
+function FilterSection({
+ title,
+ children,
+}: {
+ title: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-content-emphasis px-2 py-2 text-sm font-semibold">
+ {title}
+ </span>
+ <div className="flex flex-col gap-1">{children}</div>
+ </div>
+ );
+}
+
+function FilterLink({
+ href,
+ active,
+ count,
+ children,
+}: {
+ href: string;
+ active: boolean;
+ count: number;
+ children: ReactNode;
+}) {
+ return (
+ <Link
+ href={href}
+ className={cn(
+ "flex items-center gap-3 rounded-md px-2 py-2 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-100",
+ active && "bg-neutral-100",
+ )}
+ >
+ <div
+ className={cn(
+ "flex h-4 w-4 shrink-0 items-center justify-center rounded border",
+ active ? "border-neutral-900 bg-neutral-900" : "border-neutral-300",
+ )}
+ >
+ {active ? <Check className="h-3 w-3 text-white" /> : null}
+ </div>
+ <span className="min-w-0 flex-1 truncate">{children}</span>
+ <span className="shrink-0 text-xs tabular-nums text-neutral-400">
+ {count}
+ </span>
+ </Link>
+ );
+}
+
+export function getMarketplaceExternalBasePath({
+ segments,
+}: {
+ segments: string[];
+}) {
+ if (segments.length === 1 && segments[0] === "all") {
+ return "/marketplace/all";
+ }
+
+ if (segments.length === 2 && segments[0] === "c") {
+ return `/marketplace/c/${segments[1]}`;
+ }
+
+ return "/marketplace/all";
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-header.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-header.tsx
new file mode 100644
index 0000000000..c76538ece2
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-header.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { NavMobile, Nav as NavUI, Shop, Wordmark } from "@dub/ui";
+import Link from "next/link";
+
+const DUB_HOME_HREF = "https://dub.co/home";
+
+function MarketplaceLogo() {
+ return (
+ <div className="flex items-center gap-2.5">
+ <Link
+ href={DUB_HOME_HREF}
+ className="transition-opacity hover:opacity-80"
+ >
+ <Wordmark className="h-6" />
+ </Link>
+ <span className="text-lg font-light text-neutral-300">|</span>
+ <Link
+ href="/marketplace"
+ className="flex items-center gap-2 text-sm font-medium text-neutral-500 transition-opacity hover:opacity-80"
+ >
+ <Shop className="size-3.5" /> Program Marketplace
+ </Link>
+ </div>
+ );
+}
+
+export function MarketplaceExternalHeader() {
+ return (
+ <>
+ <NavMobile navItems={[]} />
+ <NavUI staticDomain="dub.co" navItems={[]} logo={<MarketplaceLogo />} />
+ </>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-home-page.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-home-page.tsx
new file mode 100644
index 0000000000..996de2e57e
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-home-page.tsx
@@ -0,0 +1,34 @@
+import { getMarketplaceProgramsSummary } from "@/lib/fetchers/get-marketplace-programs-summary";
+import { FeaturedPrograms } from "../featured-programs";
+import { MARKETPLACE_HOME_ROWS } from "../home-sections";
+import { MarketplaceCategoriesSection } from "../marketplace-categories-section";
+import { MarketplaceProgramRow } from "../marketplace-program-row";
+import { MarketplaceExternalShell } from "./marketplace-external-shell";
+
+export async function MarketplaceExternalHomePage() {
+ const summary = await getMarketplaceProgramsSummary();
+
+ return (
+ <MarketplaceExternalShell variant="home">
+ <div className="flex flex-col gap-10">
+ <div className="-mx-4 -mt-8 px-2 sm:-mx-6 lg:-mx-8">
+ <FeaturedPrograms
+ programs={summary.featuredPrograms}
+ showStatus={false}
+ />
+ </div>
+ <MarketplaceCategoriesSection />
+ {MARKETPLACE_HOME_ROWS.map((row, index) => (
+ <MarketplaceProgramRow
+ key={row.key}
+ title={row.title}
+ viewAllHref={row.viewAllHref}
+ showViewAllCard={row.showViewAllCard}
+ showStatus={false}
+ programs={summary.categories[row.key] ?? summary[row.key]}
+ />
+ ))}
+ </div>
+ </MarketplaceExternalShell>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-list-page-client.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-list-page-client.tsx
new file mode 100644
index 0000000000..401736adbf
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-list-page-client.tsx
@@ -0,0 +1,288 @@
+"use client";
+
+import { EXTERNAL_MARKETPLACE_PAGE_SIZE } from "@/lib/marketplace/parse-public-marketplace-query";
+import { NetworkProgramProps } from "@/lib/types";
+import { getPublicNetworkProgramsQuerySchema } from "@/lib/zod/schemas/program-network";
+import { useRouterStuff } from "@dub/ui";
+import { cn, fetcher } from "@dub/utils";
+import { Category } from "@prisma/client";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import {
+ Dispatch,
+ ReactNode,
+ SetStateAction,
+ Suspense,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import useSWR from "swr";
+import * as z from "zod/v4";
+import { MarketplaceListToolbar } from "../marketplace-list-toolbar";
+import {
+ MarketplaceProgramGrid,
+ MarketplaceProgramGridEmpty,
+ MarketplaceProgramGridSkeleton,
+} from "../marketplace-program-grid";
+import { type MarketplaceRewardType } from "../utils/constants";
+import {
+ MarketplaceExternalFilterSidebar,
+ MarketplaceExternalFilterSidebarSkeleton,
+} from "./marketplace-external-filters";
+
+const PAGE_SIZE = EXTERNAL_MARKETPLACE_PAGE_SIZE;
+
+type FilterCounts = {
+ categories: { category: Category; count: number }[];
+ rewardTypes: {
+ type: MarketplaceRewardType;
+ count: number;
+ }[];
+};
+
+type ProgramCounts = FilterCounts & { total: number };
+
+type ParsedQuery = z.infer<typeof getPublicNetworkProgramsQuerySchema>;
+
+type QueryState = {
+ hasParams: boolean;
+ queryString: string | null;
+ data: ParsedQuery;
+};
+
+// query params that switch the page from its server-rendered default into a
+// client-fetched (SWR) view; `category` is part of the static route, not a param
+const PARAM_KEYS = ["rewardType", "search", "sortBy", "sortOrder", "page"];
+
+function pickString(value: string | string[] | undefined) {
+ return typeof value === "string" ? value : undefined;
+}
+
+type SharedProps = {
+ basePath: string;
+ fixedCategory?: Category;
+ initialCounts: ProgramCounts;
+ defaultGrid: ReactNode;
+ defaultSidebar: ReactNode;
+};
+
+export function MarketplaceExternalListPageClient({
+ basePath,
+ fixedCategory,
+ initialCounts,
+ defaultGrid,
+ defaultSidebar,
+}: SharedProps) {
+ const [query, setQuery] = useState<QueryState | null>(null);
+
+ const hasParams = query?.hasParams ?? false;
+ const queryString = query?.queryString ?? null;
+
+ const { data: fetchedPrograms, isValidating } = useSWR<NetworkProgramProps[]>(
+ queryString ? `/api/marketplace/programs${queryString}` : null,
+ fetcher,
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ const { data: fetchedCounts } = useSWR<ProgramCounts>(
+ queryString ? `/api/marketplace/programs/counts${queryString}` : null,
+ fetcher,
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ const rewardType = query?.data.rewardType;
+ const search = query?.data.search;
+ const sortBy = query?.data.sortBy;
+ const sortOrder = query?.data.sortOrder;
+ const page = query?.data.page ?? 1;
+
+ const counts = (hasParams ? fetchedCounts : initialCounts) ?? initialCounts;
+ const isLoadingCounts = hasParams && !fetchedCounts;
+ const totalPages = Math.max(1, Math.ceil(counts.total / PAGE_SIZE));
+
+ const sidebar = !hasParams ? (
+ defaultSidebar
+ ) : isLoadingCounts ? (
+ <MarketplaceExternalFilterSidebarSkeleton />
+ ) : (
+ <MarketplaceExternalFilterSidebar
+ basePath={basePath}
+ activeCategory={fixedCategory}
+ activeRewardType={rewardType}
+ categoryCounts={counts.categories}
+ rewardTypeCounts={counts.rewardTypes}
+ search={search}
+ sortBy={sortBy}
+ sortOrder={sortOrder}
+ />
+ );
+
+ const grid = !hasParams ? (
+ defaultGrid
+ ) : !fetchedPrograms ? (
+ <MarketplaceProgramGridSkeleton />
+ ) : fetchedPrograms.length > 0 ? (
+ <MarketplaceProgramGrid
+ programs={fetchedPrograms}
+ showStatus={false}
+ className={cn(isValidating && "opacity-50")}
+ />
+ ) : (
+ <MarketplaceProgramGridEmpty />
+ );
+
+ return (
+ <>
+ <Suspense fallback={null}>
+ <MarketplaceParamSync
+ basePath={basePath}
+ fixedCategory={fixedCategory}
+ onChange={setQuery}
+ />
+ </Suspense>
+
+ <div className="flex flex-col gap-8 lg:flex-row lg:items-start lg:gap-10">
+ <div className="hidden shrink-0 lg:block">{sidebar}</div>
+ <div className="@container/page flex min-w-0 flex-1 flex-col gap-6">
+ <Suspense fallback={<MarketplaceListToolbarSkeleton />}>
+ <MarketplaceListToolbar
+ variant="external"
+ basePath={basePath}
+ activeCategory={fixedCategory}
+ categoryCounts={counts.categories}
+ rewardTypeCounts={counts.rewardTypes}
+ />
+ </Suspense>
+
+ {grid}
+
+ <MarketplacePagination
+ basePath={basePath}
+ totalPages={totalPages}
+ page={page}
+ rewardType={rewardType}
+ search={search}
+ sortBy={sortBy}
+ sortOrder={sortOrder}
+ />
+ </div>
+ </div>
+ </>
+ );
+}
+
+function MarketplaceParamSync({
+ basePath,
+ fixedCategory,
+ onChange,
+}: {
+ basePath: string;
+ fixedCategory?: Category;
+ onChange: Dispatch<SetStateAction<QueryState | null>>;
+}) {
+ const router = useRouter();
+ const { getQueryString, searchParamsObj } = useRouterStuff();
+
+ const hasParams = PARAM_KEYS.some((key) => {
+ const value = searchParamsObj[key];
+ return typeof value === "string" && value !== "";
+ });
+
+ const parsed = useMemo(
+ () =>
+ getPublicNetworkProgramsQuerySchema.safeParse({
+ rewardType: pickString(searchParamsObj.rewardType),
+ search: pickString(searchParamsObj.search),
+ sortBy: pickString(searchParamsObj.sortBy),
+ sortOrder: pickString(searchParamsObj.sortOrder),
+ page: pickString(searchParamsObj.page),
+ pageSize: PAGE_SIZE,
+ ...(fixedCategory ? { category: fixedCategory } : {}),
+ }),
+ [fixedCategory, searchParamsObj],
+ );
+
+ const queryString =
+ parsed.success && hasParams
+ ? getQueryString({
+ ...(fixedCategory ? { category: fixedCategory } : {}),
+ pageSize: String(PAGE_SIZE),
+ })
+ : null;
+
+ useEffect(() => {
+ if (!parsed.success) {
+ router.replace(basePath);
+ return;
+ }
+
+ onChange({ hasParams, queryString, data: parsed.data });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [basePath, hasParams, queryString, parsed.success, router]);
+
+ return null;
+}
+
+function MarketplacePagination({
+ basePath,
+ totalPages,
+ page,
+ rewardType,
+ search,
+ sortBy,
+ sortOrder,
+}: {
+ basePath: string;
+ totalPages: number;
+ page: number;
+ rewardType?: string;
+ search?: string;
+ sortBy?: string;
+ sortOrder?: string;
+}) {
+ if (totalPages <= 1) return null;
+
+ return (
+ <div className="flex items-center justify-center gap-2">
+ {Array.from({ length: totalPages }, (_, index) => {
+ const pageNumber = index + 1;
+ const queryParams = new URLSearchParams();
+
+ if (rewardType) queryParams.set("rewardType", rewardType);
+ if (search) queryParams.set("search", search);
+ if (sortBy && sortBy !== "popularity")
+ queryParams.set("sortBy", sortBy);
+ if (sortOrder && sortOrder !== "desc")
+ queryParams.set("sortOrder", sortOrder);
+ if (pageNumber > 1) queryParams.set("page", String(pageNumber));
+
+ const query = queryParams.toString();
+
+ return (
+ <Link
+ key={pageNumber}
+ href={`${basePath}${query ? `?${query}` : ""}`}
+ className={
+ pageNumber === page
+ ? "rounded-lg bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white"
+ : "border-border-subtle hover:bg-bg-subtle rounded-lg border px-3 py-1.5 text-sm font-medium"
+ }
+ >
+ {pageNumber}
+ </Link>
+ );
+ })}
+ </div>
+ );
+}
+
+function MarketplaceListToolbarSkeleton() {
+ return (
+ <div className="grid grid-cols-2 gap-4 lg:flex lg:items-center lg:justify-between lg:gap-6">
+ <div className="h-9 w-full animate-pulse rounded-lg bg-neutral-100 lg:hidden" />
+ <div className="hidden h-9 w-44 animate-pulse rounded-lg bg-neutral-100 lg:block" />
+ <div className="h-9 w-full animate-pulse rounded-lg bg-neutral-100 lg:w-[19rem]" />
+ </div>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-list-page.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-list-page.tsx
new file mode 100644
index 0000000000..0ae5526280
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-list-page.tsx
@@ -0,0 +1,77 @@
+import { getNetworkProgramCounts } from "@/lib/fetchers/get-network-program-counts";
+import { getPublicNetworkPrograms } from "@/lib/fetchers/get-public-network-programs";
+import { EXTERNAL_MARKETPLACE_PAGE_SIZE } from "@/lib/marketplace/parse-public-marketplace-query";
+import { PROGRAM_CATEGORIES_MAP } from "@/lib/network/program-categories";
+import { Category } from "@prisma/client";
+import {
+ MarketplaceProgramGrid,
+ MarketplaceProgramGridEmpty,
+} from "../marketplace-program-grid";
+import {
+ getMarketplaceExternalBasePath,
+ MarketplaceExternalFilterSidebar,
+} from "./marketplace-external-filters";
+import { MarketplaceExternalListPageClient } from "./marketplace-external-list-page-client";
+import { MarketplaceExternalShell } from "./marketplace-external-shell";
+
+export async function MarketplaceExternalListPage({
+ segments,
+ fixedCategory,
+}: {
+ segments: string[];
+ fixedCategory?: Category;
+}) {
+ const basePath = getMarketplaceExternalBasePath({ segments });
+ const categoryMeta = fixedCategory
+ ? PROGRAM_CATEGORIES_MAP[fixedCategory]
+ : undefined;
+
+ const [initialPrograms, initialCounts] = await Promise.all([
+ getPublicNetworkPrograms({
+ category: fixedCategory,
+ page: 1,
+ pageSize: EXTERNAL_MARKETPLACE_PAGE_SIZE,
+ }),
+ getNetworkProgramCounts({ category: fixedCategory }),
+ ]);
+
+ const defaultSidebar = (
+ <MarketplaceExternalFilterSidebar
+ basePath={basePath}
+ activeCategory={fixedCategory}
+ categoryCounts={initialCounts.categories}
+ rewardTypeCounts={initialCounts.rewardTypes}
+ />
+ );
+
+ const defaultGrid =
+ initialPrograms.length > 0 ? (
+ <MarketplaceProgramGrid programs={initialPrograms} showStatus={false} />
+ ) : (
+ <MarketplaceProgramGridEmpty />
+ );
+
+ return (
+ <MarketplaceExternalShell
+ variant="list"
+ title={
+ categoryMeta ? (
+ <>
+ {categoryMeta.label} affiliate
+ <br />
+ programs
+ </>
+ ) : undefined
+ }
+ description={categoryMeta?.listPageDescription}
+ >
+ <MarketplaceExternalListPageClient
+ basePath={basePath}
+ fixedCategory={fixedCategory}
+ initialCounts={initialCounts}
+ defaultGrid={defaultGrid}
+ defaultSidebar={defaultSidebar}
+ />
+ </MarketplaceExternalShell>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx
new file mode 100644
index 0000000000..7ff3b60b93
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx
@@ -0,0 +1,54 @@
+import { getNetworkProgram } from "@/lib/fetchers/get-network-program";
+import { ApplicationAnalytics } from "@/ui/application-analytics";
+import { MarketplaceProgramDetailBody } from "@/ui/program-marketplace/marketplace-program-detail-body";
+import { MarketplaceProgramDetailsLayout } from "@/ui/program-marketplace/marketplace-program-details-layout";
+import { MarketplaceProgramHero } from "@/ui/program-marketplace/marketplace-program-hero";
+import { getMarketplaceAllHref } from "@/ui/program-marketplace/utils/urls";
+import { ChevronLeft } from "@dub/ui";
+import Link from "next/link";
+import { redirect } from "next/navigation";
+import { MarketplaceExternalApplyButton } from "./marketplace-external-apply-button";
+import { MarketplaceExternalShell } from "./marketplace-external-shell";
+
+export async function MarketplaceExternalProgramPage({
+ programSlug,
+}: {
+ programSlug: string;
+}) {
+ const program = await getNetworkProgram({
+ slug: programSlug,
+ });
+
+ if (!program) {
+ redirect("/marketplace");
+ }
+
+ return (
+ <>
+ <ApplicationAnalytics />
+ <MarketplaceExternalShell variant="none">
+ <MarketplaceProgramDetailsLayout
+ header={
+ <Link
+ href={getMarketplaceAllHref()}
+ className="group inline-flex items-center gap-1 text-xs font-medium text-neutral-800 transition-colors hover:text-neutral-500"
+ >
+ <ChevronLeft className="size-[10px] text-neutral-500 transition-transform group-hover:-translate-x-0.5" />
+ All Programs
+ </Link>
+ }
+ hero={
+ <MarketplaceProgramHero
+ program={program}
+ applySlot={
+ <MarketplaceExternalApplyButton programSlug={program.slug} />
+ }
+ />
+ }
+ >
+ <MarketplaceProgramDetailBody program={program} />
+ </MarketplaceProgramDetailsLayout>
+ </MarketplaceExternalShell>
+ </>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-router.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-router.tsx
new file mode 100644
index 0000000000..db7d0a5f0d
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-router.tsx
@@ -0,0 +1,38 @@
+import { notFound } from "next/navigation";
+import { slugToCategory } from "../utils/urls";
+import { MarketplaceExternalHomePage } from "./marketplace-external-home-page";
+import { MarketplaceExternalListPage } from "./marketplace-external-list-page";
+import { MarketplaceExternalProgramPage } from "./marketplace-external-program-page";
+
+export async function MarketplaceExternalRouter({
+ segments,
+}: {
+ segments: string[];
+}) {
+ if (segments.length === 0) {
+ return <MarketplaceExternalHomePage />;
+ }
+
+ if (segments.length === 1 && segments[0] === "all") {
+ return <MarketplaceExternalListPage segments={segments} />;
+ }
+
+ if (segments.length === 2 && segments[0] === "c") {
+ const category = slugToCategory(segments[1]);
+
+ if (category) {
+ return (
+ <MarketplaceExternalListPage
+ segments={segments}
+ fixedCategory={category}
+ />
+ );
+ }
+ }
+
+ if (segments.length === 1) {
+ return <MarketplaceExternalProgramPage programSlug={segments[0]} />;
+ }
+
+ notFound();
+}
diff --git a/apps/web/ui/program-marketplace/external/marketplace-external-shell.tsx b/apps/web/ui/program-marketplace/external/marketplace-external-shell.tsx
new file mode 100644
index 0000000000..23757c242f
--- /dev/null
+++ b/apps/web/ui/program-marketplace/external/marketplace-external-shell.tsx
@@ -0,0 +1,61 @@
+import { cn } from "@dub/utils";
+import { ReactNode } from "react";
+
+const CONTAINER_CLASS = "mx-auto w-full max-w-screen-xl px-4 sm:px-6 lg:px-8";
+
+export function MarketplaceExternalShell({
+ variant = "home",
+ title,
+ description,
+ children,
+}: {
+ variant?: "home" | "list" | "none";
+ title?: ReactNode;
+ description?: string;
+ children: ReactNode;
+}) {
+ if (variant === "none") {
+ return (
+ <div className={cn(CONTAINER_CLASS, "relative z-10 pb-10 pt-6")}>
+ {children}
+ </div>
+ );
+ }
+
+ const resolvedTitle =
+ title ??
+ (variant === "home" ? (
+ <>
+ Best SaaS affiliate
+ <br />
+ programs in {new Date().getFullYear()}
+ </>
+ ) : (
+ <>
+ Discover your
+ <br />
+ next partnership
+ </>
+ ));
+
+ const resolvedDescription =
+ description ??
+ "Explore the variety of SaaS affiliate programs in the Dub Program Marketplace and start monetizing your traffic/audience today.";
+
+ return (
+ <div className="relative z-10 flex flex-col">
+ <div className={cn(CONTAINER_CLASS, "pb-12 pt-20")}>
+ <div className="flex flex-col gap-4">
+ <h1 className="font-display text-[50px] font-medium leading-[1.1] text-neutral-900">
+ {resolvedTitle}
+ </h1>
+ <p className="max-w-2xl text-lg font-normal text-neutral-600">
+ {resolvedDescription}
+ </p>
+ </div>
+ </div>
+ <div className="h-px w-full bg-neutral-200" />
+ <div className={cn(CONTAINER_CLASS, "py-10")}>{children}</div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/program-marketplace/featured-program-card.tsx b/apps/web/ui/program-marketplace/featured-program-card.tsx
index 0cb6bdd7f3..24eb3460b6 100644
--- a/apps/web/ui/program-marketplace/featured-program-card.tsx
+++ b/apps/web/ui/program-marketplace/featured-program-card.tsx
@@ -7,7 +7,6 @@ import { ProgramRewardsDisplay } from "@/ui/program-marketplace/program-rewards-
import {
getMarketplaceAllHref,
getMarketplaceCategoryHref,
- getMarketplaceProgramHref,
} from "@/ui/program-marketplace/utils/urls";
import { Tooltip } from "@dub/ui";
import { ArrowUpRight, Globe } from "@dub/ui/icons";
@@ -65,7 +64,7 @@ export function FeaturedProgramCard({
/>
<Link
- href={getMarketplaceProgramHref(program.slug)}
+ href={`/marketplace/${program.slug}`}
className="absolute inset-0 z-10 rounded-2xl"
aria-label={`View ${program.name}`}
/>
diff --git a/apps/web/ui/program-marketplace/home-sections.ts b/apps/web/ui/program-marketplace/home-sections.ts
index 61f478cb99..7bfd486050 100644
--- a/apps/web/ui/program-marketplace/home-sections.ts
+++ b/apps/web/ui/program-marketplace/home-sections.ts
@@ -14,7 +14,7 @@ export type MarketplaceHomeRow = {
const featuredHomeRows: MarketplaceHomeRow[] = [
{
- key: "most-popular",
+ key: "mostPopular",
title: "Most popular",
viewAllHref: getMarketplaceAllHref({
sortBy: "popularity",
@@ -23,7 +23,7 @@ const featuredHomeRows: MarketplaceHomeRow[] = [
showViewAllCard: true,
},
{
- key: "new",
+ key: "newPrograms",
title: "New",
viewAllHref: getMarketplaceAllHref({
sortBy: "recency",
diff --git a/apps/web/ui/program-marketplace/marketplace-program-row.tsx b/apps/web/ui/program-marketplace/marketplace-program-row.tsx
index 19e67c51fe..5b87e9af8b 100644
--- a/apps/web/ui/program-marketplace/marketplace-program-row.tsx
+++ b/apps/web/ui/program-marketplace/marketplace-program-row.tsx
@@ -3,9 +3,7 @@
import { NetworkProgramProps } from "@/lib/types";
import { Carousel, CarouselContent, CarouselItem, useCarousel } from "@dub/ui";
import { ChevronLeft, ChevronRight } from "@dub/ui/icons";
-import { cn, fetcher } from "@dub/utils";
import Link from "next/link";
-import useSWR from "swr";
import { MarketplaceViewAllCard } from "./marketplace-view-all-card";
import {
MarketplaceProgramCard,
@@ -58,30 +56,12 @@ export function MarketplaceProgramRow({
viewAllHref,
showViewAllCard = false,
showStatus = true,
- variant = "default",
- ...props
+ programs,
}: MarketplaceProgramRowProps) {
- const { data: fetchedPrograms, error } = useSWR<NetworkProgramProps[]>(
- props.apiPath ?? null,
- fetcher,
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- const programs = props.programs ?? fetchedPrograms;
- const isHome = variant === "home";
-
- const carouselItemClassName = cn(
- "pl-0",
- isHome
- ? "basis-[310px] sm:basis-[419px]"
- : "basis-[280px] md:basis-[320px]",
- );
-
- const cardClassName = isHome
- ? "h-[260px] w-[310px] sm:h-[284px] sm:w-[419px] sm:p-8"
- : undefined;
+ const carouselItemClassName = "pl-0 basis-[310px] sm:basis-[419px]";
+ const cardClassName = "h-[260px] w-[310px] sm:h-[284px] sm:w-[419px] sm:p-8";
- if (error || programs?.length === 0) {
+ if (programs && programs.length === 0) {
return null;
}
diff --git a/apps/web/ui/program-marketplace/marketplace-router.tsx b/apps/web/ui/program-marketplace/marketplace-router.tsx
index 7d200ba1cc..2286766f59 100644
--- a/apps/web/ui/program-marketplace/marketplace-router.tsx
+++ b/apps/web/ui/program-marketplace/marketplace-router.tsx
@@ -1,10 +1,7 @@
import { PROGRAM_CATEGORIES_MAP } from "@/lib/network/program-categories";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
-import {
- getMarketplaceHref,
- slugToCategory,
-} from "@/ui/program-marketplace/utils/urls";
+import { slugToCategory } from "@/ui/program-marketplace/utils/urls";
import { ChevronRight, Shop } from "@dub/ui";
import { Category } from "@prisma/client";
import Link from "next/link";
@@ -23,7 +20,7 @@ function MarketplaceListTitle({ category }: { category?: Category }) {
<div className="flex items-center gap-1.5">
<div className="flex items-center gap-1">
<Link
- href={getMarketplaceHref()}
+ href="/marketplace"
aria-label="Back to marketplace"
className="bg-bg-subtle hover:bg-bg-emphasis flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 active:scale-95"
>
diff --git a/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx b/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx
index e3e051fe50..56455742e8 100644
--- a/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx
+++ b/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx
@@ -1,6 +1,5 @@
"use client";
-import { getMarketplaceHref } from "@/ui/program-marketplace/utils/urls";
import { ChevronLeft, Filter, useKeyboardShortcut } from "@dub/ui";
import { cn } from "@dub/utils";
import Link from "next/link";
@@ -24,7 +23,7 @@ export function MarketplaceSidebarFilters() {
return (
<div className="flex flex-col gap-2">
<Link
- href={getMarketplaceHref()}
+ href="/marketplace"
className={cn(
"group flex w-full items-center gap-3 rounded-lg px-2 py-1.5 text-sm font-medium text-neutral-800 transition-all duration-75",
"hover:bg-neutral-200/50 active:bg-neutral-200/80",
diff --git a/apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx b/apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx
index 44af6e1def..4398519e50 100644
--- a/apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx
+++ b/apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx
@@ -1,9 +1,7 @@
"use client";
-import type { NetworkProgramProps } from "@/lib/types";
import { MarketplaceProgramsSummarySchema } from "@/lib/zod/schemas/program-network";
import { fetcher } from "@dub/utils";
-import { Category } from "@prisma/client";
import useSWR from "swr";
import type * as z from "zod/v4";
import {
@@ -18,21 +16,6 @@ type MarketplaceProgramsSummary = z.infer<
typeof MarketplaceProgramsSummarySchema
>;
-function getRowPrograms(
- summary: MarketplaceProgramsSummary,
- rowKey: string,
-): NetworkProgramProps[] {
- if (rowKey === "most-popular") {
- return summary.mostPopular;
- }
-
- if (rowKey === "new") {
- return summary.newPrograms;
- }
-
- return summary.categories[rowKey as Category] ?? [];
-}
-
export function MarketplaceHomePage() {
const { data: summary } = useSWR<MarketplaceProgramsSummary>(
"/api/network/programs/summary",
@@ -51,11 +34,14 @@ export function MarketplaceHomePage() {
{MARKETPLACE_HOME_ROWS.map((row) => (
<MarketplaceProgramRow
key={row.key}
- variant="home"
title={row.title}
viewAllHref={row.viewAllHref}
showViewAllCard={row.showViewAllCard}
- programs={summary ? getRowPrograms(summary, row.key) : undefined}
+ programs={
+ summary
+ ? summary.categories[row.key] ?? summary[row.key]
+ : undefined
+ }
/>
))}
</div>
diff --git a/apps/web/ui/program-marketplace/pages/marketplace-program-page.tsx b/apps/web/ui/program-marketplace/pages/marketplace-program-page.tsx
index d99378a091..3f5e8ebe9f 100644
--- a/apps/web/ui/program-marketplace/pages/marketplace-program-page.tsx
+++ b/apps/web/ui/program-marketplace/pages/marketplace-program-page.tsx
@@ -1,5 +1,4 @@
import { getNetworkProgram } from "@/lib/fetchers/get-network-program";
-import { prisma } from "@/lib/prisma";
import { ApplicationAnalytics } from "@/ui/application-analytics";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
@@ -8,43 +7,11 @@ import { MarketplaceProgramDetailsLayout } from "@/ui/program-marketplace/market
import { MarketplaceProgramHero } from "@/ui/program-marketplace/marketplace-program-hero";
import { MarketplaceProgramPageSkeleton } from "@/ui/program-marketplace/marketplace-program-page-skeleton";
import { ChevronRight, Shop } from "@dub/ui";
-import { Category } from "@prisma/client";
import Link from "next/link";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { MarketplaceProgramHeaderControls } from "../marketplace-program-header-controls";
import { ProgramStatusBadge } from "../program-status-badge";
-import { getMarketplaceHref } from "../utils/urls";
-
-export const revalidate = 3600; // 1 hour
-
-export async function generateMarketplaceProgramStaticParams() {
- const programs = await prisma.program.findMany({
- where: {
- addedToMarketplaceAt: {
- not: null,
- },
- },
- select: {
- slug: true,
- },
- });
-
- const categoryPages = Object.values(Category).map((category) => ({
- segments: ["c", category.toLowerCase()],
- }));
-
- const programPages = programs.map((program) => ({
- segments: [program.slug],
- }));
-
- return [
- { segments: [] },
- { segments: ["all"] },
- ...categoryPages,
- ...programPages,
- ];
-}
export function MarketplaceProgramPage({
programSlug,
@@ -68,7 +35,7 @@ async function MarketplaceProgramPageContent({
});
if (!program) {
- redirect(getMarketplaceHref());
+ redirect("/marketplace");
}
return (
@@ -77,7 +44,7 @@ async function MarketplaceProgramPageContent({
<div className="flex items-center gap-1.5">
<div className="flex items-center gap-1">
<Link
- href={getMarketplaceHref()}
+ href="/marketplace"
aria-label="Back to marketplace"
className="bg-bg-subtle hover:bg-bg-emphasis flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 active:scale-95"
>
diff --git a/apps/web/ui/program-marketplace/program-card.tsx b/apps/web/ui/program-marketplace/program-card.tsx
index fb3d87dedf..22b6370b40 100644
--- a/apps/web/ui/program-marketplace/program-card.tsx
+++ b/apps/web/ui/program-marketplace/program-card.tsx
@@ -6,7 +6,6 @@ import { ProgramRewardsDisplay } from "@/ui/program-marketplace/program-rewards-
import {
getMarketplaceAllHref,
getMarketplaceCategoryHref,
- getMarketplaceProgramHref,
} from "@/ui/program-marketplace/utils/urls";
import { Tooltip } from "@dub/ui";
import { OG_AVATAR_URL, cn } from "@dub/utils";
@@ -27,7 +26,7 @@ export function MarketplaceProgramCard({
return (
<Link
- href={getMarketplaceProgramHref(program.slug)}
+ href={`/marketplace/${program.slug}`}
className={cn(
"border-border-subtle hover:drop-shadow-card-hover flex h-full flex-col rounded-xl border bg-white p-4 transition-[filter] sm:p-6",
className,
diff --git a/apps/web/ui/program-marketplace/program-marketplace-banner.tsx b/apps/web/ui/program-marketplace/program-marketplace-banner.tsx
index 872502285d..07ef04d479 100644
--- a/apps/web/ui/program-marketplace/program-marketplace-banner.tsx
+++ b/apps/web/ui/program-marketplace/program-marketplace-banner.tsx
@@ -2,7 +2,6 @@
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { useProgramMarketplacePromo } from "@/ui/program-marketplace/use-program-marketplace-promo";
-import { getMarketplaceHref } from "@/ui/program-marketplace/utils/urls";
import { X } from "@/ui/shared/icons";
import { Button, Grid, buttonVariants } from "@dub/ui";
import { cn } from "@dub/utils";
@@ -69,7 +68,7 @@ export function ProgramMarketplaceBanner() {
<div className="flex items-center gap-2 p-3 sm:px-2 sm:py-0">
<Link
- href={getMarketplaceHref()}
+ href="/marketplace"
className={cn(
buttonVariants({ variant: "primary" }),
"flex h-8 w-fit items-center justify-center whitespace-nowrap rounded-lg border px-3 text-sm",
diff --git a/apps/web/ui/program-marketplace/program-marketplace-card.tsx b/apps/web/ui/program-marketplace/program-marketplace-card.tsx
index f22ebdbed9..b0d0e97b97 100644
--- a/apps/web/ui/program-marketplace/program-marketplace-card.tsx
+++ b/apps/web/ui/program-marketplace/program-marketplace-card.tsx
@@ -2,7 +2,6 @@
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { useProgramMarketplacePromo } from "@/ui/program-marketplace/use-program-marketplace-promo";
-import { getMarketplaceHref } from "@/ui/program-marketplace/utils/urls";
import { Grid, buttonVariants } from "@dub/ui";
import { cn } from "@dub/utils";
import { AnimatePresence, motion } from "motion/react";
@@ -55,7 +54,7 @@ export function ProgramMarketplaceCard() {
</div>
<Link
- href={getMarketplaceHref()}
+ href="/marketplace"
className={cn(
buttonVariants({ variant: "primary" }),
"flex h-6 w-fit items-center justify-center whitespace-nowrap rounded-md border px-1.5 text-xs",
diff --git a/apps/web/ui/program-marketplace/program-rewards-display.tsx b/apps/web/ui/program-marketplace/program-rewards-display.tsx
index 9fe4a7f359..f0cc30266f 100644
--- a/apps/web/ui/program-marketplace/program-rewards-display.tsx
+++ b/apps/web/ui/program-marketplace/program-rewards-display.tsx
@@ -100,7 +100,7 @@ export function ProgramRewardsDisplay({
<span>{item.description}</span>
</HoverCard.Content>
</HoverCard.Portal>
- <HoverCard.Trigger>
+ <HoverCard.Trigger asChild>
<As
{...(item.onClick && {
type: "button",
diff --git a/apps/web/ui/program-marketplace/utils/default-exports.ts b/apps/web/ui/program-marketplace/utils/default-exports.ts
new file mode 100644
index 0000000000..c1f8782a4f
--- /dev/null
+++ b/apps/web/ui/program-marketplace/utils/default-exports.ts
@@ -0,0 +1,32 @@
+import { prisma } from "@/lib/prisma";
+import { Category } from "@prisma/client";
+
+export const revalidate = 3600;
+
+export async function generateStaticParams() {
+ const programs = await prisma.program.findMany({
+ where: {
+ addedToMarketplaceAt: {
+ not: null,
+ },
+ },
+ select: {
+ slug: true,
+ },
+ });
+
+ const categoryPages = Object.values(Category).map((category) => ({
+ segments: ["c", category.toLowerCase()],
+ }));
+
+ const programPages = programs.map((program) => ({
+ segments: [program.slug],
+ }));
+
+ return [
+ { segments: [] },
+ { segments: ["all"] },
+ ...categoryPages,
+ ...programPages,
+ ];
+}
diff --git a/apps/web/ui/program-marketplace/utils/urls.ts b/apps/web/ui/program-marketplace/utils/urls.ts
index c09ab1a56a..2f70cc4b6c 100644
--- a/apps/web/ui/program-marketplace/utils/urls.ts
+++ b/apps/web/ui/program-marketplace/utils/urls.ts
@@ -34,14 +34,10 @@ function buildMarketplaceHref(
return `${path}${queryString ? `?${queryString}` : ""}`;
}
-export function getMarketplaceHref() {
- return MARKETPLACE_BASE;
-}
-
export function getMarketplaceAllHref(
params?: Record<string, string | undefined>,
) {
- return buildMarketplaceHref(`${MARKETPLACE_BASE}/all`, params);
+ return buildMarketplaceHref("/marketplace/all", params);
}
export function getPreservedMarketplaceSearchParams(
@@ -62,37 +58,11 @@ export function getMarketplaceCategoryHref(
params?: Record<string, string | undefined>,
) {
return buildMarketplaceHref(
- `${MARKETPLACE_BASE}/c/${category.toLowerCase()}`,
+ `/marketplace/c/${category.toLowerCase()}`,
params,
);
}
-export function getMarketplaceProgramHref(programSlug: string) {
- return `${MARKETPLACE_BASE}/${programSlug}`;
-}
-
-export function getMarketplacePathFromSlug(slug?: string[]) {
- const segments = slug ?? [];
-
- if (segments.length === 0) {
- return MARKETPLACE_BASE;
- }
-
- return `${MARKETPLACE_BASE}/${segments.join("/")}`;
-}
-
-export function getMarketplaceCanonicalUrl(pathname: string) {
- return `https://dub.co${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
-}
-
-function getMarketplacePartnersProgramUrl(programSlug: string) {
- return `https://partners.dub.co${getMarketplaceProgramHref(programSlug)}`;
-}
-
-export function getMarketplacePublicApplyHref(programSlug: string) {
- return getMarketplacePartnersProgramUrl(programSlug);
-}
-
export function getMarketplaceCategoryFromPathname(
pathname: string,
): Category | null {
diff --git a/packages/ui/src/nav/nav-mobile.tsx b/packages/ui/src/nav/nav-mobile.tsx
index d9a40ed7af..7eee44ae4f 100644
--- a/packages/ui/src/nav/nav-mobile.tsx
+++ b/packages/ui/src/nav/nav-mobile.tsx
@@ -15,7 +15,7 @@ import {
DubLinksIcon,
DubPartnersIcon,
} from "../icons";
-import { navItems, type NavTheme } from "./nav";
+import { navItems, type NavItem, type NavTheme } from "./nav";
const specialIcons: Record<string, ReactNode> = {
"Dub Links": (
@@ -43,9 +43,11 @@ const specialIcons: Record<string, ReactNode> = {
export function NavMobile({
theme = "light",
staticDomain,
+ navItems: items = navItems,
}: {
theme?: NavTheme;
staticDomain?: string;
+ navItems?: NavItem[];
}) {
let { domain = "dub.co" } = useParams() as { domain: string };
if (staticDomain) {
@@ -110,7 +112,7 @@ export function NavMobile({
)}
>
<ul className="grid divide-y divide-neutral-200 dark:divide-white/[0.15]">
- {navItems.map(({ name, href, childItems }, idx) => (
+ {items.map(({ name, href, childItems }, idx) => (
<MobileNavItem
key={idx}
name={name}
diff --git a/packages/ui/src/nav/nav.tsx b/packages/ui/src/nav/nav.tsx
index 18f4f74a8c..4b3298d4af 100644
--- a/packages/ui/src/nav/nav.tsx
+++ b/packages/ui/src/nav/nav.tsx
@@ -6,6 +6,7 @@ import { motion } from "motion/react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import {
+ ComponentType,
PropsWithChildren,
ReactNode,
SVGProps,
@@ -15,7 +16,12 @@ import {
} from "react";
import useSWR from "swr";
import { buttonVariants } from "../button";
-import { FEATURES_LIST, RESOURCES, SOLUTIONS } from "../content";
+import {
+ FEATURES_LIST,
+ RESOURCES,
+ SOLUTIONS,
+ type NavItemChildren,
+} from "../content";
import { useScroll } from "../hooks";
import { MaxWidthWrapper } from "../max-width-wrapper";
import { NavWordmark } from "../nav-wordmark";
@@ -29,7 +35,16 @@ export const NavContext = createContext<{ theme: NavTheme }>({
theme: "light",
});
-export const navItems = [
+export type NavItem = {
+ name: string;
+ href?: string;
+ segments?: string[];
+ content?: ComponentType<{ domain: string }>;
+ childItems?: NavItemChildren;
+ mobileOnly?: boolean;
+};
+
+export const navItems: NavItem[] = [
{
name: "Product",
content: ProductContent,
@@ -123,11 +138,13 @@ export function Nav({
theme = "light",
staticDomain,
maxWidthWrapperClassName,
+ navItems: items = navItems,
logo,
}: {
theme?: NavTheme;
staticDomain?: string;
maxWidthWrapperClassName?: string;
+ navItems?: NavItem[];
logo?: ReactNode;
}) {
let { domain = "dub.co" } = useParams() as { domain: string };
@@ -228,7 +245,7 @@ export function Nav({
animate={hoverStyle}
transition={pillSpring}
/>
- {navItems
+ {items
.filter(({ mobileOnly }) => !mobileOnly)
.map(({ name, href, segments, content: Content }) => {
const isActive = (segments ?? []).some((segment) =>