[!NOTE]
> Currency values rendered in the earnings summary header use `currencyFormatter` with `maximumFractionDigits: 2` to standardize payout display figures across variable locales.
### Chart Component and SVG Scaling Constants
The internal `Chart` component receives the timeseries data and background variant. It defines layout constants for circle rendering and coordinate scaling, operating on an internal canvas width of 1400 and height of 600 pixels.
```tsx
function Chart({
data,
background,
}: {
data: { start: string; earnings: number }[];
background: "light" | "dark";
}) {
if (!data || data.length === 0) {
return null;
}
const circleRadius = 10;
const strokeWidth = 6;
const strokeHalfWidth = strokeWidth / 2;
const edgePadding = circleRadius + strokeHalfWidth;
const width = 1400;
const height = 600;
const padding = {
```
Sources: [apps/web/app/api/og/partner-earnings/route.tsx:160-178](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/partner-earnings/route.tsx#L160-L178)
## Analytics Timeseries Social Cards
### Edge Route Request Handling and Validation
The analytics Open Graph endpoint (`apps/web/app/api/og/analytics/route.tsx`) processes incoming GET requests by extracting `linkId` and `folderId` query parameters. If both parameters are absent, the route immediately responds with a status code of `400` and the text `"Missing linkId or folderId"`.
```tsx
export async function GET(req: NextRequest) {
// Load Inter Medium font (weight 500)
const interMedium = await loadGoogleFont("Inter:wght@500");
const linkId = req.nextUrl.searchParams.get("linkId");
const folderId = req.nextUrl.searchParams.get("folderId");
if (!linkId && !folderId) {
return new Response("Missing linkId or folderId", {
status: 400,
});
}
```
Sources: [apps/web/app/api/og/analytics/route.tsx:16-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L16-L27)
When `linkId` is supplied, the route queries `prismaEdge.link.findUnique` with dashboard inclusion. It verifies that the record exists and possesses an active public [analytics dashboard](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/analytics-dashboard), returning status `404` if the link is missing or `403` if `dashboard` is null. When `folderId` is provided instead, it queries `prismaEdge.folder.findUnique`, validating its existence and dashboard presence in the same manner.
```tsx
if (linkId) {
const data = await prismaEdge.link.findUnique({
where: {
id: linkId,
},
include: {
dashboard: true,
},
});
if (!data) {
return new Response("Link not found", {
status: 404,
});
}
if (!data.dashboard) {
return new Response("Link does not have a public analytics dashboard", {
status: 403,
});
}
workspaceId = data.projectId;
link = {
domain: data.domain,
key: data.key,
url: data.url,
};
} else if (folderId) {
const data = await prismaEdge.folder.findUnique({
where: {
id: folderId,
},
include: {
dashboard: true,
},
});
if (!data) {
return new Response("Folder not found", {
status: 404,
});
}
if (!data.dashboard) {
return new Response("Folder does not have a public analytics dashboard", {
status: 403,
});
}
workspaceId = data.projectId;
folder = {
id: data.id,
name: data.name,
};
}
```
Sources: [apps/web/app/api/og/analytics/route.tsx:32-85](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L32-L85)
### Tinybird Timeseries Data Fetching
Concurrently with font loading via `loadGoogleFont("Inter:wght@500")`, the route calculates date ranges using `getStartEndDates` with a fixed `30d` interval. It queries the [Tinybird analytics](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics) pipeline endpoint at `https://api.us-east.tinybird.co/v0/pipes/v3_timeseries.json`.
```tsx
import { formatUTCDateTimeClickhouse } from "@/lib/analytics/utils/format-utc-datetime-clickhouse";
import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
import { prismaEdge } from "@/lib/prisma/edge";
import {
GOOGLE_FAVICON_URL,
getApexDomain,
linkConstructor,
nFormatter,
} from "@dub/utils";
import { Folder, Link } from "@prisma/client";
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
import { loadGoogleFont } from "../load-google-font";
…
const { startDate, endDate, granularity } = getStartEndDates({
interval: "30d",
});
const timeseriesData = await fetch(
`https://api.us-east.tinybird.co/v0/pipes/v3_timeseries.json?${new URLSearchParams(
{
event: "clicks",
...(workspaceId ? { workspaceId } : {}),
...(folderId ? { folderId } : {}),
...(linkId ? { linkId } : {}),
start: formatUTCDateTimeClickhouse(startDate),
end: formatUTCDateTimeClickhouse(endDate),
granularity,
},
)}`,
{
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
},
next: {
revalidate: 60, // revalidate every minute
},
},
)
.then((res) => res.json())
.then((res) => res.data)
.catch(() => []);
```
Sources: [apps/web/app/api/og/analytics/route.tsx:1-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L1-L13), [apps/web/app/api/og/analytics/route.tsx:87-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L87-L114)
| Query Parameter | Source / Value | Purpose |
| :--- | :--- | :--- |
| `event` | `"clicks"` | Specifies click telemetry event stream |
| `workspaceId` | `data.projectId` | Scopes data to the parent workspace |
| `folderId` | `folderId` (conditional) | Scopes data to a specific folder |
| `linkId` | `linkId` (conditional) | Scopes data to an individual short link |
| `start` | `formatUTCDateTimeClickhouse(startDate)` | Beginning timestamp of the 30-day window |
| `end` | `formatUTCDateTimeClickhouse(endDate)` | Ending timestamp of the 30-day window |
| `granularity` | `granularity` | Time bucket aggregation interval |
```tsx
const timeseriesData = await fetch(
`https://api.us-east.tinybird.co/v0/pipes/v3_timeseries.json?${new URLSearchParams(
{
event: "clicks",
...(workspaceId ? { workspaceId } : {}),
...(folderId ? { folderId } : {}),
...(linkId ? { linkId } : {}),
start: formatUTCDateTimeClickhouse(startDate),
end: formatUTCDateTimeClickhouse(endDate),
granularity,
},
)}`,
```
Sources: [apps/web/app/api/og/analytics/route.tsx:91-102](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L91-L102)
> [!WARNING]
> Requests to the Tinybird API authenticate via bearer token using `process.env.TINYBIRD_API_KEY` and enforce a cache revalidation period of 60 seconds (`next: { revalidate: 60 }`). Failures in fetching or parsing JSON catch and fall back to an empty array `[]`.
```tsx
{
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
},
next: {
revalidate: 60, // revalidate every minute
},
},
)
.then((res) => res.json())
.then((res) => res.data)
.catch(() => []);
```
Sources: [apps/web/app/api/og/analytics/route.tsx:103-115](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L103-L115)
### Chart Component and SVG Coordinate Scaling
The internal `Chart` component renders an SVG element inside the `ImageResponse` with a fixed viewport width of `1100` and height of `370`. It computes `maxClicks` across all data points and applies linear scaling functions for coordinate transformation.
```tsx
const Chart = ({ data }) => {
// Define SVG size
const width = 1100;
const height = 370;
// Find the max clicks value for Y-axis scaling
const maxClicks = Math.max(...data.map((d) => d.clicks));
// Function to convert date to X coordinate
const scaleX = (index) => (width / (data.length - 1)) * index;
// Function to convert clicks to Y coordinate
const scaleY = (clicks) => height - (clicks / maxClicks) * height;
```
Sources: [apps/web/app/api/og/analytics/route.tsx:231-244](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L231-L244)
```mermaid
flowchart TD
A["Raw Timeseries Data"] --> B["Math.max(...data.clicks)"]
B --> C["scaleX: (width / (length - 1)) * index"]
B --> D["scaleY: height - (clicks / maxClicks) * height"]
C --> E["Append Bottom Corners (width,height 0,height)"]
D --> E
E --> F["SVG Polyline with Linear Gradient Fill"]
```
Sources: [apps/web/app/api/og/analytics/route.tsx:236-251](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L236-L251), [apps/web/app/api/og/analytics/route.tsx:268-273](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L268-L273)
> [!TIP]
> To form a closed shape suitable for SVG area fill gradients (`customGradient`), the coordinate mapping appends closing points at `width,height` and `0,height` after mapping each data entry's X and Y coordinates.
```tsx
// Extend the points to the bottom to create a closed shape for the fill
let points = data
.map((d, index) => `${scaleX(index)},${scaleY(d.clicks)}`)
.join(" ");
// Close the shape by drawing a line to the bottom right corner and bottom left corner
points += ` ${width},${height} 0,${height}`;
…
```
Sources: [apps/web/app/api/og/analytics/route.tsx:245-251](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L245-L251), [apps/web/app/api/og/analytics/route.tsx:261-266](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx#L261-L266)
## Partner Program Card Previews
### Affiliate Program and Group Reward Rendering
The Open Graph endpoint at `apps/web/app/api/og/program/route.tsx` serves dynamic program cards by querying Prisma for a specific program slug and partner group. If the group parameter is omitted, it falls back to `DEFAULT_PARTNER_GROUP.slug`. It extracts branding metadata, including `logo`, `wordmark`, and `brandColor` (defaulting to `#000000`), alongside [reward rules](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/reward-rules) mapped via `serializeReward`.
```tsx
// GET /api/og/program?slug=program&groupSlug=group
export async function GET(req: NextRequest) {
const slug = req.nextUrl.searchParams.get("slug");
const groupSlug = req.nextUrl.searchParams.get("groupSlug");
if (!slug) {
return new Response("Missing 'slug' parameter", {
status: 400,
});
}
const [interSemibold, program] = await Promise.all([
loadGoogleFont("Inter:wght@600"),
prisma.program.findUnique({
where: {
slug,
},
include: {
groups: {
where: {
slug: groupSlug ?? DEFAULT_PARTNER_GROUP.slug,
},
include: {
clickReward: true,
saleReward: true,
leadReward: true,
referralReward: true,
},
},
},
}),
]);
if (!program) {
return new Response("Program not found", {
status: 404,
});
}
const group = program.groups[0];
if (!group) {
return new Response("Group not found", {
status: 404,
});
}
const logo = group.wordmark || group.logo;
const brandColor = group.brandColor || "#000000";
const rewards = [group.clickReward, group.leadReward, group.saleReward]
.filter((r): r is Reward => r !== null)
.map(serializeReward);
const reward = rewards[0];
```
Sources: [apps/web/app/api/og/program/route.tsx:18-71](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/route.tsx#L18-L71)
| Parameter / Field | Source / Expression | Purpose |
| :--- | :--- | :--- |
| `slug` | `req.nextUrl.searchParams.get("slug")` | Identifies the target affiliate program in Prisma |
| `groupSlug` | `req.nextUrl.searchParams.get("groupSlug")` | Scopes reward rules to a partner group, falling back to `DEFAULT_PARTNER_GROUP.slug` |
| `logo` | `group.wordmark || group.logo` | Selects brand imagery for the card header |
| `brandColor` | `group.brandColor || "#000000"` | Dynamically styles the badge and CTA button |
| `rewards` | `[group.clickReward, group.leadReward, group.saleReward]` | Filters out null rewards and serializes active structures |
```tsx
const slug = req.nextUrl.searchParams.get("slug");
const groupSlug = req.nextUrl.searchParams.get("groupSlug");
…
const group = program.groups[0];
if (!group) {
return new Response("Group not found", {
status: 404,
});
}
const logo = group.wordmark || group.logo;
const brandColor = group.brandColor || "#000000";
const rewards = [group.clickReward, group.leadReward, group.saleReward]
.filter((r): r is Reward => r !== null)
.map(serializeReward);
const reward = rewards[0];
```
Sources: [apps/web/app/api/og/program/route.tsx:20-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/route.tsx#L20-L21), [apps/web/app/api/og/program/route.tsx:56-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/route.tsx#L56-L70)
> [!CAUTION]
> If either the program or the targeted partner group cannot be located in the database, the route immediately terminates by returning a plain `Response` with status `404` and text `'Program not found'` or `'Group not found'`.
```tsx
if (!program) {
return new Response("Program not found", {
status: 404,
});
}
const group = program.groups[0];
if (!group) {
return new Response("Group not found", {
status: 404,
});
}
```
Sources: [apps/web/app/api/og/program/route.tsx:50-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/route.tsx#L50-L62)
### Program Marketplace Discovery Categories
The category Open Graph endpoint at `apps/web/app/api/og/program/categories/route.tsx` generates discovery cards for vertical categories using `PROGRAM_CATEGORIES`. It verifies the presence of the `categorySlug` query parameter and performs a case-insensitive match against category identifiers.
```tsx
// 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,
});
}
```
Sources: [apps/web/app/api/og/program/categories/route.tsx:14-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/categories/route.tsx#L14-L32)
| Parameter / Variable | Source / Condition | Purpose |
| :--- | :--- | :--- |
| `categorySlug` | `req.nextUrl.searchParams.get("categorySlug")` | Required query string parameter identifying the category |
| Missing Slug | `!categorySlug` | Returns `400` status with `"Missing 'categorySlug' parameter"` |
| Unknown Category | `!category` | Returns `404` status with `"Category not found"` |
| Font Payload | `loadGoogleFont("Inter:wght@600")` | Loads semibold font weights for ImageResponse rendering |
```tsx
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");
```
Sources: [apps/web/app/api/og/program/categories/route.tsx:16-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/categories/route.tsx#L16-L34)
> [!NOTE]
> Both image generation routes utilize an absolute SVG background layer configured with 20px and 160px grid patterns, linear gradients, and predefined coordinate offsets from the `DARK_CELLS` array `[[2, 3], [5, 3], [56, 7], [53, 1]]` rendered at 2% black opacity.
```tsx
const DARK_CELLS = [
[2, 3],
[5, 3],
[56, 7],
[53, 1],
];
…
{DARK_CELLS.map(([x, y]) => (
))}
```
Sources: [apps/web/app/api/og/program/categories/route.tsx:7-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/categories/route.tsx#L7-L12), [apps/web/app/api/og/program/categories/route.tsx:43-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/categories/route.tsx#L43-L91)
## Link Preview Builder UI
### Interactive Preview Components and State Management
The link preview builder interface relies on client-side state management through `react-hook-form` and dedicated provider contexts to let users modify Open Graph card assets interactively. The core `LinkPreview` component registers multiple social platform tabs including Default, X/Twitter, LinkedIn, and Facebook, each mapping to specialized preview subcomponents that render title, description, and asset domains.
```tsx
const tabs = ["default", "x", "linkedin", "facebook"] as const;
type Tab = (typeof tabs)[number];
const tabTitles: Record
= {
default: "Default",
facebook: "Facebook",
linkedin: "LinkedIn",
x: "X/Twitter",
};
const tabIcons: Record = {
default: GlobePointer,
x: Twitter,
linkedin: LinkedIn,
facebook: Facebook,
};
type OGPreviewProps = PropsWithChildren<{
title: string | null;
description: string | null;
hostname: string | null;
password: string | null;
}>;
const tabComponents: Record> = {
default: DefaultOGPreview,
x: XOGPreview,
linkedin: LinkedInOGPreview,
```
Sources: [apps/web/ui/links/link-builder/link-preview.tsx:44-71](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/links/link-builder/link-preview.tsx#L44-L71)
| Tab Key | Component | Icon | Purpose |
| :--- | :--- | :--- | :--- |
| `default` | `DefaultOGPreview` | `GlobePointer` | Standard Open Graph rendering layout |
| `x` | `XOGPreview` | `Twitter` | Platform preview for X (Twitter) cards |
| `linkedin` | `LinkedInOGPreview` | `LinkedIn` | Platform preview for LinkedIn share posts |
| `facebook` | `FacebookOGPreview` | `Facebook` | Platform preview for Facebook link attachments |
```tsx
const tabTitles: Record = {
default: "Default",
facebook: "Facebook",
linkedin: "LinkedIn",
x: "X/Twitter",
};
const tabIcons: Record = {
default: GlobePointer,
x: Twitter,
linkedin: LinkedIn,
facebook: Facebook,
};
type OGPreviewProps = PropsWithChildren<{
title: string | null;
description: string | null;
hostname: string | null;
password: string | null;
}>;
const tabComponents: Record> = {
default: DefaultOGPreview,
x: XOGPreview,
linkedin: LinkedInOGPreview,
```
Sources: [apps/web/ui/links/link-builder/link-preview.tsx:47-71](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/links/link-builder/link-preview.tsx#L47-L71)
> [!NOTE]
> Whenever a user modifies the metadata title or description inside any preview card tab on a non-free workspace plan, the form handler automatically updates the `proxy` boolean flag to `true`, ensuring custom overrides take precedence over the destination URL's native metatags.
```tsx
if (plan && plan !== "free") {
setValue("proxy", true, { shouldDirty: true });
}
…
if (plan && plan !== "free") {
setValue("proxy", true, { shouldDirty: true });
}
…
if (plan && plan !== "free") {
setValue("proxy", true, { shouldDirty: true });
}
…
if (plan && plan !== "free") {
setValue("proxy", true, { shouldDirty: true });
}
```
Sources: [apps/web/ui/links/link-builder/link-preview.tsx:310-312](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/links/link-builder/link-preview.tsx#L310-L312), [apps/web/ui/links/link-builder/link-preview.tsx:323-325](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/links/link-builder/link-preview.tsx#L323-L325), [apps/web/ui/links/link-builder/link-preview.tsx:357-359](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/links/link-builder/link-preview.tsx#L357-L359), [apps/web/ui/links/link-builder/link-preview.tsx:370-372](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/links/link-builder/link-preview.tsx#L370-L372)
## Related
- [Link Dispatch](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/link-attribution/link-dispatch)
- [Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs)
---
## Technical docs: Tinybird Analytics
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/analytics/get-analytics.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/get-analytics.ts)
- [apps/web/lib/postback/record-postback-event.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/record-postback-event.ts)
- [apps/web/app/ee/api/track/visit/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/visit/route.ts)
- [apps/web/lib/tinybird/record-click.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts)
- [apps/web/app/api/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts)
- [apps/web/app/ee/api/track/application/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts)
- [apps/web/lib/tinybird/record-webhook-event.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-webhook-event.ts)
- [apps/web/scripts/tinybird/get-sale-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/get-sale-events.ts)
- [apps/web/lib/postback/get-postback-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/get-postback-events.ts)
- [apps/web/app/api/og/analytics/route.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx)
- [apps/web/lib/tinybird/get-customer-events-tb.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-customer-events-tb.ts)
- [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts)
- [apps/web/lib/tinybird/record-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-lead.ts)
- [apps/web/lib/tinybird/get-lead-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-lead-events.ts)
- [apps/web/lib/tinybird/record-click-zod.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click-zod.ts)
- [apps/web/lib/tinybird/record-sale.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-sale.ts)
- [apps/web/lib/tinybird/record-link.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-link.ts)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/lib/analytics/get-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/get-events.ts)
- [apps/web/lib/tinybird/client.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/client.ts)
- [apps/web/lib/tinybird/log-import-error.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/log-import-error.ts)
- [apps/web/scripts/dub-wrapped.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dub-wrapped.ts)
- [apps/web/lib/tinybird/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/index.ts)
- [apps/web/scripts/tinybird/delete-links.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/delete-links.ts)
- [apps/web/lib/tinybird/get-click-event.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-click-event.ts)
- [apps/web/ui/analytics/events/example-data.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/events/example-data.ts)
- [apps/web/lib/tinybird/get-webhook-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-webhook-events.ts)
- [apps/web/lib/tinybird/get-top-links-by-countries.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-top-links-by-countries.ts)
- [apps/web/lib/upstash/redis-streams/workspace-click-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-click-events.ts)
- [apps/web/scripts/tinybird/update-click-event.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/update-click-event.ts)
## Overview
Dub leverages Tinybird as its underlying real-time analytics and event streaming backbone to ingest, process, and query millions of click, lead, sale, webhook, and visit telemetry events. By utilizing the `@chronark/zod-bird` client library, the system coordinates low-latency data pipelines that feed high-performance parameterized pipe endpoints. These endpoints power dynamic analytical reporting, workspace metrics aggregations, and raw event lookups across distributed workloads.
Sources: [apps/web/lib/tinybird/client.ts:1-6](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/client.ts#L1-L6), [apps/web/lib/tinybird/record-click-zod.ts:1-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click-zod.ts#L1-L42)
## Tinybird Client Setup and Ingestion Endpoints
### Client Instantiation and Configuration
The Tinybird client is initialized using the `@chronark/zod-bird` package. The client instance `tb` requires two environment variables for authentication and connection targeting: `TINYBIRD_API_KEY` for authorization and `TINYBIRD_API_URL` for the API base URL.
```typescript
import { Tinybird } from "@chronark/zod-bird";
export const tb = new Tinybird({
token: process.env.TINYBIRD_API_KEY as string,
baseUrl: process.env.TINYBIRD_API_URL as string,
});
```
Sources: [apps/web/lib/tinybird/client.ts:1-6](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/client.ts#L1-L6)
> [!NOTE]
> The `tb` client export serves as the foundation for building ingest endpoints and pipes across all data streams, including click tracking, lead submissions, and link synchronizations.
Sources: [apps/web/lib/tinybird/client.ts:3-5](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/client.ts#L3-L5), [apps/web/lib/tinybird/index.ts:1-8](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/index.ts#L1-L8)
### Ingestion Endpoints and Schemas
Ingestion pipelines define schemas using `zod/v4` to validate event payloads before pushing them to Tinybird data sources. For example, the click recording endpoint validates input objects against `recordClickZodSchema` and targets the `dub_click_events` datasource with `wait: true`.
```typescript
export const recordClickZod = tb.buildIngestEndpoint({
datasource: "dub_click_events",
event: recordClickZodSchema,
wait: true,
});
```
Sources: [apps/web/lib/tinybird/record-click-zod.ts:39-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click-zod.ts#L39-L42)
| Endpoint Constant | Tinybird Datasource | Description |
| :--- | :--- | :--- |
| `recordClickZod` | `dub_click_events` | Ingests validated click events with `wait: true` |
| `recordPostbackEvent` | `dub_postback_events` | Ingests postback event telemetry |
| `recordWebhookEvent` | `dub_webhook_events` | Ingests webhook delivery event logs |
| `recordLead` / `recordLeadWithTimestamp` | `dub_lead_events` | Ingests conversion lead events |
| `recordSale` / `recordSaleWithTimestamp` | `dub_sale_events` | Ingests conversion sale events |
| `logImportError` | `dub_import_error_logs` | Logs data import errors |
Sources: [apps/web/lib/postback/record-postback-event.ts:4-7](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/record-postback-event.ts#L4-L7), [apps/web/lib/tinybird/record-webhook-event.ts:4-7](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-webhook-event.ts#L4-L7), [apps/web/lib/tinybird/record-lead.ts:5-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-lead.ts#L5-L14), [apps/web/lib/tinybird/record-sale.ts:5-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-sale.ts#L5-L14), [apps/web/lib/tinybird/log-import-error.ts:4-7](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/log-import-error.ts#L4-L7)
## Click and Interaction Ingestion Pipeline
### Request Validation and Filtering
Incoming requests to record a click pass through `recordClick`, which verifies the presence of a `clickId` and checks request headers or query parameters for `dub-no-track`. Except when the trigger is set to `"deeplink"`, bot detection executes via `detectBot(req)`; requests identified as bots are immediately discarded.
```typescript
export async function recordClick({
req,
clickId,
workspaceId,
linkId,
domain,
key,
url,
programId,
partnerId,
skipRatelimit,
timestamp,
referrer,
trigger = "link",
shouldCacheClickId,
}: {
req: Request;
clickId?: string;
linkId: string;
workspaceId?: string;
domain: string;
key: string;
url?: string;
programId?: string;
partnerId?: string;
skipRatelimit?: boolean;
timestamp?: string;
referrer?: string;
trigger?: string;
shouldCacheClickId?: boolean;
}) {
if (!clickId) {
return null;
}
const searchParams = new URL(req.url).searchParams;
if (req.headers.has("dub-no-track") || searchParams.has("dub-no-track")) {
return null;
}
const ua = userAgent(req);
if (trigger !== "deeplink") {
const isBot = detectBot(req);
if (isBot) {
console.log(`Click not recorded ❌ – Bot detected.`, {
ua,
isBot,
});
return null;
}
}
```
Sources: [apps/web/lib/tinybird/record-click.ts:22-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts#L22-L78)
> [!WARNING]
> Bot checks are deliberately bypassed when `trigger` evaluates to `"deeplink"`, allowing deep link interactions to bypass standard client filtering rules.
### Metadata Enrichment and Deduplication
After passing initial filters, the pipeline computes an identity hash. Unless `skipRatelimit` is enabled, it queries `recordClickCache` to prevent duplicate clicks from the same IP address and domain/key pair within a one-hour window. QR code detection runs via `detectQr(req)`, shifting the trigger type to `"qr"` if matched. Geolocation extracts continent and country-region headers on Vercel deployments, while falling back to `LOCALHOST_GEO_DATA` and `LOCALHOST_IP` locally. IP addresses belonging to EU country codes (`EU_COUNTRY_CODES`) are scrubbed to preserve privacy compliance.
```typescript
const identityHash = await getIdentityHash(req);
if (!skipRatelimit) {
try {
const cachedClickId = await recordClickCache.get({
domain,
key,
identityHash,
});
if (cachedClickId) {
return null;
}
} catch (error) {
console.error(`[recordClickCache error]: ${error}`);
return null;
}
}
const isQr = detectQr(req);
if (isQr) {
trigger = "qr";
}
const { continent, region } =
process.env.VERCEL === "1"
? {
continent: req.headers.get("x-vercel-ip-continent"),
region: req.headers.get("x-vercel-ip-country-region"),
}
: LOCALHOST_GEO_DATA;
const geo =
process.env.VERCEL === "1" ? geolocation(req) : LOCALHOST_GEO_DATA;
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
const isEuCountry = geo.country && EU_COUNTRY_CODES.includes(geo.country);
```
Sources: [apps/web/lib/tinybird/record-click.ts:80-123](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts#L80-L123)
### Dual Redis Stream Fanout and Tinybird Ingestion
Asynchronously via `waitUntil`, the constructed click payload is sent to Tinybird's event ingestion endpoint (`dub_click_events`), recorded in the rate limit cache for one hour, and fanned out concurrently to two distinct Upstash Redis streams: `publishLinkClickEvent` and `publishWorkspaceClickEvent`.
```typescript
fetchWithRetry(
`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
},
body: JSON.stringify(clickData),
},
).then((res) => res.json()),
recordClickCache.set({
domain,
key,
identityHash,
clickId,
}),
publishLinkClickEvent({
linkId,
timestamp: clickData.timestamp,
...(workspaceId && url && { workspaceId }),
...(programId && partnerId && { programId, partnerId }),
}),
publishWorkspaceClickEvent(clickData),
```
Sources: [apps/web/lib/tinybird/record-click.ts:172-199](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts#L172-L199)
Workspace click events undergo schema validation via `clickEventSchemaTB`, converting boolean flags `qr` and `bot` into numeric representations before pushing to the `workspace:click:events` stream if the workspace has active link-click webhooks configured.
```typescript
export const workspaceClickEventStream = new RedisStream(STREAM_KEY);
export const publishWorkspaceClickEvent = async (event) => {
try {
const parsedEvent = clickEventSchemaTB.parse({
...event,
qr: Number(event.qr),
bot: Number(event.bot),
});
const hasLinkClickedWebhooks = await clickWebhookWorkspaces.has(
parsedEvent.workspace_id,
);
if (!hasLinkClickedWebhooks) {
return;
}
return await redis.xadd(STREAM_KEY, "*", parsedEvent);
} catch (error) {
logger.error("stream.publish_failed", {
service: "upstash",
streamKey: STREAM_KEY,
error: toErrorFields(error),
correlation: {
workspaceId: event.workspace_id,
clickId: event.click_id,
linkId: event.link_id,
},
});
await logger.flush();
throw error;
}
};
```
Sources: [apps/web/lib/upstash/redis-streams/workspace-click-events.ts:9-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-click-events.ts#L9-L44)
> [!NOTE]
> If `shouldCacheClickId` is enabled during ingestion, the click data is explicitly stored under `clickIdCache:${clickId}` in Redis with a 5-minute expiration to bridge the latency gap before ingested rows become available directly in Tinybird queries.
## Link Metadata Synchronization
### Payload Transformation and Ingestion
The link metadata synchronization subsystem records and updates link dimensions, casing normalization, and domain parameters into Tinybird datasources. Link synchronization is handled by the `recordLink` utility function, which transforms expanded link objects and pushes them into the `dub_links_metadata` Tinybird datasource.
Before records are dispatched to Tinybird, the `transformLinkTB` function maps an `ExpandedLink` entity into the schema shape required by `dub_links_metadata`. It extracts tag associations into flat string arrays, maps program enrollments to group identifiers and partner tag collections, and binds project identifiers to `workspace_id`.
```typescript
const transformLinkTB = (link: ExpandedLink) => {
const key = decodeKeyIfCaseSensitive({
domain: link.domain,
key: link.key,
});
return {
link_id: link.id,
domain: link.domain,
key,
url: link.url,
tag_ids: link.tags?.map(({ tag }) => tag.id) ?? [],
folder_id: link.folderId ?? "",
tenant_id: link.tenantId ?? "",
program_id: link.programId ?? "",
partner_id: link.partnerId ?? "",
partner_group_id: link.programEnrollment?.groupId ?? "",
partner_tag_ids:
link.programEnrollment?.programPartnerTags?.map(
({ partnerTagId }) => partnerTagId,
) ?? [],
workspace_id: link.projectId,
created_at: link.createdAt,
};
};
```
Sources: [apps/web/lib/tinybird/record-link.ts:52-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-link.ts#L52-L76)
The top-level `recordLink` function accepts either a single `ExpandedLink` or an array of links. When an array is provided, it maps each item through `transformLinkTB` and appends the `deleted` flag before invoking the ingestion endpoint with `wait: true`.
```typescript
export const recordLink = async (
payload: ExpandedLink | ExpandedLink[],
{ deleted }: { deleted?: boolean } = {},
) => {
if (Array.isArray(payload)) {
return await recordLinkTB(
payload.map(transformLinkTB).map((p) => ({ ...p, deleted })),
);
} else {
return await recordLinkTB({ ...transformLinkTB(payload), deleted });
}
};
```
Sources: [apps/web/lib/tinybird/record-link.ts:78-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-link.ts#L78-L89)
> [!NOTE]
> The `key` field undergoes case-sensitivity checks via `decodeKeyIfCaseSensitive` during transformation to preserve correct link routing rules across case-sensitive domains.
### Domain Transfer Deletion Scripts
Administrative maintenance tasks, such as handling domain transfers or purging metadata associated with specific domains, invoke Tinybird REST deletion endpoints via authenticated HTTP POST requests. The deletion script targets multiple datasources simultaneously using `Promise.allSettled`.
| Target Tinybird Datasource | Deletion Condition Source | HTTP Method & Auth |
| :--- | :--- | :--- |
| `dub_links_metadata` | `domain = 'xyz'` | POST, Bearer Token (`TINYBIRD_API_KEY`) |
| `dub_links_metadata_latest` | `domain = 'xyz'` | POST, Bearer Token (`TINYBIRD_API_KEY`) |
| `dub_regular_links_metadata_latest` | `domain = 'xyz'` | POST, Bearer Token (`TINYBIRD_API_KEY`) |
```typescript
const deleteCondition = "domain = 'xyz'";
// delete data from tinybird
const deleteRes = await Promise.allSettled([
deleteData({
dataSource: "dub_links_metadata",
deleteCondition,
}),
deleteData({
dataSource: "dub_links_metadata_latest",
deleteCondition,
}),
deleteData({
dataSource: "dub_regular_links_metadata_latest",
deleteCondition,
}),
]);
console.log(deleteRes);
}
```
Sources: [apps/web/scripts/tinybird/delete-links.ts:5-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/delete-links.ts#L5-L23)
The underlying `deleteData` utility constructs URL-encoded bodies containing `delete_condition` parameters and communicates with Tinybird's US-East API region.
```typescript
const deleteData = async ({
dataSource,
deleteCondition,
}: {
dataSource: string;
deleteCondition: string;
}) => {
return fetch(
`https://api.us-east.tinybird.co/v0/datasources/${dataSource}/delete`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: `delete_condition=${deleteCondition}`,
},
).then((res) => res.json());
};
```
Sources: [apps/web/scripts/tinybird/delete-links.ts:25-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/delete-links.ts#L25-L43)
> [!CAUTION]
> Deletion operations executed against Tinybird datasources via `delete_condition` permanently remove matching rows across the specified metadata views and cannot be undone.
## Analytics Pipe Query Processing
### Parameterized Analytics Pipelines
Query execution for timeseries metrics, aggregated link counts, and country statistics relies on parameterized Tinybird pipe endpoints built dynamically via `@chronark/zod-bird`. The `getAnalytics` function inspects input criteria such as grouping parameters and event types to select the matching version 4 pipe (`v4_count`, `v4_timeseries`, `v4_group_by_link_metadata`, or `v4_group_by`). Pipe inputs are validated against `analyticsFilterTB` parameters, returning structured analytics records containing dynamic groupBy fields, clicks, leads, sales, and sale amounts.
```typescript
const pipe = tb.buildPipe({
pipe: ["count", "timeseries"].includes(groupBy!)
? `v4_${groupBy}`
: [
"top_folders",
"top_link_tags",
"top_domains",
"top_partners",
"top_partner_tags",
"top_groups",
].includes(groupBy!)
? "v4_group_by_link_metadata"
: "v4_group_by",
parameters: analyticsFilterTB,
data: z.object({
groupByField: z.string(),
clicks: z.number().default(0),
leads: z.number().default(0),
sales: z.number().default(0),
saleAmount: z.number().default(0),
// only for cities and regions groupBy
country: z.string().optional(),
region: z.string().optional(),
}),
});
```
Sources: [apps/web/lib/analytics/get-analytics.ts:98-123](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/get-analytics.ts#L98-L123)
When querying country metrics for specific link sets, dedicated helper pipes such as `v3_group_by_link_country` process array filters for `linkIds` alongside formatted date ranges to return granular click distributions per country code.
```typescript
const getTopLinksByCountriesTB = tb.buildPipe({
pipe: "v3_group_by_link_country",
parameters: inputSchema,
data: responseSchema,
});
```
Sources: [apps/web/lib/tinybird/get-top-links-by-countries.ts:18-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-top-links-by-countries.ts#L18-L22)
> [!NOTE]
> Queries requesting all-time click metrics with a count interval and no supplemental dimensional filters bypass Tinybird pipes entirely, querying relational tables directly via PlanetScale SQL execution.
### Filter Assembly and Transformation
Parameters collected from API requests are transformed into serialized query requirements before hitting Tinybird endpoints. Advanced filter predicates, metadata query strings, and date boundaries formatted for ClickHouse are bundled into the `tinybirdParams` payload alongside explicit operator flags.
| Tinybird Parameter | Source Property | Description |
| :--- | :--- | :--- |
| `workspaceId` | `params.workspaceId` | Target workspace identifier for isolation |
| `groupBy` | `groupBy` | Dimension used to aggregate click and conversion metrics |
| `eventType` | `event` | Metric category (`clicks`, `leads`, `sales`, `saleAmount`, `composite`) |
| `start` | `startDate` | Start timestamp formatted via `formatUTCDateTimeClickhouse` |
| `end` | `endDate` | End timestamp formatted via `formatUTCDateTimeClickhouse` |
| `granularity` | `granularity` | Time bucket resolution (`minute`, `hour`, `day`, `month`) |
| `timezone` | `timezone` | Target timezone string defaulting to `"UTC"` |
| `filters` | `allFilters` | Serialized JSON array combining metadata and advanced criteria |
```typescript
const tinybirdParams: any = {
workspaceId,
customerId: params.customerId,
programId: params.programId,
partnerId: partnerIdParam,
partnerIdOperator,
partnerTagId: partnerTagIdParam,
partnerTagIdOperator,
tenantId: tenantIdParam,
tenantIdOperator,
groupId: groupIdParam,
groupIdOperator,
linkId: linkIdParam,
linkIdOperator,
domain: domainParam,
domainOperator,
folderId: folderIdParam,
folderIdOperator,
tagId: tagIdParam,
tagIdOperator,
groupBy,
eventType: event,
start: formatUTCDateTimeClickhouse(startDate),
end: formatUTCDateTimeClickhouse(endDate),
granularity,
timezone,
region: typeof regionForPipe === "string" ? regionForPipe : undefined,
root: params.root,
saleType: params.saleType,
filters: allFilters.length > 0 ? JSON.stringify(allFilters) : undefined,
};
```
Sources: [apps/web/lib/analytics/get-analytics.ts:164-194](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/get-analytics.ts#L164-L194)
> [!TIP]
> When executing batch analytical scripts such as `dub-wrapped.ts`, parallelized helper calls to `getAnalytics` aggregate top links and country breakdowns simultaneously across year-to-date intervals without blocking execution flow.
```typescript
const payloads = await Promise.all(
data.map(async ({ projectId, _count, _sum }) => {
const [topLinks, topCountries] = (await Promise.all([
getAnalytics({
workspaceId: projectId!,
event: "clicks",
groupBy: "top_links",
interval: "ytd",
root: false,
}),
getAnalytics({
workspaceId: projectId!,
event: "clicks",
groupBy: "countries",
interval: "ytd",
}),
])) as [AnalyticsTopLinks[], AnalyticsCountries[]];
return {
year: 2024,
workspaceId: projectId!,
totalLinks: _count.id,
totalClicks: _sum.clicks ?? 0,
topLinks: topLinks.slice(0, 5).map(({ domain, key, clicks }) => ({
item: `${domain}/${key}`,
count: clicks,
})),
topCountries: topCountries.slice(0, 5).map(({ country, clicks }) => ({
item: country,
count: clicks,
})),
};
}),
);
```
Sources: [apps/web/scripts/dub-wrapped.ts:56-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dub-wrapped.ts#L56-L89)
## Raw Event Queries and Lookups
### Event Retrieval Pipes and Functions
Dub queries raw, individual records by leveraging specialized Tinybird pipe wrappers and direct data source operations. Individual click records are fetched via `getClickEvent`, which checks a Redis cache first under `clickIdCache:${clickId}` before falling back to the `get_click_event` Tinybird pipe. Conversion and telemetry events use similar parameterized pipes: `getLeadEvents` queries lead records filtered by an array of customer identifiers, `getSaleEvents` targets internal sale records for a specific customer ID, `getPostbackEvents` retrieves postback logs by postback ID, and `getWebhookEvents` queries webhook dispatch history by webhook identifier.
```typescript
const getClickEventTB = tb.buildPipe({
pipe: "get_click_event",
parameters: z.object({
clickId: z.string(),
}),
data: clickEventSchemaTB,
});
```
Sources: [apps/web/lib/tinybird/get-click-event.ts:7-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-click-event.ts#L7-L13)
| Pipe Function | Tinybird Pipe Name | Parameter Schema | Data Output Schema |
| :--- | :--- | :--- | :--- |
| `getClickEventTB` | `get_click_event` | `clickId: z.string()` | `clickEventSchemaTB` |
| `getLeadEvents` | `get_lead_events` | `customerIds: z.string().array()` | `leadEventSchemaTB` |
| `getSaleEvents` | `internal_get_sale_events` | `customerId: z.string()` | `z.any()` |
| `getPostbackEvents` | `get_postback_events` | `postbackId: z.string()` | `postbackEventOutputSchemaTB` |
| `getWebhookEvents` | `get_webhook_events` | `webhookId: z.string()` | `webhookEventSchemaTB` |
| `getCustomerEventsTB` | `v2_customer_events` | `z.any()` | `z.any()` |
Sources: [apps/web/scripts/tinybird/get-sale-events.ts:4-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/get-sale-events.ts#L4-L10), [apps/web/lib/postback/get-postback-events.ts:5-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/get-postback-events.ts#L5-L11), [apps/web/lib/tinybird/get-customer-events-tb.ts:4-8](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-customer-events-tb.ts#L4-L8), [apps/web/lib/tinybird/get-lead-events.ts:5-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-lead-events.ts#L5-L10), [apps/web/lib/tinybird/get-click-event.ts:7-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-click-event.ts#L7-L13), [apps/web/lib/tinybird/get-webhook-events.ts:5-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-webhook-events.ts#L5-L11)
> [!NOTE]
> The `getCustomerEventsTB` wrapper delegates directly to the `v2_customer_events` pipe, dynamically appending `linkIds` and `limit` parameters when provided alongside the required `customerId`.
```typescript
export const getCustomerEventsTB = async ({
customerId,
linkIds,
limit,
}: {
customerId: string;
linkIds?: string[];
limit?: number;
}) => {
return await pipe({
customerId,
...(linkIds ? { linkIds } : {}),
...(limit ? { limit } : {}),
});
};
```
Sources: [apps/web/lib/tinybird/get-customer-events-tb.ts:10-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/get-customer-events-tb.ts#L10-L23)
### Unified Event Feeds and Modification Scripts
The `getEvents` function queries the `v4_events` pipe to unify retrieval across click, lead, and sale event types. It builds complex criteria arrays by parsing metadata queries and advanced filters, mapping workspace link filters with operators, and resolving relational data from Prisma for associated links and customers.
```typescript
const pipe = tb.buildPipe({
pipe: "v4_events",
parameters: eventsFilterTB,
data:
{
clicks: clickEventSchemaTBEndpoint,
leads: leadEventSchemaTBEndpoint,
sales: saleEventSchemaTBEndpoint,
}[eventType] ?? clickEventSchemaTBEndpoint,
});
```
Sources: [apps/web/lib/analytics/get-events.ts:77-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/get-events.ts#L77-L86)
> [!CAUTION]
> When updating raw click event properties via administrative scripts, modifications require pushing the amended JSON payload to the `dub_click_events` data source with `wait=true` while concurrently executing targeted deletions against both `dub_click_events_mv` and `dub_click_events_id` datasources using explicit `delete_condition` parameters.
```typescript
const deleteData = async ({
dataSource,
clickId,
columnName,
oldValue,
}: {
dataSource: string;
clickId: string;
columnName: string;
oldValue: string;
}) => {
return fetch(
`https://api.us-east.tinybird.co/v0/datasources/${dataSource}/delete`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: `delete_condition=click_id='${clickId}' and ${columnName}='${oldValue}'`,
},
).then((res) => res.json());
};
```
Sources: [apps/web/scripts/tinybird/update-click-event.ts:53-75](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/tinybird/update-click-event.ts#L53-L75)
## Stream Consumption and Aggregation Cron
### Batch Processing and Aggregation Constants
The background cron route defined in `apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts` manages stream ingestion from Upstash Redis streams into relational storage. Constants govern batch sizes, concurrency thresholds, and distributed execution protection.
| Constant Name | Value | Purpose |
| :--- | :--- | :--- |
| `BATCH_SIZE` | `10_000` | Maximum stream entries to consume per cron run |
| `SUB_BATCH_SIZE` | `50` | Database updates to run in parallel within each batch |
| `BACKLOG_ALERT_THRESHOLD` | `50_000` | Alert threshold when stream length exceeds this count |
| `BACKLOG_AGE_ALERT_MS` | `300_000` (5 mins) | Alert threshold when oldest pending entry exceeds age |
| `LOCK_KEY` | `lock:update-click-stats` | Redis key preventing concurrent GET/POST double-counting |
| `LOCK_TTL_SECONDS` | `600` | Lock TTL matching cron maxDuration to outlive execution |
Sources: [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:15-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L15-L20)
> [!WARNING]
> The distributed `LOCK_KEY` uses a TTL of `600` seconds to match the maximum cron duration, ensuring that overlapping HTTP requests do not invoke duplicate batch processing cycles that would double-count click stats.
Sources: [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:19-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L19-L20)
### Aggregation and Sub-Batching Architecture
The `aggregateClickStats` function iterates through incoming `RedisStreamEntry[]` objects, isolating metadata to construct grouped maps for links, workspaces, and partner program enrollments. Timestamps are parsed via `Date.parse`, defaulting to `Date.now()` if the value is invalid or non-finite.
```typescript
const aggregateClickStats = (
entries: RedisStreamEntry[],
): {
linkUpdates: LinkAggregate[];
workspaceUpdates: WorkspaceAggregate[];
enrollmentUpdates: EnrollmentAggregate[];
} => {
const links = new Map();
const workspaces = new Map();
const enrollments = new Map();
for (const entry of entries) {
const { linkId, workspaceId, programId, partnerId, timestamp } = entry.data;
if (!linkId) {
continue;
}
const parsedTimestamp = Date.parse(timestamp);
const lastClicked = Number.isFinite(parsedTimestamp)
? parsedTimestamp
: Date.now();
const existingLink = links.get(linkId);
if (existingLink) {
existingLink.clicks += 1;
existingLink.lastClicked = Math.max(
existingLink.lastClicked,
lastClicked,
);
existingLink.entryIds.push(entry.id);
} else {
links.set(linkId, {
linkId,
clicks: 1,
lastClicked,
entryIds: [entry.id],
});
}
if (workspaceId) {
const existingWorkspace = workspaces.get(workspaceId);
if (existingWorkspace) {
existingWorkspace.clicks += 1;
} else {
workspaces.set(workspaceId, {
workspaceId,
clicks: 1,
});
}
}
if (programId && partnerId) {
const key = `${programId}:${partnerId}`;
const existingEnrollment = enrollments.get(key);
if (existingEnrollment) {
existingEnrollment.clicks += 1;
} else {
enrollments.set(key, {
programId,
partnerId,
clicks: 1,
});
}
}
}
return {
linkUpdates: Array.from(links.values()),
workspaceUpdates: Array.from(workspaces.values()),
enrollmentUpdates: Array.from(enrollments.values()),
};
};
```
Sources: [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:40-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L40-L112)
> [!TIP]
> The `processInSubBatches` utility slices accumulated update arrays into chunks defined by `SUB_BATCH_SIZE` and evaluates them using `Promise.allSettled`, tracking successes and isolating errors into a returned failure collection without aborting the broader cron job.
```typescript
const processInSubBatches = async (
items: T[],
handler: (item: T) => Promise<{ success: boolean; error?: unknown }>,
) => {
const errors: unknown[] = [];
let totalProcessed = 0;
for (let i = 0; i < items.length; i += SUB_BATCH_SIZE) {
const batch = items.slice(i, i + SUB_BATCH_SIZE);
const results = await Promise.allSettled(batch.map(handler));
for (const result of results) {
if (result.status === "fulfilled" && result.value.success) {
totalProcessed++;
} else if (result.status === "fulfilled" && result.value.error) {
errors.push(result.value.error);
} else if (result.status === "rejected") {
errors.push(result.reason);
}
}
}
return { totalProcessed, errors };
};
```
Sources: [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:114-137](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L114-L137)
## Related
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
- [Analytics Dashboard](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/analytics-dashboard)
---
## Technical docs: GET Get admin links
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/admingetlinks
## Parameters
## Responses
## Try It
---
## Technical docs: Conversion Tracking
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/api/conversions/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts)
- [apps/web/app/ee/api/track/application/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts)
- [apps/web/lib/api/conversions/track-sale.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts)
- [apps/web/app/ee/api/track/visit/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/visit/route.ts)
- [apps/web/app/ee/api/track/click/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/click/route.ts)
- [apps/web/app/ee/api/appsflyer/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts)
- [apps/web/lib/middleware/link.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts)
- [apps/web/lib/api/customers/reattribute-customer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts)
- [apps/web/app/ee/api/cron/framer/backfill-leads-batch/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/framer/backfill-leads-batch/route.ts)
- [apps/web/lib/api/commissions/create-manual-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/create-manual-commissions.ts)
- [apps/web/app/ee/api/track/lead/client/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/lead/client/route.ts)
- [apps/web/app/ee/api/singular/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts)
- [apps/web/app/ee/api/track/sale/client/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/client/route.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/checkout-session-completed.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts)
- [apps/web/scripts/programs/backfill-reuse-commission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/backfill-reuse-commission.ts)
- [apps/web/app/ee/api/track/lead/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/lead/route.ts)
- [apps/web/app/ee/api/track/sale/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/route.ts)
- [apps/web/lib/integrations/shopify/attribute-via-discount-code.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts)
- [apps/web/lib/auth/track-dub-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/track-dub-lead.ts)
- [apps/web/scripts/programs/3-import-customer-leads.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/3-import-customer-leads.ts)
- [apps/web/lib/integrations/hubspot/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts)
- [apps/web/lib/integrations/singular/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/singular/track-lead.ts)
- [apps/web/lib/tinybird/record-click.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts)
- [apps/web/lib/application-events/mark-application-event-submitted-network.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/application-events/mark-application-event-submitted-network.ts)
- [apps/web/app/ee/api/cron/streams/update-partner-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts)
- [apps/web/lib/integrations/shopify/create-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/create-lead.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts)
- [apps/web/lib/api/partners/sync-partner-links-stats.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/partners/sync-partner-links-stats.ts)
- [apps/web/lib/analytics/is-first-conversion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/is-first-conversion.ts)
- [apps/web/lib/integrations/singular/track-sale.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/singular/track-sale.ts)
## Overview
Dub implements an end-to-end conversion tracking and attribution engine that ingests edge interactions, records customer lead and sale funnels, and dispatches multi-channel commissions and downstream webhooks. It resolves request identities, attributes events across organic links, discount codes, and merchant platforms like Stripe and Shopify, and synchronizes real-time partner performance metrics via Redis streams and analytical storage.
Sources: [apps/web/lib/api/conversions/track-lead.ts:112-162](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L112-L162)
## Edge ingestion for visits and clicks
### Visit and Click Tracking Endpoints
Dub exposes public edge tracking routes to ingest incoming client visits, record link interactions, and verify workspace hostnames against analytics configuration. These endpoints process incoming telemetry from client-side scripts and redirects, validating request parameters and coordinating with caching layers to deduplicate events and enrich click records.
Sources: [apps/web/app/ee/api/track/visit/route.ts:17-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/visit/route.ts#L17-L50)
The visit tracking route at `/api/track/visit` accepts POST requests containing a target domain, URL, and optional referrer. It parses the request body, checks if a click identifier is already cached in Redis via `recordClickCache`, and retrieves link details from edge storage if necessary. If no cached click identifier exists, a new 16-character identifier is generated using `nanoid`.
Sources: [apps/web/app/ee/api/track/visit/route.ts:19-54](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/visit/route.ts#L19-L54)
Similarly, the click tracking route at `/api/track/click` validates incoming payloads against `trackClickSchema`, enforcing domain normalization and presence checks for keys and URLs. It resolves request identity hashes to prevent duplicate logging within hourly windows and evaluates allowed workspace hostnames before recording click telemetry.
Sources: [apps/web/app/ee/api/track/click/route.ts:25-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/click/route.ts#L25-L33)
| Endpoint | Method | Request Schema | Core Action | Sources |
| :--- | :--- | :--- | :--- | :--- |
| `/api/track/visit` | `POST` | `domain`, `url`, `referrer` (optional) | Tracks client-side page views and logs visits | Sources: [apps/web/app/(ee)/api/track/visit/route.ts:17-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/visit/route.ts#L17-L105) |
| `/api/track/click` | `POST` | `domain`, `key`, `url`, `referrer` (optional) | Tracks link clicks, returns partner info and discounts | Sources: [apps/web/app/(ee)/api/track/click/route.ts:25-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/click/route.ts#L25-L55) |
> [!NOTE]
> Requests lacking a domain or URL in the visit route throw a `bad_request` error, while click tracking requests failing hostname verification return a `forbidden` error with configuration guidance.
> Sources: [apps/web/app/(ee)/api/track/visit/route.ts:22-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/visit/route.ts#L22-L27)
### Telemetry Recording and Deduplication
The underlying `recordClick` engine manages geolocation extraction, bot detection, and data ingestion into [Tinybird Analytics](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics). It evaluates request headers to determine user agents, checks for bot traffic unless triggered via deeplinks, and respects `dub-no-track` headers or query parameters to bypass collection.
Sources: [apps/web/lib/tinybird/record-click.ts:53-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts#L53-L78)
```mermaid
flowchart TD
A[Incoming Request] --> B{Check dub-no-track}
B -- Yes --> C[Ignore & Return Null]
B -- No --> D{Trigger === deeplink?}
D -- No --> E{Detect Bot}
E -- Yes --> C
E -- No --> F[Compute Identity Hash]
D -- Yes --> F
F --> G{Rate Limit Check}
G -- Cached --> C
G -- New --> H[Extract Geolocation & User Agent]
H --> I[Dispatch to Tinybird & Upstash Streams]
Sources: [apps/web/lib/tinybird/record-click.ts:59-200](https://github.com/blade47/dub/blob/HEAD/apps/web/lib/tinybird/record-click.ts#L59-L200)
```
> [!WARNING]
> When executing on Vercel, region codes are extracted from `x-vercel-ip-country-region` rather than standard geolocation helpers to ensure accurate sub-national geographic attribution.
> Sources: [apps/web/lib/tinybird/record-click.ts:110-116](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts#L110-L116)
European Union visitors have their IP addresses scrubbed before being recorded in analytics tables to comply with data privacy requirements.
Sources: [apps/web/lib/tinybird/record-click.ts:122-137](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tinybird/record-click.ts#L122-L137)
## Lead capture and attribution pipeline
### Server and Client Tracking Workflows
Lead conversion events are processed through unified server actions and API routes designed for both direct client integrations and authenticated server requests. The core lead processing function `trackLead` handles event intake across multiple execution modes: `wait`, `async`, and `deferred`. Client-side tracking operates via `/api/track/lead/client`, which requires a publishable key and validates incoming request hostnames against the workspace's configured `allowedHostnames`. Server-side tracking takes place via `/api/track/lead`, which authenticates requests through workspace membership cookies or API tokens while supporting legacy payload properties for backwards compatibility.
Sources: [apps/web/app/ee/api/track/lead/route.ts:10-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/lead/route.ts#L10-L36)
```typescript
const {
clickId,
eventName,
eventQuantity,
customerExternalId: newExternalId,
externalId: oldExternalId, // deprecated (but we'll support it for backwards compatibility)
customerId: oldCustomerId, // deprecated (but we'll support it for backwards compatibility)
customerName,
customerEmail,
customerAvatar,
mode,
metadata,
} = trackLeadRequestSchema
.extend({
// we if clickId is undefined/nullish, we'll coerce into an empty string
clickId: z.string().trim().nullish(),
// add backwards compatibility
customerExternalId: z.string().trim().nullish(),
externalId: z.string().trim().nullish(),
customerId: z.string().trim().nullish(),
})
.parse(body);
```
Sources: [apps/web/app/ee/api/track/lead/route.ts:14-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/lead/route.ts#L14-L35)
```typescript
if (!isDuplicateEvent) {
// First, we need to find the click event
const clickData = await getClickEvent({ clickId });
// if there is no click data, throw an error
if (!clickData) {
throw new DubApiError({
code: "not_found",
message: `Click event not found for clickId: ${clickId}`,
});
}
```
Sources: [apps/web/lib/api/conversions/track-lead.ts:111-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L111-L122)
> [!WARNING]
> If a click identifier fails to resolve to a valid, enabled link owned by the target workspace, `trackLead` throws a `not_found` DubApiError and halts lead registration.
> Sources: [apps/web/lib/api/conversions/track-lead.ts:115-149](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L115-L149)
### Customer Resolution and Deduplication
Incoming leads are verified against Redis cache layers to prevent duplicate processing within a 7-week window by testing keys against `clickId`, `eventName`, and `customerExternalId`. When an event is new, the system queries click data and validates link ownership before provisioning or fetching customer records via `getOrCreateCustomer`. For authenticated Next.js users, `trackDubLead` extracts the `dub_id` cookie, submits a sign-up lead event with user metadata, and subsequently clears the tracking cookies.
Sources: [apps/web/lib/api/conversions/track-lead.ts:91-106](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L91-L106)
```typescript
export const trackDubLead = async (user: User) => {
const cookieStore = await cookies();
const clickId = cookieStore.get("dub_id")?.value;
if (!clickId) {
console.log("No dub_id cookie found, skipping lead tracking...");
return;
}
// send the lead event to Dub
await dub.track.lead({
clickId,
eventName: "Sign Up",
customerExternalId: user.id,
customerName: user.name,
customerEmail: user.email,
customerAvatar: user.image,
});
```
Sources: [apps/web/lib/auth/track-dub-lead.ts:5-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/track-dub-lead.ts#L5-L23)
```typescript
if (!customer) {
const { customer: existingOrNewCustomer } = await getOrCreateCustomer({
where: {
projectId_externalId: {
projectId: workspace.id,
externalId: customerExternalId,
},
},
create: {
id: finalCustomerId,
name: finalCustomerName,
email: customerEmail,
avatar: finalCustomerAvatar,
externalId: customerExternalId,
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
clickId: clickData.click_id,
linkId: link.id,
programId: link.programId,
partnerId: link.partnerId,
country: clickData.country,
clickedAt: new Date(clickData.timestamp + "Z"),
},
});
customer = existingOrNewCustomer;
}
```
Sources: [apps/web/lib/api/conversions/track-lead.ts:174-200](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L174-L200)
> [!TIP]
> In `wait` execution mode, lead event payloads are cached in Redis for 5 minutes under keys scoped to both customer ID and specific event names to bridge telemetry read-after-write delays from [Tinybird Analytics](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics).
> Sources: [apps/web/lib/api/conversions/track-lead.ts:203-224](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L203-L224)
### Third-Party Integrations and Webhook Delivery
Lead attribution extends to external merchant platforms like HubSpot, where `trackHubSpotLeadEvent` maps contact creations, property changes, and deal stage transitions into conversion events. When HubSpot objects meet criteria such as lifecycle stage progression or deal creation, deferred or asynchronous leads are recorded, and corresponding contact properties (`dub_link` and `dub_partner_email`) are updated back on HubSpot.
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:25-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L25-L32)
```typescript
if (objectTypeId === "0-1" && subscriptionType === "object.creation") {
const contactInfo = await hubSpotApi.getContact(objectId);
if (!contactInfo) {
return `No contact info found for contact ${objectId}.`;
}
const { properties } = contactInfo;
if (!properties.dub_id) {
return `No dub_id found for contact ${objectId}.`;
}
const customerName =
[properties.firstname, properties.lastname].filter(Boolean).join(" ") ||
null;
const trackLeadResult = await trackLead({
clickId: properties.dub_id,
eventName: "Sign up",
customerEmail: properties.email,
customerExternalId: properties.email,
customerName,
mode: "deferred",
workspace,
source: "hubspot",
commissionSource: CommissionSource.hubspot,
});
if (trackLeadResult) {
await updateHubSpotContact({
contact: contactInfo,
trackLeadResult,
hubSpotApi,
});
}
return `Deferred lead tracked for contact ${objectId}.`;
}
```
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:34-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L34-L72)
```typescript
export const updateHubSpotContact = async ({
hubSpotApi,
contact,
trackLeadResult,
}: {
hubSpotApi: HubSpotApi;
contact: HubSpotContact;
trackLeadResult: TrackLeadResponse;
}) => {
if (contact.properties.dub_link && contact.properties.dub_partner_email) {
console.log(
`[HubSpot] Contact ${contact.id} already has dub_link and dub_partner_email. Skipping update.`,
);
return;
}
const properties: Record = {};
if (trackLeadResult.link?.partnerId) {
const partner = await prisma.partner.findUniqueOrThrow({
where: {
id: trackLeadResult.link.partnerId,
},
select: {
email: true,
},
});
if (partner.email) {
properties["dub_partner_email"] = partner.email;
}
}
if (trackLeadResult.link?.shortLink) {
properties["dub_link"] = trackLeadResult.link.shortLink;
}
```
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:251-287](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L251-L287)
## Sale tracking and first conversion detection
### Sale Event Ingestion and Currency Normalization
Sale conversions are ingested via dedicated server-side endpoints and client-side publishable key routes. The primary server route `/api/track/sale` authenticates via workspace membership, parses requests using `trackSaleRequestSchema`, and handles legacy parameters with backwards compatibility for `externalId` and `customerId`. The client endpoint `/api/track/sale/client` verifies request hostnames against `allowedHostnames` stored on the workspace before passing payloads to `trackSale`.
Sources: [apps/web/app/ee/api/track/sale/route.ts:10-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/route.ts#L10-L36)
```typescript
export const POST = withWorkspace(
async ({ req, workspace }) => {
const body = await parseRequestBody(req);
let {
customerExternalId: newExternalId,
externalId: oldExternalId, // deprecated
customerId: oldCustomerId, // deprecated
customerName,
customerEmail,
customerAvatar,
clickId,
amount,
currency,
eventName,
paymentProcessor,
invoiceId,
leadEventName,
metadata,
} = trackSaleRequestSchema
.extend({
// add backwards compatibility
customerExternalId: z.string().nullish(),
externalId: z.string().nullish(),
customerId: z.string().nullish(),
})
.parse(body);
const customerExternalId = newExternalId || oldExternalId || oldCustomerId;
if (!customerExternalId) {
throw new DubApiError({
code: "bad_request",
message: "customerExternalId is required",
});
}
```
Sources: [apps/web/app/ee/api/track/sale/route.ts:10-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/route.ts#L10-L45)
```typescript
export const POST = withPublishableKey(
async ({ req, workspace }) => {
const body = await parseRequestBody(req);
const allowRequest = verifyAnalyticsAllowedHostnames({
allowedHostnames: (workspace?.allowedHostnames ?? []) as string[],
req,
});
if (!allowRequest) {
throw new DubApiError({
code: "forbidden",
message: `Request origin '${getHostnameFromRequest(req)}' is not included in the allowed hostnames for this workspace. Update your allowed hostnames here: https://app.dub.co/settings/tracking`,
});
}
const {
customerExternalId,
customerName,
customerEmail,
customerAvatar,
clickId,
amount,
currency,
eventName,
paymentProcessor,
invoiceId,
leadEventName,
metadata,
} = trackSaleRequestSchema.parse(body);
if (!customerExternalId) {
throw new DubApiError({
code: "bad_request",
message: "customerExternalId is required",
});
}
```
Sources: [apps/web/app/ee/api/track/sale/client/route.ts:14-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/client/route.ts#L14-L50)
Within `_trackSale`, incoming transactions are evaluated and normalized before data recording. If the transaction amount is zero or negative, processing terminates early. Transactions denominated in non-USD currencies are converted to USD using current foreign exchange rates via `convertCurrency`.
Sources: [apps/web/lib/api/conversions/track-sale.ts:469-490](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L469-L490)
```typescript
// Skip if amount is 0 or less
if (amount <= 0) {
return {
eventName,
customer: null,
sale: null,
};
}
// if currency is not USD, convert it to USD based on the current FX rate
// TODO: allow custom "defaultCurrency" on workspace table in the future
if (currency !== "usd") {
const { currency: convertedCurrency, amount: convertedAmount } =
await convertCurrency({
currency,
amount,
});
currency = convertedCurrency;
amount = convertedAmount;
}
```
Sources: [apps/web/lib/api/conversions/track-sale.ts:493-514](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L493-L514)
> [!WARNING]
> If `leadEventData` cannot be resolved for a customer during sale ingestion, `_trackSale` throws a `not_found` error indicating that lead event data is missing.
> Sources: [apps/web/lib/api/conversions/track-sale.ts:486-491](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L486-L491)
### First Conversion Detection and Deduplication
First conversion detection determines whether a transaction represents an initial acquisition or a recurring customer purchase. The helper `isFirstConversion` evaluates customer metrics against the incoming `linkId`. A transaction is categorized as a first conversion if the customer has recorded zero previous sales, or if the customer's original referral link identifier differs from the current transaction link.
Sources: [apps/web/lib/analytics/is-first-conversion.ts:3-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/is-first-conversion.ts#L3-L10)
```typescript
export const isFirstConversion = ({
customer,
linkId,
}: {
customer: Pick;
linkId?: string;
}) => {
// if this is the first sale for the customer, it's a first conversion
if (customer.sales === 0) {
return true;
}
// if customer has sales, but the original referral link is not the same as the current link
// it is most likely a first conversion
if (customer.linkId !== linkId) {
// TODO: fix edge case where customer was brought in by a different link, but then had recurring sales on the current link
return true;
}
return false;
};
```
Sources: [apps/web/lib/analytics/is-first-conversion.ts:3-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/is-first-conversion.ts#L3-L23)
To prevent race conditions where concurrent requests attempt to record initial purchases simultaneously, first conversion claims are deduplicated using a Redis key with a 30-second expiry and an `nx: true` constraint.
Sources: [apps/web/lib/api/conversions/track-sale.ts:535-546](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L535-L546)
```typescript
let firstConversionFlag = isFirstConversion({
customer,
linkId: saleData.link_id,
});
// Deduplicate concurrent first sales for the same customer + link so only one
// request is counted as the first conversion.
if (firstConversionFlag) {
const claim = await redis.set(
`firstConversion:${customer.id}:${saleData.link_id}`,
1,
{
ex: 30,
nx: true,
},
);
firstConversionFlag = claim !== null;
}
```
Sources: [apps/web/lib/api/conversions/track-sale.ts:528-547](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L528-L547)
> [!TIP]
> The Redis deduplication lock uses the key pattern `firstConversion:{customerId}:{linkId}` to ensure only a single concurrent request is counted as the first conversion for a given customer and link pairing.
> Sources: [apps/web/lib/api/conversions/track-sale.ts:536-543](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L536-L543)
### Commission Dispatch and Metrics Updates
Once sale data and conversion flags are established, asynchronous background processing updates link statistics and dispatches partner commissions. Prisma updates increment link metrics such as `sales` and `saleAmount`, while conditionally incrementing conversion counts and setting `lastConversionAt` when `firstConversionFlag` evaluates to true.
Sources: [apps/web/lib/api/conversions/track-sale.ts:548-570](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L548-L570)
```typescript
waitUntil(
(async () => {
// Update link conversions, sales, and saleAmount
const link = await prisma.link.update({
where: {
id: saleData.link_id,
},
data: {
...(firstConversionFlag && {
conversions: {
increment: 1,
},
lastConversionAt: new Date(),
}),
sales: {
increment: 1,
},
saleAmount: {
increment: amount,
},
},
include: includeTags,
});
```
Sources: [apps/web/lib/api/conversions/track-sale.ts:548-570](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L548-L570)
If the associated link contains valid partner and program identifiers, `queuePartnerCommissionCreation` is invoked to calculate earnings through the [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine). The payload bundles customer country, signup date, source provenance, product metadata, and the first conversion status.
Sources: [apps/web/lib/api/conversions/track-sale.ts:576-608](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L576-L608)
```typescript
if (link.programId && link.partnerId) {
result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
partnerId: link.partnerId,
linkId: link.id,
customerId: customer.id,
eventId: saleData.event_id,
amount: saleData.amount,
quantity: 1,
invoiceId,
currency,
source: commissionSource,
userId,
...(metadata != null && { metadata }),
context: {
customer: {
country: customer.country,
signupDate: customer.createdAt,
source,
},
sale: {
productId: metadata?.productId,
amount: saleData.amount,
...(metadata != null && { metadata }),
},
},
clickEvent: {
url: saleData.url,
referer: saleData.referer,
},
isFirstConversion: firstConversionFlag,
});
```
Sources: [apps/web/lib/api/conversions/track-sale.ts:576-608](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L576-L608)
## Promotion codes and merchant integrations
### Stripe Promotion Code Attribution Workflow
When a Stripe checkout session completes without a direct `dubCustomerExternalId` or matching customer record, Dub evaluates whether a Stripe promotion code identifier (`promotionCodeId`) was attached to the checkout session. The function `attributeViaPromotionCodeId` queries the connected Stripe account via `getPromotionCode` to resolve the promo code string. It then searches the database for a matching `DiscountCode` record within the workspace's default program.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts:30-85](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts#L30-L85)
```typescript
export async function attributeViaPromotionCodeId({
promotionCodeId,
workspace,
mode,
customerDetails,
}: {
promotionCodeId: string; // must be Stripe's promotion code ID `promo_xxx`, not the actual promo code
workspace: Pick<
Project,
"id" | "defaultProgramId" | "stripeConnectId" | "webhookEnabled"
>;
mode: StripeMode;
customerDetails: PromoCodeCustomerDetails;
}) {
console.log(
`Attributing via promotion code ID ${promotionCodeId} for customer ${customerDetails.stripeCustomerId} in workspace ${workspace.id}`,
);
const stripeAccountId = workspace.stripeConnectId!;
const stripeCustomerId = customerDetails.stripeCustomerId;
if (!workspace.defaultProgramId) {
console.log(
`Workspace with stripeConnectId ${stripeAccountId} has no default program, skipping...`,
);
return null;
}
// Find the promotion code for the promotion code id
const promotionCode = await getPromotionCode({
promotionCodeId,
stripeAccountId,
mode,
});
if (!promotionCode) {
console.log(
`Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, skipping...`,
);
return null;
}
console.log(`Promotion code found: ${promotionCode.code}`);
const discountCode = await prisma.discountCode.findUnique({
where: {
programId_code: {
programId: workspace.defaultProgramId,
code: promotionCode.code,
},
},
include: {
link: true,
},
});
if (!discountCode) {
console.log(
`Couldn't find discount code "${promotionCode.code}" in program "${workspace.defaultProgramId}", skipping...`,
);
return null;
```
Sources: [apps/web/app/ee/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts:30-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts#L30-L90)
Once the discount code and its associated link are identified and verified as active (not disabled), Dub simulates attribution by executing a fake click event using customer billing address geographic properties. It resolves or creates the customer record and records a lead event in Tinybird, while caching the lead payload in Redis with a five-minute expiration window to support immediate subsequent sale lookups.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts:93-195](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts#L93-L195)
```typescript
const link = discountCode.link;
const linkId = link.id;
const customerAddress = customerDetails.address;
const customerCountry = customerAddress?.country?.toUpperCase();
// Record a fake click for this event
const clickEvent = await recordFakeClick({
link,
customer: {
continent: customerCountry
? COUNTRIES_TO_CONTINENTS[customerCountry] ?? "Unknown"
: "Unknown",
country: customerCountry ?? "Unknown",
region: customerAddress?.state ?? "Unknown",
},
});
const { customer, created } = await getOrCreateCustomer({
findMode: "first",
where: {
OR: [
{
stripeCustomerId,
},
{
projectId: workspace.id,
externalId: clickEvent.click_id,
},
],
},
create: {
id: createId({ prefix: "cus_" }),
name:
customerDetails.name || customerDetails.email || generateRandomName(),
email: customerDetails.email,
externalId: clickEvent.click_id,
stripeCustomerId,
linkId: clickEvent.link_id,
clickId: clickEvent.click_id,
clickedAt: new Date(clickEvent.timestamp + "Z"),
country: customerAddress?.country,
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
programId: link.programId,
partnerId: link.partnerId,
},
});
// Concurrent webhook already created this customer — continue sale without re-recording lead
if (!created) {
let existingLead = await redis.get(`leadCache:${customer.id}`);
if (!existingLead) {
existingLead = await getLeadEvent({
customerId: customer.id,
});
}
if (!existingLead) {
console.log(
`Customer with stripeCustomerId ${stripeCustomerId} already exists but no lead event found, skipping promo code attribution...`,
);
return null;
}
return {
linkId,
customer,
clickEvent,
leadEvent: {
...existingLead,
workspace_id: workspace.id,
},
};
}
// Prepare the payload for the lead event
const { timestamp, ...rest } = clickEvent;
const leadEvent = {
```
Sources: [apps/web/app/ee/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts:100-195](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts#L100-L195)
> [!NOTE]
> If a concurrent webhook execution has already created the customer record, `attributeViaPromotionCodeId` bypasses duplicate lead recording and retrieves the existing lead event from Redis or Tinybird.
> Sources: [apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts:148-174](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts#L148-L174)
### Shopify Discount Code Attribution
Shopify orders containing discount codes are handled by `attributeViaDiscountCode`, which extracts customer billing information and maps country codes to continents. A fake click event is generated via `recordFakeClick`, establishing geographic provenance for the order before a customer record is created with a `cus_` prefix.
Sources: [apps/web/lib/integrations/shopify/attribute-via-discount-code.ts:28-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts#L28-L65)
```typescript
export async function attributeViaDiscountCode({
order,
workspace,
link,
}: {
order: ShopifyOrder;
workspace: Pick;
link: Link;
}) {
const { customer: orderCustomer, billing_address: billingAddress } = order;
const billingAddressCountry = billingAddress?.country_code?.toUpperCase();
// Record a fake click for this event
const clickEvent = await recordFakeClick({
link,
customer: {
continent: billingAddressCountry
? COUNTRIES_TO_CONTINENTS[billingAddressCountry] ?? "Unknown"
: "Unknown",
country: billingAddressCountry ?? "Unknown",
region: billingAddress?.province ?? "Unknown",
},
});
const customerId = createId({ prefix: "cus_" });
const clickId = clickEvent.click_id;
// Create the customer before recording the fake click so a P2002 on
// projectId_externalId never leaves an orphaned Tinybird click behind.
const customer = await prisma.customer.create({
data: {
id: customerId,
name: orderCustomer
? `${orderCustomer.first_name} ${orderCustomer.last_name}`.trim()
: generateRandomName(),
email: orderCustomer?.email,
externalId: orderCustomer?.id?.toString() || customerId,
linkId: link.id,
clickId,
clickedAt: new Date(),
country: billingAddress?.country_code,
projectId: workspace.id,
programId: link.programId,
partnerId: link.partnerId,
},
});
```
Sources: [apps/web/lib/integrations/shopify/attribute-via-discount-code.ts:19-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts#L19-L65)
After the customer record is established, a lead event named `"Checkout with discount code"` is recorded, link lead metrics are incremented, and partner commission queues, workflow executions, and Google Ads conversion uploads are triggered asynchronously.
Sources: [apps/web/lib/integrations/shopify/attribute-via-discount-code.ts:67-179](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts#L67-L179)
```typescript
// Prepare the payload for the lead event
const { timestamp, ...rest } = clickEvent;
const leadEvent = {
...rest,
workspace_id: clickEvent.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id
event_id: nanoid(16),
event_name: "Checkout with discount code",
customer_id: customer.id,
metadata: "",
};
await recordLead(leadEvent);
const linkUpdated = await prisma.link.update({
where: {
id: link.id,
},
data: {
leads: {
increment: 1,
},
lastLeadAt: new Date(),
},
include: includeTags,
});
let result:
| Awaited>
| undefined = undefined;
if (link.programId && link.partnerId) {
result = await queuePartnerCommissionCreation({
event: "lead",
programId: link.programId,
partnerId: link.partnerId,
linkId: link.id,
eventId: leadEvent.event_id,
customerId: customer.id,
quantity: 1,
source: CommissionSource.shopify,
context: {
customer: {
country: customer.country,
},
},
});
await Promise.allSettled([
executeWorkflows({
event: "leadRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
partnerId: link.partnerId,
},
metrics: {
current: {
leads: 1,
},
},
}),
syncPartnerLinksStats({
partnerId: link.partnerId,
programId: link.programId,
eventType: "lead",
}),
]);
}
await Promise.allSettled([
sendWorkspaceWebhook({
trigger: "lead.created",
workspace,
data: transformLeadEventData({
...clickEvent,
eventName: "Checkout with discount code",
link: linkUpdated,
customer,
```
Sources: [apps/web/lib/integrations/shopify/attribute-via-discount-code.ts:67-185](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts#L67-L185)
> [!CAUTION]
> When creating Shopify customers during discount code attribution, the customer record is inserted before recording the fake click to ensure a unique constraint violation (`P2002` on `projectId_externalId`) never leaves an orphaned Tinybird click behind.
> Sources: [apps/web/lib/integrations/shopify/attribute-via-discount-code.ts:47-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts#L47-L49)
## Customer reattribution and historical reconciliation
### Customer Recreation and Reattribution Flow
When a customer needs to be reattributed across links, Dub executes `recreateCustomerForReattribution` inside a Prisma transaction. The original customer record is updated by appending `(old)` to its name and assigning a randomized external identifier prefix (`reattributed_`) while nullifying all partnership, link, click, and Stripe billing properties. Simultaneously, a new customer record is created with the target link, program, partner, and click identifiers.
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:126-170](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L126-L170)
```typescript
export async function recreateCustomerForReattribution({
customer,
link,
newCustomerId,
newClickId,
}: {
customer: Customer;
link: Pick ;
newCustomerId: string;
newClickId: string;
}) {
return await prisma.$transaction(async (tx) => {
await tx.customer.update({
where: {
id: customer.id,
},
data: {
name: customer.name ? `${customer.name} (old)` : undefined,
externalId: `reattributed_${nanoid(32)}`,
stripeCustomerId: null,
linkId: null,
clickId: null,
clickedAt: null,
programId: null,
partnerId: null,
sales: 0,
saleAmount: 0,
firstSaleAt: null,
subscriptionCanceledAt: null,
},
});
return await tx.customer.create({
data: {
id: newCustomerId,
name: customer.name,
email: customer.email,
avatar: customer.avatar,
externalId: customer.externalId,
stripeCustomerId: customer.stripeCustomerId,
clickedAt: customer.clickedAt,
country: customer.country,
sales: customer.sales,
saleAmount: customer.saleAmount,
firstSaleAt: customer.firstSaleAt,
subscriptionCanceledAt: customer.subscriptionCanceledAt,
projectId: customer.projectId,
projectConnectId: customer.projectConnectId,
createdAt: customer.createdAt,
linkId: link.id,
programId: link.programId,
partnerId: link.partnerId,
clickId: newClickId,
},
});
});
}
```
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:115-171](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L115-L171)
> [!NOTE]
> Reattribution stubs are identified strictly by checking if the external identifier starts with `reattributed_`, `dummy_`, or `retired_` while holding null values for `partnerId`, `linkId`, and `programId`.
> Sources: [apps/web/lib/api/customers/reattribute-customer.ts:77-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L77-L96)
Event reconciliation reads historical customer event telemetry from Tinybird via `getCustomerReattributeEvents`, enforcing an upper limit defined by `CUSTOMER_REATTRIBUTION_EVENTS_LIMIT` set to 500 events. If event counts breach this threshold, reattribution halts to prevent memory exhaustion during event processing plans.
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:98-103](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L98-L103)
```typescript
export const CUSTOMER_REATTRIBUTION_EVENTS_LIMIT = 500;
const UNPAID_COMMISSION_STATUSES = ["pending", "hold", "processed"] as const;
const STATS_LOCK_TTL_SECONDS = 60 * 60 * 24;
```
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:22-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L22-L24)
### Historical Backfill and Partition Splitting
Historical backfills for leads and clicks duplicate events under new customer identifiers while transferring existing event references. In migration scripts such as `backfill-reuse-commission.ts`, existing sale events are capped at a maximum limit of 5 entries per execution to prevent batch timeout failures.
Sources: [apps/web/scripts/programs/backfill-reuse-commission.ts:145-150](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/backfill-reuse-commission.ts#L145-L150)
When importing customer leads in bulk, click payloads are grouped by calendar year to satisfy ClickHouse partition boundaries, since partition ingestion supports a maximum of 12 partitions per backfill batch.
Sources: [apps/web/scripts/programs/3-import-customer-leads.ts:157-169](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/3-import-customer-leads.ts#L157-L169)
| Parameter / Constant | Value / Limit | Purpose |
| :--- | :--- | :--- |
| `CUSTOMER_REATTRIBUTION_EVENTS_LIMIT` | `500` | Maximum event retrieval ceiling for customer reattribution pipelines |
| `STATS_LOCK_TTL_SECONDS` | `86400` (24 hours) | Redis distributed lock expiration time for stat synchronization runs |
| Max Sale Events Backfill | `5` | Upper limit for existing sale events processed during reuse-commission backfills |
| ClickHouse Partitions | `12` | Maximum monthly partitions allowed for a single event backfill batch |
```typescript
export const CUSTOMER_REATTRIBUTION_EVENTS_LIMIT = 500;
const UNPAID_COMMISSION_STATUSES = ["pending", "hold", "processed"] as const;
const STATS_LOCK_TTL_SECONDS = 60 * 60 * 24;
```
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:22-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L22-L24)
> [!CAUTION]
> Distributed stat updates during reattribution utilize Redis keys guarded by `runOnce`, which immediately deletes the lock key if the execution function throws an uncaught exception.
> Sources: [apps/web/lib/api/customers/reattribute-customer.ts:58-75](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L58-L75)
## Partner metrics synchronization and batch processing
### Redis Streams and Asynchronous Activity Updates
Partner activity updates are published to an asynchronous Redis stream via `publishPartnerActivityEvent` in [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine), capturing events with `programId`, `partnerId`, `eventType`, and `timestamp`. The cron route `GET /api/cron/streams/update-partner-stats` processes these streams in batches governed by `BATCH_SIZE` set to `6000`, running with `deleteAfterRead: true`.
Sources: [apps/web/app/ee/api/cron/streams/update-partner-stats/route.ts:15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts#L15)
When a partner activity stream batch is processed, unique program-partner pairs are extracted to query grouped link metrics and commission totals in parallel via Prisma. Derived metrics such as net revenue, earnings per click, and consistency scores are computed before executing updates in sub-batches of size `50` against PlanetScale using raw SQL execution via `conn.execute`. If publishing to the Redis stream fails, `syncPartnerLinksStats` falls back directly to an atomic Prisma transaction executing `tx.link.aggregate` and updating `tx.programEnrollment`.
Sources: [apps/web/app/ee/api/cron/streams/update-partner-stats/route.ts:77-107](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts#L77-L107)
> [!NOTE]
> Consistency scores default to `50` and scale dynamically based on `daysSinceLastConversion`: `100` for 7 days or less, `85` for up to 30 days, `70` for up to 90 days, `55` for up to 180 days, and `40` for longer periods.
> Sources: [apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts:210-229](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts#L210-L229)
### Backfill Processing and Application Tracking
The backfill cron route `apps/web/app/(ee)/api/cron/framer/backfill-leads-batch/route.ts` records batch click telemetry, leads, zero-amount sale events, and paid commissions simultaneously while caching external ID and event name pairs in Redis using `redis.sadd`. Concurrently, short link click, lead, and sale counters are incremented using `link.updateMany` grouped by key occurrences.
Sources: [apps/web/app/ee/api/cron/framer/backfill-leads-batch/route.ts:295-329](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/framer/backfill-leads-batch/route.ts#L295-L329)
```typescript
await Promise.all([
// Record clicks
fetch(
`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
"Content-Type": "application/x-ndjson",
},
body: dataArray.map((d) => JSON.stringify(d.clickData)).join("\n"),
},
),
// Record leads
recordLeadWithTimestamp(dataArray.map((d) => d.leadEventData)),
// Record commissions
prisma.commission.createMany({
data: dataArray.map((d) => d.commissionData),
skipDuplicates: true,
}),
// Record sales
recordSaleWithTimestamp(dataArray.map((d) => d.saleEventData)),
// Cache the externalId:eventName pairs
redis.sadd(
CACHE_KEY,
...(dataArray.map(
({ payload: { externalId, eventName } }) =>
`${externalId}:${eventName}`,
) as [string]),
),
]);
…
await Promise.all(
Object.entries(groupedLinks).map(([count, linkKeys]) =>
prisma.link.updateMany({
where: {
shortLink: {
in: linkKeys.map((key) =>
linkConstructorSimple({
domain: DOMAIN,
key,
}),
),
},
},
data: {
clicks: {
increment: parseInt(count),
},
leads: {
increment: parseInt(count),
},
sales: {
increment: parseInt(count),
},
},
}),
),
```
Sources: [apps/web/app/ee/api/cron/framer/backfill-leads-batch/route.ts:295-329](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/framer/backfill-leads-batch/route.ts#L295-L329), [apps/web/app/ee/api/cron/framer/backfill-leads-batch/route.ts:351-376](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/framer/backfill-leads-batch/route.ts#L351-L376)
Application events are managed via `markApplicationEventSubmittedNetwork`, which validates network program cookies, updates application records within a transaction, creates customer profiles, and triggers `syncPartnerLinksStats` with an event type of `"lead"`.
Sources: [apps/web/lib/application-events/mark-application-event-submitted-network.ts:17-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/application-events/mark-application-event-submitted-network.ts#L17-L72)
```typescript
const cookieStore = await cookies();
const cookieName = getApplicationEventCookieName(NETWORK_PROGRAM_ID);
const applicationEventId = cookieStore.get(cookieName)?.value;
if (!applicationEventId) {
console.log(
`No application event ID found for network program + new partner ${partner.id}, skipping...`,
);
return;
}
const applicationEvent = await prisma.programApplicationEvent.findUnique({
where: {
id: applicationEventId,
programId: NETWORK_PROGRAM_ID,
},
});
if (!applicationEvent) {
console.log(
`No application event found for new partner ${partner.id}, skipping...`,
);
return;
}
if (applicationEvent.submittedAt) {
console.log(
`Application event already submitted for new partner ${partner.id}, skipping...`,
);
return;
}
await prisma.$transaction(async (tx) => {
await tx.programApplicationEvent.update({
where: {
id: applicationEventId,
},
data: {
// assuming application starts after 15-45 seconds of visiting the page
startedAt: addSeconds(applicationEvent.visitedAt, randomInt(15, 45)),
submittedAt: new Date(),
partnerId: partner.id,
},
});
if (applicationEvent.referredByPartnerId) {
await tx.partner.update({
where: {
id: partner.id,
},
data: {
referredByPartnerId: applicationEvent.referredByPartnerId,
},
});
}
});
…
await prisma.link.update({
where: {
id: networkPartnerLink.id,
},
data: {
clicks: {
increment: 1,
},
lastClicked: applicationEvent.visitedAt,
leads: {
increment: 1,
},
lastLeadAt: new Date(),
},
});
console.log(`Updated stats for link ${networkPartnerLink.id}`);
await syncPartnerLinksStats({
partnerId: networkPartnerLink.partnerId!,
programId: networkPartnerLink.programId!,
eventType: "lead",
});
```
Sources: [apps/web/lib/application-events/mark-application-event-submitted-network.ts:17-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/application-events/mark-application-event-submitted-network.ts#L17-L72), [apps/web/lib/application-events/mark-application-event-submitted-network.ts:136-157](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/application-events/mark-application-event-submitted-network.ts#L136-L157)
## Related
- [Tinybird Analytics](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics)
- [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine)
---
## Technical docs: POST Generate Veriff session
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/admingenerateveriffsession
## Parameters
## Responses
## Try It
---
## Technical docs: Analytics Dashboard
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/analytics-dashboard
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/api/analytics/dashboard/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/dashboard/route.ts)
- [apps/web/app/api/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts)
- [apps/web/app/api/analytics/export/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts)
- [apps/web/app/ee/api/events/export/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts)
- [apps/web/app/api/og/analytics/route.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/analytics/route.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/analytics-chart.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/analytics-chart.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/program-analytics-shell.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/program-analytics-shell.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/analytics/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/analytics/page.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/billing/usage-chart.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/billing/usage-chart.tsx)
- [apps/web/app/ee/api/partner-profile/programs/programId/analytics/export/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/analytics/export/route.ts)
- [apps/web/ui/analytics/location-section.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/location-section.tsx)
- [apps/web/app/ee/api/partner-profile/programs/programId/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/analytics/route.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/payouts/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/payouts/page.tsx)
- [apps/web/app/ee/api/program-applications/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/program-applications/analytics/route.ts)
- [apps/web/app/ee/api/partners/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partners/analytics/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/links/analytics/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/links/analytics/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/commissions/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/commissions/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/revenue/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/page.tsx)
- [apps/web/ui/analytics/index.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/index.tsx)
- [apps/web/ui/analytics/device-section.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/device-section.tsx)
- [apps/web/ui/analytics/chart-section.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/page.tsx)
- [apps/web/ui/analytics/analytics-export-button.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/analytics-export-button.tsx)
- [apps/web/app/app.dub.co/share/share/dashboardId/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(share)/share/%5BdashboardId%5D/page.tsx)
- [apps/web/app/ee/api/partner-profile/referrals/timeseries/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/referrals/timeseries/route.ts)
- [apps/web/ui/analytics/toggle.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/toggle.tsx)
- [apps/web/app/ee/api/embed/referrals/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/events/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/events/page.tsx)
- [apps/web/ui/analytics/referrers-utms.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/referrers-utms.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/applications/use-applications-analytics-query.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/applications/use-applications-analytics-query.ts)
## Overview
Dub provides a comprehensive analytics dashboard system that tracks and aggregates link clicks, lead submissions, and sale conversions across workspaces, [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs), and shared public views. The platform combines server-side query routing, Redis caching, and plan-aware validations with rich client-side visualizations—including timeseries charts, conversion funnels, and dimension breakdowns for geographic, device, and referrer data. Users can also configure filters, examine program-specific application pipelines, and export filtered datasets or raw events as CSV and ZIP archives.
Sources: [apps/web/app/api/analytics/dashboard/route.ts:1-202](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/dashboard/route.ts#L1-L202), [apps/web/app/api/analytics/route.ts:1-137](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L1-L137), [apps/web/app/api/analytics/export/route.ts:1-132](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts#L1-L132), [apps/web/app/ee/api/events/export/route.ts:37-181](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts#L37-L181), [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/analytics-chart.tsx:13-120](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/analytics-chart.tsx#L13-L120), [apps/web/ui/analytics/location-section.tsx:19-175](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/location-section.tsx#L19-L175), [apps/web/app/app.dub.co/share/share/dashboardId/page.tsx:31-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(share)/share/%5BdashboardId%5D/page.tsx#L31-L122), [apps/web/ui/analytics/index.tsx:23-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/index.tsx#L23-L55), [apps/web/ui/analytics/device-section.tsx:14-150](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/device-section.tsx#L14-L150), [apps/web/ui/analytics/chart-section.tsx:26-147](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx#L26-L147), [apps/web/ui/analytics/toggle.tsx:40-307](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/toggle.tsx#L40-L307), [apps/web/ui/analytics/referrers-utms.tsx:42-237](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/referrers-utms.tsx#L42-L237)
## Analytics API query routing
### Parameter parsing and path normalization
Server-side analytics endpoints process incoming requests by parsing search parameters, validating workspace permissions and plan limits, and normalizing filter arguments before querying telemetry backends. The core analytics API (`/api/analytics`) is wrapped with workspace authentication requiring the `analytics.read` permission and checks click usage limits via `throwIfClicksUsageExceeded`.
```typescript
export const GET = withWorkspace(
async ({ params, searchParams, workspace, session }) => {
throwIfClicksUsageExceeded(workspace);
```
Sources: [apps/web/app/api/analytics/route.ts:20-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L20-L22)
Query parameters are parsed using `parseAnalyticsQuery(searchParams)`. Path parameters are evaluated against `analyticsPathParamsSchema` to extract event types and grouping endpoints, supporting backward compatibility where `/analytics/[endpoint]` patterns map directly to grouping configurations.
```typescript
let { eventType: oldEvent, endpoint: oldType } =
analyticsPathParamsSchema.parse(params);
// for backwards compatibility (we used to support /analytics/[endpoint] as well)
if (!oldType && oldEvent && VALID_ANALYTICS_ENDPOINTS.includes(oldEvent)) {
oldType = oldEvent;
oldEvent = undefined;
}
const parsedParams = parseAnalyticsQuery(searchParams);
```
Sources: [apps/web/app/api/analytics/route.ts:24-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L24-L33)
> [!NOTE]
> Backward compatibility logic checks if the endpoint parameter is omitted while an event matches `VALID_ANALYTICS_ENDPOINTS`, promoting it to the grouping parameter.
> [!WARNING]
> Requests referencing deprecated endpoints (`/api/analytics/clicks`, `/api/analytics/count`) set `isDeprecatedClicksEndpoint` to true so the underlying query builder handles legacy aggregation structures correctly.
Sources: [apps/web/app/api/analytics/route.ts:28-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L28-L31), [apps/web/app/api/analytics/route.ts:116-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L116-L118)
### Filter normalization and link resolution
When requests specify domain and key or external identifiers without an explicit `linkId`, the router resolves the link via `getLinkOrThrow`. The filter parameters are then normalized by replacing the domain/key combination with an explicit SQL operator structure on `linkId` and clearing the standalone domain filter.
```typescript
if (!linkId && (externalId || (domain && key))) {
const link = await getLinkOrThrow({
workspaceId: workspace.id,
linkId,
externalId,
domain: getFirstFilterValue(domain),
key,
});
parsedParams.linkId = {
operator: "IS",
sqlOperator: "IN",
values: [link.id],
};
// since we're filtering for a specific link, exclude domain from filters
parsedParams.domain = undefined;
```
Sources: [apps/web/app/api/analytics/route.ts:71-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L71-L88)
Workspace folders associated with links or direct folder filters undergo access verification via `verifyFolderAccess` requiring `folders.read` permissions. Additionally, program identifiers are verified against the workspace default program, throwing a `DubApiError` with a forbidden code if a mismatch occurs.
```typescript
if (programId) {
const workspaceProgramId = getDefaultProgramIdOrThrow(workspace);
if (programId !== workspaceProgramId) {
throw new DubApiError({
code: "forbidden",
message: `Program ${programId} does not belong to workspace ${prefixWorkspaceId(workspace.id)}.`,
});
}
if (groupBy === "timeseries") {
```
Sources: [apps/web/app/api/analytics/route.ts:53-61](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/route.ts#L53-L61)
## Dashboard visualization layout and controls
### Client-side analytics container and conditional stats grid
The client-side analytics view is initialized through the `Analytics` component within workspace routes, dashboard previews, and partner portal pages. It wraps child layouts in an `AnalyticsProvider` context, rendering a sticky top navigation bar via `AnalyticsToggle` alongside a responsive grid that houses the main chart section and statistical breakdown cards.
```tsx
export default function Analytics({
adminPage,
dashboardProps,
}: {
adminPage?: boolean;
dashboardProps?: AnalyticsDashboardProps;
}) {
return (
{({ dashboardProps }) => {
return (
);
}}
);
}
```
Sources: [apps/web/ui/analytics/index.tsx:23-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/index.tsx#L23-L55)
The `StatsGrid` component conditionally hides [conversion tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking) metrics based on the selected tab and workspace plan tier. Specifically, when the selected tab is set to `leads`, `sales`, or the view mode is set to `funnel` under a `free` or `pro` plan, the stats grid returns `null` to restrict advanced conversion insights to higher tiers.
```tsx
function StatsGrid() {
const { dashboardProps, selectedTab, view } = useContext(AnalyticsContext);
const { plan } = useWorkspace();
const hide =
(selectedTab === "leads" || selectedTab === "sales" || view === "funnel") &&
(plan === "free" || plan === "pro");
return hide ? null : (
{!dashboardProps?.key && }
);
}
```
Sources: [apps/web/ui/analytics/index.tsx:57-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/index.tsx#L57-L72)
> [!WARNING]
> Attempting to view `leads`, `sales`, or `funnel` views on free and pro workspaces completely unmounts the underlying dimension cards (`TopLinks`, `ReferrersUTMs`, `LocationSection`, and `DeviceSection`), preventing unauthorized metric exposure.
Sources: [apps/web/ui/analytics/index.tsx:61-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/index.tsx#L61-L64)
### Date filtering, interval selection, and plan validation
The `AnalyticsToggle` component manages date range parameters, filtering state, and interval selections. It integrates a `DateRangePicker` utilizing interval presets defined by `INTERVAL_DISPLAYS`, allowing users to switch between standard pre-configured time ranges or custom date bounds.
```tsx
const dateRangePicker = (
{
if (preset) {
queryParams({
del: ["start", "end"],
set: {
interval: preset.id,
},
});
return;
}
// Regular range
if (!range || !range.from || !range.to) return;
queryParams({
del: "interval",
set: {
start: range.from.toISOString(),
end: range.to.toISOString(),
},
});
}}
presets={INTERVAL_DISPLAYS.map(({ display, value, shortcut }) => {
const requiresUpgrade =
partnerPage ||
DUB_DEMO_LINKS.find((l) => l.domain === domain && l.key === key)
? false
: !validDateRangeForPlan({
plan: plan || dashboardProps?.workspacePlan,
dataAvailableFrom: createdAt,
interval: value,
start,
end,
}).valid;
const { startDate, endDate } = getStartEndDates({
interval: value,
dataAvailableFrom: createdAt,
});
return {
id: value,
label: display,
dateRange: {
from: startDate,
to: endDate,
},
requiresUpgrade,
tooltipContent: requiresUpgrade ? (
) : undefined,
shortcut,
};
})}
/>
```
Sources: [apps/web/ui/analytics/toggle.tsx:94-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/toggle.tsx#L94-L164)
When a user selects an interval preset, `AnalyticsToggle` updates the URL search parameters by deleting explicit `start` and `end` bounds while setting the `interval` query parameter to the preset ID. Conversely, selecting a custom date range removes the `interval` parameter and encodes ISO strings for `start` and `end`.
```tsx
onChange={(range, preset) => {
if (preset) {
queryParams({
del: ["start", "end"],
set: {
interval: preset.id,
},
});
return;
}
// Regular range
if (!range || !range.from || !range.to) return;
queryParams({
del: "interval",
set: {
start: range.from.toISOString(),
end: range.to.toISOString(),
},
});
}}
```
Sources: [apps/web/ui/analytics/toggle.tsx:109-131](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/toggle.tsx#L109-L131)
> [!TIP]
> Preset validation checks plan capabilities using `validDateRangeForPlan` against workspace creation dates. If an interval exceeds the plan limit, an `UpgradeTooltip` is attached to prompt users for a plan upgrade.
Sources: [apps/web/ui/analytics/toggle.tsx:132-163](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/toggle.tsx#L132-L163)
## Timeseries and funnel metric charts
### Chart section container and tab management
The `ChartSection` component coordinates the visualization rendering inside the dashboard. It inspects workspace tier parameters alongside `showConversions` flags to build the available event tabs: `clicks`, `leads`, and `sales`.
```tsx
export function ChartSection() {
const {
totalEvents,
requiresUpgrade,
showConversions,
selectedTab,
saleUnit,
view,
} = useContext(AnalyticsContext);
const { plan } = useWorkspace();
const { queryParams } = useRouterStuff();
const tabs = useMemo(
() =>
[
{
id: "clicks",
label: "Clicks",
colorClassName: "text-blue-500/50",
conversions: false,
},
...(showConversions
? [
{
id: "leads",
label: "Leads",
colorClassName: "text-violet-600/50",
conversions: true,
},
{
id: "sales",
label: "Sales",
colorClassName: "text-teal-400/50",
conversions: true,
},
]
: []),
] as Tab[],
[showConversions],
);
```
Sources: [apps/web/ui/analytics/chart-section.tsx:26-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx#L26-L65)
Each tab holds an identifier, display label, color styling class, and a boolean indicating whether it represents a conversion metric.
| Tab ID | Label | Color Class Name | Conversions |
| :--- | :--- | :--- | :--- |
| `clicks` | Clicks | `text-blue-500/50` | `false` |
| `leads` | Leads | `text-violet-600/50` | `true` |
| `sales` | Sales | `text-teal-400/50` | `true` |
Sources: [apps/web/ui/analytics/chart-section.tsx:41-61](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx#L41-L61)
> [!WARNING]
> When `showPaywall` evaluates to true—triggered when accessing conversion tabs or funnel views on `free` or `pro` workspace plans—the chart container applies pointer-events disabling alongside linear gradient masking and renders the `ConversionTrackingPaywall` overlay.
Sources: [apps/web/ui/analytics/chart-section.tsx:69-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx#L69-L72), [apps/web/ui/analytics/chart-section.tsx:99-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx#L99-L105), [apps/web/ui/analytics/chart-section.tsx:143-143](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/chart-section.tsx#L143-L143)
### Program analytics chart data and view modes
Program-specific analytics charts fetch timeseries aggregation datasets from `/api/analytics` parameterized by `groupBy=timeseries` and the currently selected event tab. The returned records map start dates and metric counts or sale amounts into chart values.
```tsx
const { data, error } = useSWR<
{
start: Date;
clicks: number;
leads: number;
sales: number;
saleAmount: number;
}[]
>(
`/api/analytics?${editQueryString(queryString ?? "", {
event: selectedTab,
groupBy: "timeseries",
})}`,
fetcher,
);
const chartData = useMemo(
() =>
data?.map((d) => ({
date: new Date(d.start),
values: {
amount:
selectedTab === "sales" && saleUnit === "saleAmount"
? d.saleAmount
: d[selectedTab],
},
})),
[data, selectedTab, saleUnit],
);
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/analytics-chart.tsx:19-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/analytics-chart.tsx#L19-L47)
The view switcher toggles between `timeseries` and `funnel` visualization modes. When loading data, a loading spinner is shown, while fetch errors present a fallback message.
```tsx
{dataLoading ? (
) : error ? (
Failed to load data
) : (
<>
{view === "timeseries" ? (
) : (
)}
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/analytics-chart.tsx:74-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/analytics-chart.tsx#L74-L91)
## Geographic, device, and referrer breakdown
### Location metrics and country/city bar lists
The `LocationSection` component manages geographic distributions by rendering an `AnalyticsCard` with four tabs: `countries`, `cities`, `regions`, and `continents`. It retrieves data using `useAnalyticsFilterOption(tab)` alongside an unfiltered dataset (`omitGroupByFilterKey: true`) to render proportion values inside a `BarList`.
```tsx
export function LocationSection() {
const { queryParams, searchParams } = useRouterStuff();
const { selectedTab, saleUnit } = useContext(AnalyticsContext);
const dataKey = selectedTab === "sales" ? saleUnit : "count";
const [tab, setTab] = useState<
"countries" | "cities" | "regions" | "continents"
>("countries");
const { data } = useAnalyticsFilterOption(tab);
const { data: allData } = useAnalyticsFilterOption(tab, {
omitGroupByFilterKey: true,
});
```
Sources: [apps/web/ui/analytics/location-section.tsx:19-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/location-section.tsx#L19-L32)
Each item formats its display title and icon based on the active tab context. Continent tabs resolve names from `CONTINENTS`, countries map through `COUNTRIES` with `CountryFlag` elements, and regions or cities construct composite location strings with regional fallbacks.
| Tab ID | Icon Component | Title Resolution Source | Endpoint Mapping |
| :--- | :--- | :--- | :--- |
| `countries` | `CountryFlag` | `COUNTRIES[d.country]` | `country` |
| `cities` | `CountryFlag` | `${d.city}, ${REGIONS[d.region] || ...}` | `city` |
| `regions` | `CountryFlag` | `REGIONS[d.region] || fallback` | `region` |
| `continents` | `ContinentIcon` | `CONTINENTS[d.continent]` | `continent` |
Sources: [apps/web/ui/analytics/location-section.tsx:74-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/location-section.tsx#L74-L79), [apps/web/ui/analytics/location-section.tsx:94-117](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/location-section.tsx#L94-L117)
> [!NOTE]
> When location filter values are toggled, `onApplyFilterValues` updates URL query parameters using the singular endpoint name from `SINGULAR_ANALYTICS_ENDPOINTS[tab]`. Empty selections delete the parameter, whereas multiple selections join values with commas.
Sources: [apps/web/ui/analytics/location-section.tsx:47-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/location-section.tsx#L47-L59)
### Device, browser, and OS distributions
The `DeviceSection` component displays technical breakdown statistics across four device categories: `devices`, `browsers`, `os`, and `triggers`. It utilizes `DeviceIcon` and `TRIGGER_DISPLAY` maps to render respective icons and labels for each metric entry.
```tsx
export function DeviceSection() {
const { queryParams, searchParams } = useRouterStuff();
const { selectedTab, saleUnit } = useContext(AnalyticsContext);
const dataKey = selectedTab === "sales" ? saleUnit : "count";
const [tab, setTab] = useState
("devices");
const { data } = useAnalyticsFilterOption(tab);
const { data: allData } = useAnalyticsFilterOption(tab, {
omitGroupByFilterKey: true,
});
const singularTabName = SINGULAR_ANALYTICS_ENDPOINTS[tab];
```
Sources: [apps/web/ui/analytics/device-section.tsx:14-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/device-section.tsx#L14-L25)
The card styles its elements using green color variables (`bg-green-100`, `hover:bg-green-50`, `bg-green-600`) to visually distinguish device telemetry from other analytics sections.
| Tab ID | Label | Icon Component | Singular Endpoint |
| :--- | :--- | :--- | :--- |
| `devices` | Devices | `MobilePhone` | `device` |
| `browsers` | Browsers | `Window` | `browser` |
| `os` | OS | `Cube` | `os` |
| `triggers` | Triggers | `CursorRays` | `trigger` |
Sources: [apps/web/ui/analytics/device-section.tsx:66-71](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/device-section.tsx#L66-L71), [apps/web/lib/analytics/constants.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/analytics/constants.ts)
### Referrers and UTM parameter breakdowns
The `ReferrersUTMs` component handles traffic source grouping by splitting metrics between `referers` and `utms` top-level tabs. Referrers contain subtabs for domain `referers` and full `referer_urls`, while UTM tabs iterate over `UTM_TAGS_PLURAL_LIST`.
```tsx
const TAB_CONFIG: Record<
TabId,
{
subtabs: Subtab[];
defaultSubtab: Subtab;
getSubtabLabel: (subtab: Subtab) => string;
}
> = {
referers: {
subtabs: ["referers", "referer_urls"],
defaultSubtab: "referers",
getSubtabLabel: (subtab) => (subtab === "referers" ? "Domain" : "URL"),
},
utms: {
subtabs: [...UTM_TAGS_PLURAL_LIST] as Subtab[],
defaultSubtab: "utm_sources" as Subtab,
getSubtabLabel: (subtab) =>
SINGULAR_ANALYTICS_ENDPOINTS[subtab as UTM_TAGS_PLURAL].replace(
"utm_",
"",
),
},
};
```
Sources: [apps/web/ui/analytics/referrers-utms.tsx:18-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/referrers-utms.tsx#L18-L40)
For URL subtabs or standard referrers, item icons fetch favicons using `GOOGLE_FAVICON_URL` alongside `getApexDomain`. Direct traffic entries render a `Link2` icon, and UTM rows load their specific parameter icon from `UTM_PARAMETERS`.
```tsx
icon:
isUtmTab && UTMTagIcon ? (
) : isDirect ? (
) : (
),
```
Sources: [apps/web/ui/analytics/referrers-utms.tsx:152-169](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/referrers-utms.tsx#L152-L169)
> [!WARNING]
> Switching between the `referers` and `utms` primary tabs automatically resets the active subtab to the corresponding default defined in `TAB_CONFIG` and clears any selected filter items.
Sources: [apps/web/ui/analytics/referrers-utms.tsx:53-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/referrers-utms.tsx#L53-L56), [apps/web/ui/analytics/referrers-utms.tsx:68-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/referrers-utms.tsx#L68-L70)
## Partner program analytics pipelines
### Program application metrics and event aggregations
Program applications and referral events are processed through specific workspace analytics routes and Prisma aggregations. The endpoint `/api/program-applications/analytics` handles queries for application metrics, supporting distinct group-by configurations including absolute counts, groupings by `referralSource` or `country`, partner-specific breakdowns, and timeseries intervals.
```typescript
const aggregations = {
_count: {
visitedAt: true,
startedAt: true,
submittedAt: true,
approvedAt: true,
rejectedAt: true,
},
} as const;
```
Sources: [apps/web/app/ee/api/program-applications/analytics/route.ts:27-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/program-applications/analytics/route.ts#L27-L35)
Application event queries evaluate specific event stages through dedicated query hooks and parse stage identifiers (`visited`, `started`, `submitted`, `approved`) alongside view options like `timeseries` and `funnel`.
| Stage Identifier | Matching Event Field | Description |
| :--- | :--- | :--- |
| `visited` | `visitedAt` | Initial visit tracking on the partner program page |
| `started` | `startedAt` | Application form interaction initiation |
| `submitted` | `submittedAt` | Completed application submission |
| `approved` | `approvedAt` | Program manager approval of partner application |
Sources: [apps/web/app/ee/api/program-applications/analytics/route.ts:27-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/program-applications/analytics/route.ts#L27-L35), [apps/web/app/app.dub.co/dashboard/slug/ee/program/analytics/applications/use-applications-analytics-query.ts:9-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/analytics/applications/use-applications-analytics-query.ts#L9-L14)
> [!NOTE]
> When executing partner-specific application aggregations via `byPartnerId`, the system resolves partner records by filtering IDs that maintain active program enrollments in the target `programId`.
Sources: [apps/web/app/ee/api/program-applications/analytics/route.ts:174-187](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/program-applications/analytics/route.ts#L174-L187)
### Commissions and partner analytics routing
Partner performance and commission metrics are handled by `/api/partners/analytics` and partner profile analytics routes, aligning tracking data with earnings aggregations. Depending on the `groupBy` parameter (`count`, `timeseries`, or `top_links`), the route queries the `Commission` table using Prisma raw queries or aggregate functions with status filters (`pending`, `processed`, `paid`) and types such as `sale` or `referral`.
```typescript
if (groupBy === "count") {
const earnings = await prisma.commission.aggregate({
_sum: {
earnings: true,
},
where: {
type: "sale",
amount: {
gt: 0,
},
programId: programEnrollment.programId,
partnerId: programEnrollment.partnerId,
status: {
in: ["pending", "processed", "paid"],
},
createdAt: {
gte: startDate,
lt: endDate,
},
},
});
return NextResponse.json({
...analytics,
earnings: earnings._sum.earnings || 0,
});
}
```
Sources: [apps/web/app/ee/api/partners/analytics/route.ts:92-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partners/analytics/route.ts#L92-L118)
Partner profile program analytics endpoints evaluate large program thresholds and link counts before querying underlying analytics providers, returning fallback errors if Tinybird execution exceeds timeout thresholds.
| Parameter / Constant | Purpose | Context / Condition |
| :--- | :--- | :--- |
| `LARGE_PROGRAM_IDS` | Identifies high-volume programs | Checks program eligibility for optimized analytics aggregation |
| `LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS` | Commission threshold | Minimum commission cents required for detailed analytics queries |
| `MAX_PARTNER_LINKS_FOR_LOCAL_FILTERING` | Link optimization threshold | Determines whether to query by `partnerId` or specific `linkId` array |
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/analytics/route.ts:7-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/analytics/route.ts#L7-L10), [apps/web/app/ee/api/partner-profile/programs/programId/analytics/route.ts:86-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/analytics/route.ts#L86-L96)
> [!WARNING]
> If Tinybird times out after 30 seconds during heavy partner analytics queries, the API throws a `bad_request` DubApiError instructing the UI to prompt a page refresh, preventing unhandled 500 server errors.
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/analytics/route.ts:102-109](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/analytics/route.ts#L102-L109)
### Network referrals timeseries routing
Network referral timeseries data is aggregated via `/api/partner-profile/referrals/timeseries`, which requires partners to maintain an `approved` or `trusted` network status. The pipeline executes concurrent raw SQL queries against `Partner` and `Commission` tables using timezone conversion and date formatting maps.
```typescript
const [partnersResult, earningsResult] = await Promise.all([
prisma.$queryRaw<{ start: string; partners: number }[]>(
Prisma.sql`
SELECT
DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
COUNT(*) AS partners
FROM Partner
WHERE
referredByPartnerId = ${partner.id}
AND createdAt >= ${startDate}
AND createdAt < ${endDate}
GROUP BY start
ORDER BY start ASC
`,
),
prisma.$queryRaw<{ start: string; earnings: number }[]>(
Prisma.sql`
SELECT
DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
SUM(earnings) AS earnings
FROM Commission
WHERE
partnerId = ${partner.id}
AND programId = ${NETWORK_PROGRAM_ID}
AND type = ${CommissionType.referral}
AND status in ('pending', 'processed', 'paid')
AND createdAt >= ${startDate}
AND createdAt < ${endDate}
GROUP BY start
ORDER BY start ASC
`,
),
]);
```
Sources: [apps/web/app/ee/api/partner-profile/referrals/timeseries/route.ts:40-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/referrals/timeseries/route.ts#L40-L73)
## Public and shared dashboard delivery
### Password verification and dashboard page rendering
Shared analytics views are accessed via dynamic dashboard identifiers at `/share/[dashboardId]`. The page renderer fetches dashboard metadata using `getDashboard`, inspecting whether the targeted resource is tied to a specific link or folder. If no valid link or folder association exists, the server triggers a 404 response.
```tsx
export default async function DashboardPage(props: {
params: Promise<{ dashboardId: string }>;
}) {
const params = await props.params;
const data = await getDashboard({ id: params.dashboardId });
// if the dashboard, link, or folder doesn't exist
if (!data?.link && !data?.folder) {
notFound();
}
```
Sources: [apps/web/app/app.dub.co/share/share/dashboardId/page.tsx:31-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(share)/share/%5BdashboardId%5D/page.tsx#L31-L40)
When a dashboard enforces password protection, the server compares the cookie value stored under `dub_password_[dashboardId]` against the password hash configured on the dashboard record. If the cookie does not match, the page renders an authentication view featuring a decorative grid, an aurora gradient background, and a `DashboardPasswordForm` component.
```tsx
if (
data.password &&
(await cookies()).get(`dub_password_${params.dashboardId}`)?.value !==
data.password
) {
return (
Enter Password
This dashboard is password protected.
);
}
```
Sources: [apps/web/app/app.dub.co/share/share/dashboardId/page.tsx:42-94](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(share)/share/%5BdashboardId%5D/page.tsx#L42-L94)
> [!WARNING]
> If a shared dashboard requires a password and the matching cookie `dub_password_[dashboardId]` is absent or incorrect, the server bypasses the analytics component entirely and returns an unauthorized password entry view.
Sources: [apps/web/app/app.dub.co/share/share/dashboardId/page.tsx:42-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(share)/share/%5BdashboardId%5D/page.tsx#L42-L46)
### REST analytics endpoint authentication
The backend route `/api/analytics/dashboard` validates incoming query parameters via `parseAnalyticsQuery`, checking for `domain`, `key`, or `folderId` filters. Folders and links are looked up in Prisma to verify whether they expose a public `dashboard` configuration and whether a password is required.
```typescript
export const GET = async (req: Request) => {
try {
const searchParams = getSearchParams(req.url);
const parsedParams = parseAnalyticsQuery(searchParams);
const {
domain: domainFilter,
key,
folderId: folderIdFilter,
interval,
start,
end,
} = parsedParams;
// Extract string values for specific link/folder lookup
const domain = getFirstFilterValue(domainFilter);
const folderId = getFirstFilterValue(folderIdFilter);
if ((!domain || !key) && !folderId) {
throw new DubApiError({
code: "bad_request",
message: "Missing domain/key or folderId query parameters",
});
}
```
Sources: [apps/web/app/api/analytics/dashboard/route.ts:17-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/dashboard/route.ts#L17-L40)
| Entity Type | Lookup Strategy | Password Enforcement | Error Code on Missing Dashboard |
| :--- | :--- | :--- | :--- |
| `folderId` | `prisma.folder.findUnique` | Checked via `assertDashboardPassword` | `forbidden` |
| `demoLink` | Matched against `DUB_DEMO_LINKS` | None (public demo) | N/A |
| `link` | `prisma.link.findUnique` via `domain_key` | Checked via `assertDashboardPassword` | `forbidden` |
Sources: [apps/web/app/api/analytics/dashboard/route.ts:44-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/dashboard/route.ts#L44-L142)
The helper function `assertDashboardPassword` evaluates the `dashboard.password` property against the cookie `dub_password_${dashboard.id}`. If validation fails, a `DubApiError` with code `unauthorized` is thrown.
```typescript
async function assertDashboardPassword(dashboard: {
id: string;
password: string | null;
}) {
if (!dashboard.password) {
return;
}
const cookiePassword = (await cookies()).get(
`dub_password_${dashboard.id}`,
)?.value;
if (cookiePassword !== dashboard.password) {
throw new DubApiError({
code: "unauthorized",
message: "This dashboard is password protected",
});
}
}
```
Sources: [apps/web/app/api/analytics/dashboard/route.ts:204-222](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/dashboard/route.ts#L204-L222)
## Dataset and event CSV exports
### Analytics ZIP archive generation
Exporting comprehensive analytics datasets is handled by the server route `/api/analytics/export`, which returns a compressed ZIP archive containing multiple CSV breakdowns. The route enforces request rate limits via `RATELIMIT_POLICIES.analyticsExport` keyed to the workspace ID, and checks short link usage constraints using `throwIfClicksUsageExceeded`.
```typescript
await assertRateLimit({
policy: RATELIMIT_POLICIES.analyticsExport,
identifier: workspace.id,
});
throwIfClicksUsageExceeded(workspace);
```
Sources: [apps/web/app/api/analytics/export/route.ts:26-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts#L26-L31)
Query parameters are parsed using `parseAnalyticsQuery`. If an external ID, domain, or key filter is provided without an explicit link ID, the backend resolves the target link using `getLinkOrThrow` to scope the parameters accurately. Date ranges are validated against plan capabilities via `assertValidDateRangeForPlan`, and workspace-level permission requirements enforce `analytics.read`.
```typescript
const parsedParams = parseAnalyticsQuery(searchParams);
let {
interval,
start,
end,
folderId,
domain,
key,
linkId,
externalId,
programId,
} = parsedParams;
let programStartedAt: Date | null | undefined = null;
if (programId) {
const workspaceProgramId = getDefaultProgramIdOrThrow(workspace);
if (programId !== workspaceProgramId) {
throw new DubApiError({
code: "forbidden",
message: `Program ${programId} does not belong to workspace ${prefixWorkspaceId(workspace.id)}.`,
});
}
const program = await getProgramOrThrow({
workspaceId: workspace.id,
programId,
});
programStartedAt = program.startedAt;
}
let folderIdToVerify = getFirstFilterValue(folderId);
if (!linkId && (externalId || (domain && key))) {
const link = await getLinkOrThrow({
workspaceId: workspace.id,
linkId,
externalId,
domain: getFirstFilterValue(domain),
key,
});
parsedParams.linkId = {
operator: "IS",
sqlOperator: "IN",
values: [link.id],
};
parsedParams.domain = undefined;
if (link.folderId && !folderIdToVerify) {
folderIdToVerify = link.folderId;
}
}
if (folderIdToVerify) {
await verifyFolderAccess({
workspace,
userId: session.user.id,
folderId: folderIdToVerify,
requiredPermission: "folders.read",
});
}
assertValidDateRangeForPlan({
plan: workspace.plan,
dataAvailableFrom: workspace.createdAt,
interval,
start,
end,
});
```
Sources: [apps/web/app/api/analytics/export/route.ts:33-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts#L33-L101)
The underlying archive compilation is delegated to `exportAnalyticsToZip`, incorporating conversion tracking capabilities where permitted by the workspace plan. The resulting data is streamed back with a `Content-Type` header of `application/zip` and a default file attachment name.
```typescript
const zipData = await exportAnalyticsToZip({
params: analyticsParams,
workspaceId: workspace.id,
useComposite: canTrackConversions,
skipTopLinksForSingleLink: hasExactlyOneLinkIdFilter(parsedParams.linkId),
getDataAvailableFrom: (endpoint) =>
endpoint === "timeseries"
? programStartedAt ?? workspace.createdAt
: undefined,
...(programId && {
formatRows: formatProgramAnalyticsForExport,
}),
});
return new Response(zipData as unknown as BodyInit, {
headers: {
"Content-Type": "application/zip",
"Content-Disposition": "attachment; filename=analytics_export.zip",
},
});
```
Sources: [apps/web/app/api/analytics/export/route.ts:109-128](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts#L109-L128)
Partner profile program analytics follow a parallel export path at `/api/partner-profile/programs/[programId]/analytics/export`, utilizing partner authentication rules and applying distinct rate-limit policies.
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/analytics/export/route.ts:26-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/analytics/export/route.ts#L26-L31)
### Raw event CSV exports and threshold queuing
Exporting individual telemetry events to CSV is managed by the EE events export route at `/api/events/export`. This endpoint requires business, advanced, or enterprise plans along with `analytics.read` permissions, and enforces a strict threshold where requests exceeding `MAX_EVENTS_TO_EXPORT` (set to `1000`) are offloaded to background execution via QStash.
```typescript
const MAX_EVENTS_TO_EXPORT = 1000;
const exportQuerySchema = z
.object({
columns: z
.string()
.transform((c) => c.split(","))
.pipe(z.string().array()),
})
.passthrough();
// GET /api/events/export – export events to CSV (with async support if >1000 events)
export const GET = withWorkspace(
```
Sources: [apps/web/app/ee/api/events/export/route.ts:25-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts#L25-L37)
| Condition / Metric | Threshold Value | Handling Mechanism | Response Status |
| :--- | :--- | :--- | :--- |
| `MAX_EVENTS_TO_EXPORT` | `1000` events | Synchronous CSV generation for counts within limit | `200 OK` |
| Volume > threshold | `> 1000` events | Publish background job to `/api/cron/export/events/workspace` via QStash | `202 Accepted` |
Sources: [apps/web/app/ee/api/events/export/route.ts:25-149](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts#L25-L149)
When the event count is at or below the threshold, raw events are retrieved via `getEvents`, mapped against specified column accessors and names, converted into comma-separated values using `convertToCSV`, and returned as an attachment.
```typescript
const response = await getEvents({
...parsedParams,
event,
workspaceId: workspace.id,
limit: MAX_EVENTS_TO_EXPORT,
dataAvailableFrom,
});
const data = response.map((row) =>
Object.fromEntries(
columns.map((c) => [
eventsExportColumnNames?.[c] ?? capitalize(c),
eventsExportColumnAccessors[c]?.(row) ?? row?.[c],
]),
),
);
const csvData = convertToCSV(data);
return new Response(csvData, {
headers: {
"Content-Type": "application/csv",
"Content-Disposition": `attachment; filename=${event}_export.csv`,
},
});
```
Sources: [apps/web/app/ee/api/events/export/route.ts:151-175](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts#L151-L175)
> [!CAUTION]
> Requesting an event export that exceeds 1,000 matching items causes the server to immediately short-circuit synchronous generation, dispatch a background worker payload via QStash, and return an empty `202 Accepted` JSON response instead of a downloadable file.
Sources: [apps/web/app/ee/api/events/export/route.ts:137-149](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts#L137-L149)
### Client-side export initiation
The client-side trigger for downloading analytics packages is encapsulated within `AnalyticsExportButton`. The component reads workspace context parameters via `AnalyticsContext` to determine whether to call the standard workspace export route or a partner-specific export path.
```tsx
export function AnalyticsExportButton({
setOpenPopover,
}: {
setOpenPopover: Dispatch>;
}) {
const [loading, setLoading] = useState(false);
const { queryString, baseApiPath, partnerPage } =
useContext(AnalyticsContext);
async function exportData() {
setLoading(true);
try {
const exportPath = partnerPage
? `${baseApiPath}/export`
: "/api/analytics/export";
```
Sources: [apps/web/ui/analytics/analytics-export-button.tsx:7-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/analytics-export-button.tsx#L7-L22)
Upon user interaction, the component executes a `GET` request against the resolved export route with active query parameters, handles error payloads by extracting nested API error messages, and programmatically generates an object URL blob download named with an ISO timestamp.
```tsx
const response = await fetch(`${exportPath}?${queryString}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
let message = response.statusText;
try {
const body = await response.json();
if (body?.error?.message) {
message = body.error.message;
}
} catch {
// ignore JSON parse errors
}
throw new Error(message);
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `Dub Analytics Export - ${new Date().toISOString()}.zip`;
a.click();
window.URL.revokeObjectURL(url);
} catch (error) {
throw error instanceof Error ? error : new Error(String(error));
} finally {
setLoading(false);
}
}
```
Sources: [apps/web/ui/analytics/analytics-export-button.tsx:23-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/analytics-export-button.tsx#L23-L57)
```mermaid
sequenceDiagram
participant User as AnalyticsExportButton
participant API as /api/analytics/export
participant QStash as QStash / Cron Worker
User->>API: GET /api/analytics/export?queryString
API->>API: Rate limit check & usage validation
API->>API: Parse query & verify folder/link access
alt Events export count > 1000
API->>QStash: Publish JSON job to cron export endpoint
API-->>User: Return 202 Accepted (empty JSON)
else Standard ZIP export
API->>API: Compile analytics breakdowns into ZIP archive
API-->>User: Return application/zip blob (download triggered)
end
```
Sources: [apps/web/app/api/analytics/export/route.ts:26-128](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts#L26-L128), [apps/web/app/ee/api/events/export/route.ts:37-149](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts#L37-L149), [apps/web/ui/analytics/analytics-export-button.tsx:23-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/analytics/analytics-export-button.tsx#L23-L51)
## Related
- [Tinybird Analytics](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics)
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
---
## Technical docs: PATCH Update partner network status
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/adminupdatepartnernetworkstatus
## Parameters
## Request Body
Status update details
## Responses
## Try It
---
## Technical docs: POST Add or update partner platform
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/adminupsertpartnerplatform
## Parameters
## Request Body
Platform details
## Responses
## Try It
---
## Technical docs: Audit Logs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/audit-logs
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/api/audit-logs/export/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/audit-logs/export/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/security/audit-logs.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/security/audit-logs.tsx)
- [apps/web/app/ee/api/events/export/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/export/route.ts)
- [apps/web/app/ee/api/cron/export/events/workspace/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/export/events/workspace/route.ts)
- [apps/web/app/api/analytics/export/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/analytics/export/route.ts)
- [apps/web/lib/api/audit-logs/get-audit-logs.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/get-audit-logs.ts)
- [apps/web/lib/api/audit-logs/record-audit-log.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts)
- [apps/web/app/api/logs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/route.ts)
- [apps/web/lib/swr/use-activity-logs.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts)
- [apps/web/app/api/activity-logs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/activity-logs/route.ts)
- [apps/web/app/ee/api/partner-profile/programs/programId/activity-logs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/activity-logs/route.ts)
- [apps/web/lib/api/audit-logs/schemas.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts)
- [apps/web/app/ee/api/events/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/events/route.ts)
- [apps/web/app/api/logs/logId/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/%5BlogId%5D/route.ts)
- [apps/web/app/ee/api/admin/events/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/events/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/logs/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/logs/page.tsx)
- [apps/web/app/api/logs/timeseries/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/timeseries/route.ts)
- [apps/web/lib/api/activity-log/track-activity-log.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts)
- [apps/web/app/api/logs/count/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/count/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/security/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/security/page-client.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/webhooks/webhookId/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/webhooks/%5BwebhookId%5D/page-client.tsx)
- [apps/web/lib/api/activity-log/track-reward-overrides.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-reward-overrides.ts)
- [apps/web/app/api/workspaces/idOrSlug/import/importId/download/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/%5BimportId%5D/download/route.ts)
- [apps/web/lib/api/commissions/track-commission-update-activity-log.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts)
- [apps/web/lib/api-logs/capture-webhook-log.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api-logs/capture-webhook-log.ts)
- [apps/web/ui/activity-logs/activity-log-registry.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/logs/logId/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/logs/%5BlogId%5D/page.tsx)
- [apps/web/prisma/schema/activity.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/activity.prisma)
- [apps/web/app/api/webhooks/webhookId/events/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/%5BwebhookId%5D/events/route.ts)
- [apps/web/lib/zod/schemas/activity-log.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/activity-log.ts)
## Overview
Dub maintains a multi-layered audit and telemetry architecture that captures administrative actions, partner modifications, workspace activities, and API or webhook requests across the platform. Administrative security events and audit records are ingested directly into [Tinybird Analytics](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/tinybird-analytics) and ClickHouse [apps/web/lib/api/audit-logs/record-audit-log.ts:75-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L75-L79), [apps/web/lib/api/audit-logs/get-audit-logs.ts:38-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/get-audit-logs.ts#L38-L49), whereas granular workspace operational changes—such as partner state transitions, reward overrides, and commission adjustments—are persisted relationally via Prisma [apps/web/prisma/schema/activity.prisma:1-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/activity.prisma#L1-L16), [apps/web/lib/api/activity-log/track-activity-log.ts:34-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L34-L65). This infrastructure allows enterprises to query structured historical logs, enforce strict date range retention limits based on subscription plans [apps/web/app/api/logs/route.ts:13-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/route.ts#L13-L21), export audit datasets or event streams as downloadable CSVs [apps/web/app/ee/api/audit-logs/export/route.ts:40-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/audit-logs/export/route.ts#L40-L47), and render dedicated activity timelines directly inside the dashboard UI [apps/web/ui/activity-logs/activity-log-registry.tsx:71-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L71-L129).
Sources: [apps/web/lib/api/audit-logs/record-audit-log.ts:75-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L75-L79), [apps/web/lib/api/audit-logs/get-audit-logs.ts:38-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/get-audit-logs.ts#L38-L49), [apps/web/prisma/schema/activity.prisma:1-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/activity.prisma#L1-L16), [apps/web/lib/api/activity-log/track-activity-log.ts:34-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L34-L65), [apps/web/app/api/logs/route.ts:13-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/route.ts#L13-L21), [apps/web/app/ee/api/audit-logs/export/route.ts:40-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/audit-logs/export/route.ts#L40-L47), [apps/web/ui/activity-logs/activity-log-registry.tsx:71-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L71-L129)
## Tinybird Audit Event Ingestion
### Event Transformation and Enrichment
Administrative and security audit events across Dub are processed through a structured ingestion pipeline that shapes incoming records, resolves network context, and transmits payload telemetry to Tinybird. When `recordAuditLog` is invoked with single or multiple audit log inputs, the system resolves client IP addresses by inspecting request instances via `@vercel/functions` or falling back to workspace header helpers before transformation [apps/web/lib/api/audit-logs/record-audit-log.ts:47-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L47-L56).
The `transformAuditLogTB` helper validates input schemas against `recordAuditLogInputSchema`, extracts the `user-agent` from incoming Next.js headers, and builds structured records [apps/web/lib/api/audit-logs/record-audit-log.ts:13-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L13-L44). Unique identifiers are generated with an `audit_` prefix, workspace identifiers are normalized via `prefixWorkspaceId`, and complex structures such as `targets` and `metadata` are serialized into JSON strings [apps/web/lib/api/audit-logs/record-audit-log.ts:28-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L28-L44). Batch or individual payloads are then submitted through `recordAuditLogTB`, which builds an ingest endpoint targeting the `dub_audit_logs` datasource with `wait: true` configuration [apps/web/lib/api/audit-logs/record-audit-log.ts:47-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L47-L79).
> [!NOTE]
> If recording an audit log fails during transmission to Tinybird, the error is caught, logged to console alongside the serialized audit payloads, and dispatched to error tracking with user notification flags enabled via `@dub/utils` loggers [apps/web/lib/api/audit-logs/record-audit-log.ts:58-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L58-L72).
Sources: [apps/web/lib/api/audit-logs/record-audit-log.ts:13-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/record-audit-log.ts#L13-L79)
### Action Types and Target Schemas
Audit events track specific domain operations across programs, rewards, discounts, partner enrollments, commissions, payouts, groups, bounties, and submissions. The accepted action identifiers are strictly constrained by validation schemas before reaching the persistence layer [apps/web/lib/api/audit-logs/schemas.ts:32-94](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L32-L94).
| Domain Category | Valid Action Identifiers | Sources |
| :--- | :--- | :--- |
| Program | `program.created`, `program.updated` | [apps/web/lib/api/audit-logs/schemas.ts:32-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L32-L36) |
| Rewards | `reward.created`, `reward.updated`, `reward.deleted` | [apps/web/lib/api/audit-logs/schemas.ts:37-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L37-L41) |
| Discounts | `discount.created`, `discount.updated`, `discount.deleted`, `discount_code.created`, `discount_code.deleted` | [apps/web/lib/api/audit-logs/schemas.ts:42-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L42-L48) |
| Partner Applications | `partner_application.approved`, `partner_application.rejected` | [apps/web/lib/api/audit-logs/schemas.ts:49-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L49-L52) |
| Partner Enrollments | `partner.created`, `partner.archived`, `partner.invited`, `partner.invite_deleted`, `partner.invite_resent`, `partner.enrollment_updated`, `partner.deactivated`, `partner.reactivated`, `partner.banned`, `partner.unbanned`, `partner.deleted` | [apps/web/lib/api/audit-logs/schemas.ts:53-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L53-L65) |
| Auto Approve Partner | `auto_approve_partner.enabled`, `auto_approve_partner.disabled` | [apps/web/lib/api/audit-logs/schemas.ts:66-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L66-L69) |
| Commissions & Clawbacks | `commission.created`, `commission.updated`, `clawback.created`, `commission.canceled`, `commission.marked_fraud`, `commission.marked_duplicate` | [apps/web/lib/api/audit-logs/schemas.ts:70-77](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L70-L77) |
| Payouts | `payout.confirmed`, `payout.marked_paid` | [apps/web/lib/api/audit-logs/schemas.ts:78-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L78-L81) |
| Groups | `group.created`, `group.updated`, `group.deleted` | [apps/web/lib/api/audit-logs/schemas.ts:82-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L82-L86) |
| Bounties | `bounty.created`, `bounty.updated`, `bounty.deleted`, `bounty_submission.approved`, `bounty_submission.rejected`, `bounty_submission.reopened` | [apps/web/lib/api/audit-logs/schemas.ts:87-94](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L87-L94) |
Sources: [apps/web/lib/api/audit-logs/schemas.ts:32-94](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/schemas.ts#L32-L94)
## Audit Log Retrieval and Export
### Querying Tinybird and ClickHouse
Audit records are retrieved by querying ClickHouse via Tinybird pipes using the `getAuditLogs` function. This utility executes the `get_audit_logs` pipe configured with strict input validation schemas and response serialization rules.
```typescript
export const getAuditLogs = async ({
workspaceId,
programId,
start,
end,
}: {
start: Date;
end: Date;
workspaceId: string;
programId: string;
}) => {
const pipe = tb.buildPipe({
pipe: "get_audit_logs",
parameters: auditLogFilterSchemaTB,
data: auditLogResponseSchemaTB,
});
const events = await pipe({
workspaceId,
programId,
start: formatUTCDateTimeClickhouse(start),
end: formatUTCDateTimeClickhouse(end),
});
return events.data;
```
Sources: [apps/web/lib/api/audit-logs/get-audit-logs.ts:27-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/get-audit-logs.ts#L27-L51)
The query parameters require a prefixed workspace identifier, program identifier, and formatted UTC date strings parsed through ClickHouse datetime formatting utilities.
```typescript
export const auditLogFilterSchemaTB = z.object({
workspaceId: z.string().transform(prefixWorkspaceId),
programId: z.string(),
start: z.string(),
end: z.string(),
});
export const auditLogResponseSchemaTB = z.object({
id: z.string(),
timestamp: z.string(),
action: z.string(),
actor_id: z.string(),
actor_type: z.string(),
actor_name: z.string(),
description: z.string(),
ip_address: z.string(),
user_agent: z.string(),
targets: z.string(),
metadata: z.string(),
});
```
Sources: [apps/web/lib/api/audit-logs/get-audit-logs.ts:6-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/audit-logs/get-audit-logs.ts#L6-L25)
### API Export Endpoint and Plan Enforcement
The backend export workflow is handled by a POST route secured via `withWorkspace`. The route requires an enterprise plan capability and ownership or member roles before processing requests.
```typescript
export const POST = withWorkspace(
async ({ req, workspace }) => {
const { start, end } = auditLogExportQuerySchema.parse(
await parseRequestBody(req),
);
if (!start || !end) {
throw new DubApiError({
code: "bad_request",
message: "Must provide start and end dates.",
});
}
const { canExportAuditLogs } = getPlanCapabilities(workspace.plan);
if (!canExportAuditLogs) {
throw new DubApiError({
code: "forbidden",
message: "You are not authorized to export audit logs.",
});
}
const programId = getDefaultProgramIdOrThrow(workspace);
const auditLogs = await getAuditLogs({
workspaceId: workspace.id,
programId,
start: new Date(start),
end: new Date(end),
});
const csvData = convertToCSV(auditLogs);
return new Response(csvData, {
headers: {
"Content-Type": "application/csv",
"Content-Disposition": `attachment;`,
},
});
},
{
requiredRoles: ["owner", "member"],
requiredPlan: ["enterprise"],
},
);
```
Sources: [apps/web/app/ee/api/audit-logs/export/route.ts:16-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/audit-logs/export/route.ts#L16-L60)
> [!WARNING]
> Requests lacking `start` and `end` query parameters or originating from workspaces without enterprise plan capabilities throw explicit `DubApiError` exceptions with `bad_request` or `forbidden` error codes.
Sources: [apps/web/app/ee/api/audit-logs/export/route.ts:22-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/audit-logs/export/route.ts#L22-L36)
### Frontend Client and CSV Generation
The client interface component manages date interval selections using `SimpleDateRangePicker` and triggers file downloads by converting retrieved audit logs into CSV payloads.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/security/audit-logs.tsx:22-66](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/security/audit-logs.tsx#L22-L66)
When export permissions are absent on lower-tier workspace plans, the interface disables the date picker and export button, presenting an upgrade callout prompting users to transition to the Enterprise Plan.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/security/audit-logs.tsx:106-130](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/security/audit-logs.tsx#L106-L130)
## Workspace Activity Log Persistence
### Database Schema and Prisma Modeling
Activity logs within [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs) are modeled using the `ActivityLog` Prisma model inside the database schema. Each record captures identifiers for the workspace, program, parent resource, and specific target resource, along with action metadata, descriptive text, optional batching tokens, and JSON-encoded change sets.
```
model ActivityLog {
id String @id @default(cuid())
workspaceId String
programId String
parentResourceType String?
parentResourceId String?
resourceType String
resourceId String
userId String?
action String
description String? @db.Text
batchId String?
changeSet Json?
createdAt DateTime @default(now())
```
Sources: [apps/web/prisma/schema/activity.prisma:1-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/activity.prisma#L1-L15)
The table references user entities via a foreign key relation on `userId` and maintains performance indexes on `[resourceType, resourceId]` and `userId`.
```
user User? @relation(fields: [userId], references: [id])
@@index([resourceType, resourceId])
@@index(userId)
}
```
Sources: [apps/web/prisma/schema/activity.prisma:16-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/activity.prisma#L16-L20)
### Activity Tracking and Filtering Logic
The programmatic insertion of activity logs is managed by `trackActivityLog` and transaction-bound `trackActivityLogsTx` utilities. These functions filter incoming entries to ensure that actions either require no change set or contain a non-empty change object before executing bulk creations.
```typescript
const ACTIONS_WITHOUT_CHANGE_SET: ActivityLogAction[] = [
"submittedLead.created",
"reward.created",
"reward.deleted",
];
export interface TrackActivityLogInput
extends Pick<
Prisma.ActivityLogUncheckedCreateInput,
| "workspaceId"
| "programId"
| "resourceId"
| "userId"
| "description"
| "parentResourceType"
| "parentResourceId"
| "batchId"
> {
resourceType: ActivityLogResourceType;
action: ActivityLogAction;
changeSet?: ChangeSet;
}
export const trackActivityLog = async (
input: TrackActivityLogInput | TrackActivityLogInput[],
) => {
let inputs = Array.isArray(input) ? input : [input];
inputs = inputs.filter(
(i) =>
ACTIONS_WITHOUT_CHANGE_SET.includes(i.action) ||
(i.changeSet && Object.keys(i.changeSet).length > 0),
);
if (inputs.length === 0) {
return;
}
```
Sources: [apps/web/lib/api/activity-log/track-activity-log.ts:11-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L11-L47)
```typescript
export const trackActivityLogsTx = async ({
tx,
logs,
}: {
tx: Prisma.TransactionClient;
logs: TrackActivityLogInput | TrackActivityLogInput[];
}) => {
let inputs = Array.isArray(logs) ? logs : [logs];
inputs = inputs.filter(
(i) =>
ACTIONS_WITHOUT_CHANGE_SET.includes(i.action) ||
(i.changeSet && Object.keys(i.changeSet).length > 0),
);
if (inputs.length === 0) {
return;
}
```
Sources: [apps/web/lib/api/activity-log/track-activity-log.ts:68-85](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L68-L85)
Actions configured to bypass the change set requirement include submission creations and reward creations or deletions.
| Action Name | Description / Behavior | Sources |
| :--- | :--- | :--- |
| `submittedLead.created` | Bypasses change set validation during lead submission creation | [apps/web/lib/api/activity-log/track-activity-log.ts:11-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L11-L15) |
| `reward.created` | Bypasses change set validation when a new reward entity is instantiated | [apps/web/lib/api/activity-log/track-activity-log.ts:11-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L11-L15) |
| `reward.deleted` | Bypasses change set validation upon reward removal | [apps/web/lib/api/activity-log/track-activity-log.ts:11-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L11-L15) |
Sources: [apps/web/lib/api/activity-log/track-activity-log.ts:11-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L11-L15)
> [!NOTE]
> If an input array contains entries where actions lack the explicit exemption and have an empty or missing `changeSet`, those entries are filtered out and omitted from database writes entirely.
Sources: [apps/web/lib/api/activity-log/track-activity-log.ts:39-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-activity-log.ts#L39-L43)
### Reward and Commission Activity Trackers
Partner and link-level reward overrides fetch previous and subsequent reward and discount records to construct serialized activity snapshots. The tracking functions verify that changes have occurred across click, lead, or sale reward identifiers or discount configurations before persisting log entries.
```typescript
const rewardFields = [
["clickReward", previous.clickRewardId, next.clickRewardId],
["leadReward", previous.leadRewardId, next.leadRewardId],
["saleReward", previous.saleRewardId, next.saleRewardId],
] as const;
const changedRewardFields = rewardFields.filter(
([, oldId, newId]) => oldId !== newId,
);
const discountChanged = previous.discountId !== next.discountId;
if (changedRewardFields.length === 0 && !discountChanged) {
return;
}
```
Sources: [apps/web/lib/api/activity-log/track-reward-overrides.ts:44-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/activity-log/track-reward-overrides.ts#L44-L57)
Commission updates monitor modifications specifically across amount, earnings, and status fields using resource diff utilities. Bulk status updates group commissions by program to delegate consistent status changes efficiently.
```typescript
const COMMISSION_ACTIVITY_FIELDS = ["amount", "earnings", "status"];
export function toCommissionActivitySnapshot(
commission: Pick,
): CommissionActivitySnapshot {
return {
amount: commission.amount,
earnings: commission.earnings,
status: commission.status,
};
}
```
Sources: [apps/web/lib/api/commissions/track-commission-update-activity-log.ts:19-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts#L19-L29)
```typescript
export async function trackCommissionStatusUpdatesByProgram({
commissions,
payouts,
newStatus = "paid",
}: {
commissions: Pick<
Commission,
"id" | "amount" | "earnings" | "status" | "programId"
>[];
payouts: Array<{ program: { id: string; workspaceId: string } }>;
newStatus?: CommissionStatus;
}) {
if (commissions.length === 0) {
return;
}
const workspaceByProgram = new Map(
payouts.map((p) => [p.program.id, p.program.workspaceId]),
);
const commissionsByProgram = groupBy(commissions, (c) => c.programId);
```
Sources: [apps/web/lib/api/commissions/track-commission-update-activity-log.ts:103-124](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts#L103-L124)
## Activity Log Querying and UI Rendering
### Workspace and Partner API Endpoints
Activity log retrieval is divided between internal workspace management routes and partner-facing profile endpoints. The workspace route `/api/activity-logs` is protected by `withWorkspace` middleware, validating query parameters via `getActivityLogsQuerySchema` and fetching up to 100 entries ordered by creation date descending with user relations included.
```typescript
export const GET = withWorkspace(async ({ workspace, searchParams }) => {
const { resourceType, resourceId, parentResourceId, action } =
getActivityLogsQuerySchema.parse(searchParams);
const programId = getDefaultProgramIdOrThrow(workspace);
const activityLogs = await prisma.activityLog.findMany({
where: {
programId,
resourceType,
resourceId,
parentResourceId,
action,
},
orderBy: {
createdAt: "desc",
},
take: 100,
include: {
user: true,
},
});
```
Sources: [apps/web/app/api/activity-logs/route.ts:13-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/activity-logs/route.ts#L13-L34)
When querying partner resources, the workspace endpoint automatically polyfills a initial `partner.groupChanged` activity log if a corresponding program enrollment exists, referencing the enrollment creation date and group details.
```typescript
if (resourceType === "partner" && resourceId) {
const programEnrollment = await prisma.programEnrollment.findUnique({
where: {
partnerId_programId: {
partnerId: resourceId,
programId,
},
},
select: {
createdAt: true,
groupId: true,
partnerGroup: {
select: {
name: true,
},
},
},
});
if (programEnrollment) {
parsedActivityLogs.push({
id: uuid(),
action: "partner.groupChanged",
description: null,
createdAt: programEnrollment.createdAt,
user: null,
changeSet: {
group: {
old: null,
new: parsedActivityLogs[parsedActivityLogs.length - 1]?.changeSet
?.group?.old ?? {
id: programEnrollment.groupId,
name: programEnrollment.partnerGroup?.name,
},
},
},
});
}
```
Sources: [apps/web/app/api/activity-logs/route.ts:39-75](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/activity-logs/route.ts#L39-L75)
Conversely, the partner profile endpoint at `/(ee)/api/partner-profile/programs/[programId]/activity-logs/route.ts` is secured with `withPartnerProfile` and restricts querying strictly to the `submittedLead` resource type. It validates that the requested lead identifier belongs to the authenticated partner and program, and explicitly strips internal user identities (`user: null`) from the serialized response payload.
```typescript
export const GET = withPartnerProfile(
async ({ partner, params, searchParams }) => {
const { resourceType, resourceId, action } =
getActivityLogsQuerySchema.parse(searchParams);
// Limit to submitted lead for now
if (resourceType !== "submittedLead") {
throw new DubApiError({
code: "bad_request",
message: "Resource type must be submitted lead.",
});
}
const programEnrollment = await getProgramEnrollmentOrThrow({
partnerId: partner.id,
programId: params.programId,
include: {},
});
// Check if the resource is a referral and belongs to the program and partner
const lead = await prisma.submittedLead.findUnique({
where: {
id: resourceId,
programId: programEnrollment.programId,
partnerId: partner.id,
},
select: {
id: true,
},
});
if (!lead) {
throw new DubApiError({
code: "not_found",
message: "Submitted lead not found.",
});
}
const activityLogs = await prisma.activityLog.findMany({
where: {
programId: programEnrollment.programId,
resourceType,
resourceId,
action,
},
orderBy: {
createdAt: "desc",
},
take: 100,
});
// Hide the workspace user who made each change from the partner
return NextResponse.json(
z
.array(activityLogSchema)
.parse(activityLogs.map((log) => ({ ...log, user: null }))),
);
```
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/activity-logs/route.ts:12-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/activity-logs/route.ts#L12-L68)
> [!WARNING]
> Requests to the partner profile activity logs endpoint with any `resourceType` other than `submittedLead` throw an immediate `DubApiError` with a `bad_request` status code.
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/activity-logs/route.ts:17-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/activity-logs/route.ts#L17-L23)
### Client SWR Hook and Request Guardrails
The client-side `useActivityLogs` hook wraps SWR to fetch activity logs for a specific resource within the current workspace context retrieved from `useWorkspace`.
```typescript
export function useActivityLogs({
query,
enabled = true,
}: {
query?: GetActivityLogsQuery;
enabled?: boolean;
} = {}) {
const { id: workspaceId } = useWorkspace();
const searchParams = query
? new URLSearchParams({
workspaceId: workspaceId!,
...query,
}).toString()
: "";
const requestEnabled =
enabled &&
workspaceId &&
query?.resourceType &&
(query?.parentResourceId || query?.resourceId);
const { data, error, isLoading, mutate } = useSWR(
requestEnabled && `/api/activity-logs?${searchParams}`,
fetcher,
{
keepPreviousData: true,
},
);
return {
activityLogs: data,
error,
loading: isLoading,
mutate,
};
```
Sources: [apps/web/lib/swr/use-activity-logs.ts:6-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L6-L41)
The hook evaluates an explicit `requestEnabled` boolean to determine whether SWR should execute the network request.
```typescript
const requestEnabled =
enabled &&
workspaceId &&
query?.resourceType &&
(query?.parentResourceId || query?.resourceId);
```
Sources: [apps/web/lib/swr/use-activity-logs.ts:22-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L22-L27)
| Condition Variable | Type / Requirement | Description | Sources |
| :--- | :--- | :--- | :--- |
| `enabled` | boolean (default: `true`) | Optional toggle flag passed to the hook argument | [apps/web/lib/swr/use-activity-logs.ts:8-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L8-L11) |
| `workspaceId` | string | Active workspace identifier resolved from `useWorkspace()` | [apps/web/lib/swr/use-activity-logs.ts:13-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L13-L24) |
| `resourceType` | string | Mandatory property inside the `query` object | [apps/web/lib/swr/use-activity-logs.ts:25-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L25-L25) |
| `parentResourceId` \| `resourceId` | string | At least one resource identifier must be provided in the query | [apps/web/lib/swr/use-activity-logs.ts:26-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L26-L26) |
Sources: [apps/web/lib/swr/use-activity-logs.ts:8-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-activity-logs.ts#L8-L27)
### UI Registry and Action Renderers
The activity log UI layer maps distinct action strings to specialized React components and UI icons using registries defined in `activity-log-registry.tsx`. The actor type is classified via `getActorType`, returning `"USER"` if a user relation is present or `"SYSTEM"` otherwise.
```tsx
export type ActorType = "USER" | "SYSTEM";
type ActivityLogRenderer = (props: { log: ActivityLog }) => ReactNode;
export function getActorType(log: ActivityLog): ActorType {
return log.user ? "USER" : "SYSTEM";
}
```
Sources: [apps/web/ui/activity-logs/activity-log-registry.tsx:35-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L35-L41)
Partner status actions encompass a fixed set of lifecycle events mapped to status change renderers and dotted circle icons.
```tsx
const PARTNER_STATUS_ACTIONS = [
"partner_application.approved",
"partner_application.rejected",
"partner.banned",
"partner.unbanned",
"partner.deactivated",
"partner.reactivated",
"partner.archived",
"partner.unarchived",
] as const satisfies readonly ActivityLogAction[];
```
Sources: [apps/web/ui/activity-logs/activity-log-registry.tsx:24-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L24-L33)
| Activity Action Constant | Icon Component | Renderer Component | Sources |
| :--- | :--- | :--- | :--- |
| `partner.groupChanged` | `UserArrowRight` | `PartnerGroupChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:46-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L46-L78) |
| `partner.rewardChanged` | `MoneyBill2` | `PartnerRewardChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:47-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L47-L82) |
| `partner.discountChanged` | `DiscountCode` | `PartnerDiscountChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:48-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L48-L86) |
| `link.rewardChanged` | `MoneyBill2` | `PartnerRewardChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:49-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L49-L90) |
| `link.discountChanged` | `DiscountCode` | `PartnerDiscountChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:50-94](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L50-L94) |
| Partner Status Actions (8 types) | `CircleDotted` | `PartnerStatusChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:24-98](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L24-L98) |
| `submittedLead.created` | `FileSend` | `SubmittedLeadCreatedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:55-102](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L55-L102) |
| Submitted Lead Status Actions (6 types) | `UserClock` | `SubmittedLeadStatusChangedRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:56-115](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L56-L115) |
| Reward Actions (6 types) | `MoneyBill2` / `Pen2` / `CircleMinus` / `CirclePlusIcon` | `RewardActivityRenderer` | [apps/web/ui/activity-logs/activity-log-registry.tsx:63-128](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L63-L128) |
Sources: [apps/web/ui/activity-logs/activity-log-registry.tsx:24-128](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L24-L128)
> [!TIP]
> If an activity log action lacks a registered icon mapping in `ACTIVITY_LOG_ICONS`, `getActivityLogIcon` automatically falls back to rendering a neutral informational icon (`CircleInfo`).
Sources: [apps/web/ui/activity-logs/activity-log-registry.tsx:141-149](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/activity-log-registry.tsx#L141-L149)
## API Request and Webhook Logging
### Request Capture and Endpoints
Incoming API requests and webhooks are recorded via logging utilities and exposed through workspace endpoints. The webhook capture utility parses request and response payloads, mapping incoming paths to specific actors using `WEBHOOK_REQUEST_ACTORS_BY_PATH` before recording logs with `recordApiLog`.
```typescript
export async function captureWebhookLog({
workspaceId,
method,
path,
statusCode,
duration,
requestBody,
responseBody,
userAgent,
}: {
workspaceId: string;
method: string;
path: keyof typeof WEBHOOK_REQUEST_ACTORS_BY_PATH;
statusCode: number;
duration: number;
requestBody: unknown;
responseBody: unknown;
userAgent: string | null;
}) {
const actor = WEBHOOK_REQUEST_ACTORS_BY_PATH[path];
return await recordApiLog({
workspaceId,
method,
path,
routePattern: path,
statusCode,
duration,
userAgent,
requestBody,
responseBody: await parseResponseBody(responseBody),
tokenId: null,
userId: actor.id,
requestType: "webhook",
});
}
```
Sources: [apps/web/lib/api-logs/capture-webhook-log.ts:16-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api-logs/capture-webhook-log.ts#L16-L51)
Workspace API routes process query parameters, enforce plan retention rules, and return JSON responses for request logs, counts, and timeseries aggregations.
| Endpoint Route | HTTP Method | Required Permissions | Required Plan | Sources |
| :--- | :--- | :--- | :--- | :--- |
| `/api/logs` | `GET` | `workspaces.read` | Any | [apps/web/app/api/logs/route.ts:9-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/route.ts#L9-L40) |
| `/api/logs/:logId` | `GET` | `workspaces.read` | Any | [apps/web/app/api/logs/logId/route.ts:9-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/%5BlogId%5D/route.ts#L9-L44) |
| `/api/logs/timeseries` | `GET` | `workspaces.read` | Any | [apps/web/app/api/logs/timeseries/route.ts:8-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/timeseries/route.ts#L8-L36) |
| `/api/logs/count` | `GET` | `workspaces.read` | Any | [apps/web/app/api/logs/count/route.ts:8-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/count/route.ts#L8-L34) |
| `/api/webhooks/[webhookId]/events` | `GET` | `webhooks.read` | `business`, `advanced`, `enterprise` | [apps/web/app/api/webhooks/webhookId/events/route.ts:7-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/%5BwebhookId%5D/events/route.ts#L7-L33) |
Sources: [apps/web/app/api/logs/route.ts:9-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/route.ts#L9-L40), [apps/web/app/api/logs/logId/route.ts:9-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/%5BlogId%5D/route.ts#L9-L44), [apps/web/app/api/logs/timeseries/route.ts:8-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/timeseries/route.ts#L8-L36), [apps/web/app/api/logs/count/route.ts:8-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/count/route.ts#L8-L34), [apps/web/app/api/webhooks/webhookId/events/route.ts:7-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/%5BwebhookId%5D/events/route.ts#L7-L33)
## Related
- [Admin Dashboard](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/admin-dashboard)
---
## Technical docs: Reward Rules
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/reward-rules
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/api/sales/construct-reward-amount.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/construct-reward-amount.ts)
- [apps/web/lib/zod/schemas/rewards.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts)
- [apps/web/lib/api/rewards/validate-reward.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/rewards/validate-reward.ts)
- [apps/web/lib/partners/determine-partner-reward.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/determine-partner-reward.ts)
- [apps/web/ui/partners/rewards/rewards-logic.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/rewards-logic.tsx)
- [apps/web/lib/partners/get-reward-amount.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/get-reward-amount.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/groups/groupSlug/rewards/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/groups/%5BgroupSlug%5D/rewards/page.tsx)
- [apps/web/lib/partners/evaluate-reward-conditions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts)
- [apps/web/lib/rewards/resolve-partner-link-rewards.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/resolve-partner-link-rewards.ts)
- [apps/web/lib/rewards/format-reward-condition.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/format-reward-condition.ts)
- [apps/web/lib/rewards/validate-tooltip-suggestion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/validate-tooltip-suggestion.ts)
- [apps/web/lib/ai/review-reward-tooltip.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/ai/review-reward-tooltip.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx)
- [apps/web/lib/partners/get-group-rewards-and-discount.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/get-group-rewards-and-discount.ts)
- [apps/web/ui/partners/rewards/reward-event-descriptions.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/reward-event-descriptions.tsx)
- [apps/web/app/ee/app.dub.co/embed/referrals/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx)
- [apps/web/lib/rewards/resolve-click-reward.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/resolve-click-reward.ts)
- [apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx)
- [apps/web/app/ee/api/workflows/create-partner-commission/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts)
- [apps/web/lib/ai/generate-reward.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/ai/generate-reward.ts)
- [apps/web/ui/partners/rewards/custom-reward-builder.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/custom-reward-builder.tsx)
- [apps/web/lib/partner-referrals/create-referral-commission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-referral-commission.ts)
- [apps/web/ui/partners/custom-reward-description.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/custom-reward-description.tsx)
- [apps/web/ui/partners/rewards/ai-reward-builder.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/ai-reward-builder.tsx)
- [apps/web/ui/partners/rewards/reward-quality.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/reward-quality.tsx)
- [apps/web/ui/partners/format-reward-description.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/format-reward-description.ts)
- [apps/web/ui/partners/program-reward-modifiers-tooltip.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx)
- [apps/web/lib/api/sales/calculate-sale-earnings.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/calculate-sale-earnings.ts)
- [apps/web/app/ee/app.dub.co/new-program/slug/program/new/rewards/form.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/(new-program)/%5Bslug%5D/program/new/rewards/form.tsx)
- [apps/web/lib/ai/ai-reward-schema.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/ai/ai-reward-schema.ts)
## Overview
Reward rules govern how affiliate commissions are determined across workspace programs, resolving event structures, payout calculations, and conditional overrides for sales, leads, clicks, referrals, and custom schedules. They provide the foundational engine for calculating precise compensation by evaluating contextual attributes such as partner statistics, customer geolocations, and product metadata against configured reward modifiers. The system resolves hierarchy rules from workspace groups down to individual partner links while enforcing spend limits and duration constraints. Additionally, built-in validation pipelines, natural-language formatting utilities, and AI consistency auditing support program managers in creating and maintaining accurate payout configurations.
Sources: [apps/web/lib/api/sales/construct-reward-amount.ts:6-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/construct-reward-amount.ts#L6-L79), [apps/web/lib/zod/schemas/rewards.ts:1-253](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L1-L253), [apps/web/lib/api/rewards/validate-reward.ts:15-212](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/rewards/validate-reward.ts#L15-L212), [apps/web/lib/partners/determine-partner-reward.ts:78-245](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/determine-partner-reward.ts#L78-L245), [apps/web/lib/partners/evaluate-reward-conditions.ts:10-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L10-L69), [apps/web/lib/rewards/format-reward-condition.ts:14-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/format-reward-condition.ts#L14-L70), [apps/web/lib/rewards/validate-tooltip-suggestion.ts:156-245](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/validate-tooltip-suggestion.ts#L156-L245), [apps/web/lib/ai/generate-reward.ts:108-315](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/ai/generate-reward.ts#L108-L315), [apps/web/ui/partners/rewards/reward-quality.tsx:10-125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/reward-quality.tsx#L10-L125), [apps/web/ui/partners/format-reward-description.ts:14-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/format-reward-description.ts#L14-L78), [apps/web/app/ee/api/workflows/create-partner-commission/route.ts:364-444](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L364-L444)
## Reward Schema Definition
### Commission and Reward Entities
Reward structures dictate how payouts are calculated for distinct conversion events across programs. The validation and schema layer establishes structural constraints for flat, percentage, tiered, and custom event rewards. Conditional attributes are organized by entity categories, allowing rules to inspect contextual data for partners, customers, sales, and leads.
| Entity ID | Label | Attributes | Sources |
| :--- | :--- | :--- | :--- |
| `lead` | Lead | `metadata` | [apps/web/lib/zod/schemas/rewards.ts:52-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L52-L62) |
| `partner` | Partner | `country`, `totalClicks`, `totalLeads`, `totalConversions`, `totalSaleAmount`, `totalCommissions` | [apps/web/lib/zod/schemas/rewards.ts:64-99](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L64-L99) |
| `customer` | Customer | `country` | [apps/web/lib/zod/schemas/rewards.ts:101-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L101-L111) |
| `sale` | Sale | `productId`, `amount`, `type` | [apps/web/lib/zod/schemas/rewards.ts:228-253](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L228-L253) |
Sources: [apps/web/lib/zod/schemas/rewards.ts:52-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L52-L111), [apps/web/lib/zod/schemas/rewards.ts:228-253](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/rewards.ts#L228-L253)
### Validation Rules and Constraints
> [!CAUTION]
> Percentage rewards are strictly forbidden for `click`, `lead`, and `custom` events. Attempting to assign `amountInPercentage` or setting `type` to `percentage` for these event types triggers an immediate `bad_request` API error during validation.
Sources: [apps/web/lib/api/rewards/validate-reward.ts:18-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/rewards/validate-reward.ts#L18-L76)
Validation checks enforce strict boundaries depending on the target reward event type:
- **Click and Lead Rewards:** Must use flat structures with `amountInCents` defined. `amountInPercentage` is disallowed, and `maxDuration` must be set to `0`.
- **Custom Rewards:** Require a valid `config` payload including frequency, interval, and an `anchorDate` that cannot be set in the past. Spend limits (`spendLimitAmount` and `spendLimitInterval`) and `modifiers` are disallowed, and `maxDuration` cannot be `0`.
- **Sale Rewards:** Require either `amountInCents` or `amountInPercentage` to be provided, but both cannot be used simultaneously. Flat sales mandate `amountInCents`, while percentage sales mandate `amountInPercentage`.
- **Referral Rewards:** Require a configuration object containing a valid trigger type. Percentage referral rewards must reference percentage triggers, while flat referral rewards must reference flat triggers. Reward modifiers are prohibited.
Sources: [apps/web/lib/api/rewards/validate-reward.ts:15-212](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/rewards/validate-reward.ts#L15-L212)
## Condition Evaluation Pipeline
### Field Value Resolution and Context Mapping
The evaluation pipeline resolves dynamic rule conditions by inspecting incoming reward contexts across entities such as partner stats, customer attributes, and metadata fields. When evaluating modifier conditions, field values are extracted based on the target entity and attribute type. For metadata attributes, the pipeline utilizes `prepareMetadataFieldValue` to sanitize and map the custom metadata value keyed by `metadataField`.
```typescript
function resolveConditionFieldValue({
condition,
context,
}: {
condition: RewardCondition;
context: RewardContext;
}): string | number | string[] | number[] | undefined {
if (condition.attribute === "metadata") {
const metaKey = condition.metadataField?.trim();
if (!metaKey) {
return undefined;
}
const entityMap = {
partner: undefined,
customer: undefined,
lead: context.lead,
sale: context.sale,
} as const;
return prepareMetadataFieldValue(
entityMap[condition.entity]?.metadata?.[metaKey],
condition,
);
}
const entityMap = {
partner: context.partner,
customer: context.customer,
lead: undefined,
sale: context.sale,
} as const;
return entityMap[condition.entity]?.[condition.attribute];
}
```
Sources: [apps/web/lib/partners/evaluate-reward-conditions.ts:71-106](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L71-L106)
| Entity | Mapped Context Source | Handled Attributes | Sources |
| :--- | :--- | :--- | :--- |
| `partner` | `context.partner` | Partner metrics, country, metadata | [apps/web/lib/partners/evaluate-reward-conditions.ts:98-99](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L98-L99) |
| `customer` | `context.customer` | Country, metadata | [apps/web/lib/partners/evaluate-reward-conditions.ts:100-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L100-L100) |
| `lead` | `context.lead` | Metadata fields | [apps/web/lib/partners/evaluate-reward-conditions.ts:88-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L88-L88) |
| `sale` | `context.sale` | Product ID, amount, type, metadata | [apps/web/lib/partners/evaluate-reward-conditions.ts:89-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L89-L89) |
Sources: [apps/web/lib/partners/evaluate-reward-conditions.ts:78-106](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L78-L106)
### Boolean Operators and Condition Evaluation
Once field values are resolved, individual condition rules are assessed using comparison operators. Condition groups combine multiple individual rules with either `AND` or `OR` logical operators. If all evaluations within an `AND` group or any evaluation within an `OR` group pass, the condition group is marked as met.
```typescript
const evaluateCondition = ({
condition,
fieldValue,
}: {
condition: RewardCondition;
fieldValue: string | number | string[] | number[];
}) => {
// Equals
if (condition.operator === "equals_to") {
return fieldValue === condition.value;
}
// Not equals
if (condition.operator === "not_equals") {
return fieldValue !== condition.value;
}
// Starts with
if (condition.operator === "starts_with") {
if (
typeof fieldValue !== "string" ||
typeof condition.value !== "string" ||
condition.value === ""
) {
return false;
}
return fieldValue.startsWith(condition.value);
}
// Ends with
if (condition.operator === "ends_with") {
if (
typeof fieldValue !== "string" ||
typeof condition.value !== "string" ||
condition.value === ""
) {
return false;
}
return fieldValue.endsWith(condition.value);
}
// Contains
if (condition.operator === "contains") {
if (typeof fieldValue !== "string" || typeof condition.value !== "string") {
return false;
}
const trimmedValue = condition.value.trim();
if (trimmedValue === "") {
return false;
}
return String(fieldValue).includes(trimmedValue);
}
// Not contains
if (condition.operator === "not_contains") {
if (typeof fieldValue !== "string" || typeof condition.value !== "string") {
return false;
}
const trimmedValue = condition.value.trim();
if (trimmedValue === "") {
return false;
}
return !String(fieldValue).includes(trimmedValue);
}
// In
if (condition.operator === "in") {
if (!Array.isArray(condition.value)) {
return false;
}
return (condition.value as (string | number)[]).includes(
```
Sources: [apps/web/lib/partners/evaluate-reward-conditions.ts:108-224](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L108-L224)
| Operator ID | Evaluation Logic | Sources |
| :--- | :--- | :--- |
| `equals_to` | `fieldValue === condition.value` | [apps/web/lib/partners/evaluate-reward-conditions.ts:116-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L116-L118) |
| `not_equals` | `fieldValue !== condition.value` | [apps/web/lib/partners/evaluate-reward-conditions.ts:121-123](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L121-L123) |
| `starts_with` | `fieldValue.startsWith(condition.value)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:126-136](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L126-L136) |
| `ends_with` | `fieldValue.endsWith(condition.value)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:139-149](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L139-L149) |
| `contains` | `String(fieldValue).includes(trimmedValue)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:152-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L152-L164) |
| `not_contains` | `!String(fieldValue).includes(trimmedValue)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:167-179](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L167-L179) |
| `in` | `condition.value.includes(fieldValue)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:182-190](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L182-L190) |
| `not_in` | `!condition.value.includes(fieldValue)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:193-201](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L193-L201) |
| `greater_than` | `Number(fieldValue) > Number(condition.value)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:204-206](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L204-L206) |
| `greater_than_or_equal` | `Number(fieldValue) >= Number(condition.value)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:209-211](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L209-L211) |
| `less_than` | `Number(fieldValue) < Number(condition.value)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:214-216](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L214-L216) |
| `less_than_or_equal` | `Number(fieldValue) <= Number(condition.value)` | [apps/web/lib/partners/evaluate-reward-conditions.ts:219-221](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L219-L221) |
Sources: [apps/web/lib/partners/evaluate-reward-conditions.ts:108-224](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L108-L224)
### Override Selection and Precedence
When multiple condition groups match the evaluation context, the pipeline selects the best matching condition by sorting the matching groups in descending order by their calculated reward amount and picking the first entry.
```typescript
if (matchingConditions.length === 0) {
return null;
}
// Find the best matching condition (highest amount)
return matchingConditions.sort(
(a, b) =>
getRewardAmount({
type: b.type!,
amountInCents: b.amountInCents,
amountInPercentage: b.amountInPercentage,
}) -
getRewardAmount({
type: a.type!,
amountInCents: a.amountInCents,
amountInPercentage: a.amountInPercentage,
}),
)[0];
};
```
Sources: [apps/web/lib/partners/evaluate-reward-conditions.ts:51-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L51-L69)
> [!NOTE]
> If multiple condition groups evaluate to true against the provided context, `evaluateRewardConditions` automatically sorts candidates using `getRewardAmount` and prioritizes the group yielding the highest commission amount.
Sources: [apps/web/lib/partners/evaluate-reward-conditions.ts:55-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/evaluate-reward-conditions.ts#L55-L68)
When a matched condition overrides the base reward, properties such as `type`, `amountInCents`, `amountInPercentage`, and `maxDuration` are updated on the reward object. For sales featuring Stripe line items with `productId` modifiers, `determinePartnerRewards` iterates over each product in the sale context to calculate distinct line-item overrides.
```typescript
let matchedCondition: RewardConditions | null = null;
if (partnerReward.modifiers && context) {
const modifiers = rewardConditionsArraySchema.safeParse(
partnerReward.modifiers,
);
// Parse the conditions before evaluating them
if (modifiers.success) {
matchedCondition = evaluateRewardConditions({
conditions: modifiers.data,
context,
});
if (matchedCondition) {
partnerReward = {
...partnerReward,
// Override the reward amount, type and max duration with the matched condition
type: matchedCondition.type || partnerReward.type,
amountInCents:
matchedCondition.amountInCents != null
? matchedCondition.amountInCents
: null,
amountInPercentage:
matchedCondition.amountInPercentage != null
? new Prisma.Decimal(matchedCondition.amountInPercentage)
: null,
maxDuration:
matchedCondition.maxDuration !== undefined
? matchedCondition.maxDuration
: partnerReward.maxDuration,
};
}
}
}
```
Sources: [apps/web/lib/partners/determine-partner-reward.ts:116-150](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/determine-partner-reward.ts#L116-L150), [apps/web/lib/partners/determine-partner-reward.ts:209-237](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/determine-partner-reward.ts#L209-L237)
## Payout Amount Calculations
### Earnings Calculation and Base Reward Retrieval
The commission earnings for individual sales are computed via `calculateSaleEarnings`, which evaluates the underlying reward structure against sale parameters such as quantity and total monetary amount. It first resolves the raw numeric amount using `getRewardAmount`, handling nullable configurations by defaulting unassigned reward values to zero.
```typescript
export const calculateSaleEarnings = ({
reward,
sale,
}: {
reward: Pick;
sale: Pick;
}) => {
if (!reward) {
return 0;
}
const amount = getRewardAmount(reward);
if (reward.type === "flat") {
return sale.quantity * amount;
} else if (reward.type === "percentage") {
return Math.round((sale.amount * amount) / 100);
}
return 0;
};
```
Sources: [apps/web/lib/api/sales/calculate-sale-earnings.ts:8-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/calculate-sale-earnings.ts#L8-L28), [apps/web/lib/partners/get-reward-amount.ts:3-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/get-reward-amount.ts#L3-L11)
> [!NOTE]
> `calculateSaleEarnings` branches explicitly on the reward type: flat rewards multiply the sale quantity by the resolved unit amount, whereas percentage rewards multiply the sale amount by the percentage rate and divide by 100, rounding the final integer result with `Math.round`.
Sources: [apps/web/lib/api/sales/calculate-sale-earnings.ts:21-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/calculate-sale-earnings.ts#L21-L25)
### Modifier Validation and Range Formatting
When rewards contain modifier conditions, `constructRewardAmount` validates them using `rewardConditionsArraySchema`. Each modifier's `type` and `maxDuration` are evaluated against the primary reward parameters. If every modifier matches both the primary reward type and maxDuration, the engine calculates a boundary range across the primary reward and all valid modifiers.
```typescript
// If there are modifiers, we need to check if they match the primary reward
if (reward.modifiers) {
const parsedModifiers = rewardConditionsArraySchema.safeParse(
reward.modifiers,
);
if (parsedModifiers.success) {
const modifiers = parsedModifiers.data;
// if no type or maxDuration, it falls back to the primary reward type and maxDuration
const matchPrimary = modifiers.every((m) => {
const typeMatches =
m.type === undefined ? true : m.type === reward.type;
const durationMatches =
m.maxDuration === undefined
? true
: m.maxDuration === reward.maxDuration;
return typeMatches && durationMatches;
});
// If the type AND maxDuration matches the primary, show a range
if (matchPrimary) {
const amount = getRewardAmount(reward);
const min = Math.min(
amount,
...modifiers.map((modifier) =>
reward.type === "flat"
? modifier.amountInCents ?? Infinity
: modifier.amountInPercentage ?? Infinity,
),
);
const max = Math.max(
amount,
...modifiers.map((modifier) =>
reward.type === "flat"
? modifier.amountInCents ?? 0
: modifier.amountInPercentage ?? 0,
),
);
if (min !== max) {
return `Up to ${
reward.type === "percentage"
? `${max}%`
: currencyFormatter(max, {
trailingZeroDisplay: "stripIfInteger",
})
}`;
}
}
```
Sources: [apps/web/lib/api/sales/construct-reward-amount.ts:16-67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/construct-reward-amount.ts#L16-L67)
| Reward Type | Minimum Value Fallback | Maximum Value Fallback | Formatting Logic |
| :--- | :--- | :--- | :--- |
| `flat` | `Infinity` (if null) | `0` (if null) | `currencyFormatter(max, { trailingZeroDisplay: "stripIfInteger" })` |
| `percentage` | `Infinity` (if null) | `0` (if null) | `${max}%` |
Sources: [apps/web/lib/api/sales/construct-reward-amount.ts:40-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/construct-reward-amount.ts#L40-L65)
> [!WARNING]
> If modifiers omit either `type` or `maxDuration`, they default to matching the primary reward's respective properties. However, if any modifier fails to match both properties, range construction is bypassed entirely and the engine falls back to displaying the primary reward amount.
Sources: [apps/web/lib/api/sales/construct-reward-amount.ts:25-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/construct-reward-amount.ts#L25-L34), [apps/web/lib/api/sales/construct-reward-amount.ts:71-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/construct-reward-amount.ts#L71-L78)
## Group And Link Resolution
### Hierarchy Resolution and Display Filters
Workspace groups and partner links resolve active rewards through dedicated filtering utilities. The `getPartnerLinkDisplayRewards` function processes event reward parameters including `clickReward`, `leadReward`, `saleReward`, `discount`, and `enrollmentRewards`. It invokes `pickDisplayReward` on primary event rewards to filter out null instances or negative monetary values, while `getDisplayCustomRewards` extracts custom event rewards where the computed reward amount is greater than or equal to zero.
```typescript
function pickDisplayReward(reward: RewardProps | null | undefined) {
if (!reward || getRewardAmount(reward) < 0) {
return null;
}
return reward;
}
function getDisplayCustomRewards(enrollmentRewards: RewardProps[]) {
return enrollmentRewards.filter(
(reward) => reward.event === "custom" && getRewardAmount(reward) >= 0,
);
}
export function getPartnerLinkDisplayRewards({
clickReward,
leadReward,
saleReward,
discount,
enrollmentRewards = [],
}: {
clickReward?: RewardProps | null;
leadReward?: RewardProps | null;
saleReward?: RewardProps | null;
discount?: DiscountProps | null;
enrollmentRewards?: RewardProps[];
}) {
return {
rewards: [
pickDisplayReward(saleReward),
pickDisplayReward(leadReward),
pickDisplayReward(clickReward),
...getDisplayCustomRewards(enrollmentRewards),
].filter((reward): reward is RewardProps => reward != null),
discount: discount ?? null,
};
}
```
Sources: [apps/web/lib/rewards/resolve-partner-link-rewards.ts:4-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/resolve-partner-link-rewards.ts#L4-L39)
> [!NOTE]
> When prioritizing partner incentives via `getPartnerLinkPrimaryIncentive`, the engine evaluates primary events in the strict order of `sale`, `lead`, and `click`. If none of these primary event rewards exist, the primary incentive falls back to the associated discount.
Sources: [apps/web/lib/rewards/resolve-partner-link-rewards.ts:42-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/resolve-partner-link-rewards.ts#L42-L60)
### Spend Limits and Duration Enforcement
During commission creation workflows, the [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine) evaluates whether active rewards have breached duration limits or cumulative spend thresholds. For sale events carrying a `maxDuration` property, one-time sales with a `maxDuration` of `0` immediately skip commission generation for recurring events. For recurring subscriptions where `maxDuration` exceeds zero, the workflow computes the month difference via `differenceInMonths` against the first commission creation date. If this duration meets or exceeds the configured `maxDuration`, commission processing is halted.
Sources: [apps/web/app/ee/api/workflows/create-partner-commission/route.ts:366-389](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L366-L389)
Furthermore, when a reward defines a `spendLimitAmount` and `spendLimitInterval`, earnings are evaluated through `clampEarningsToSpendLimit`. If the clamped earnings drop to zero, commission creation is skipped entirely. Custom reward commissions additionally verify that the target partner remains approved and actively bound to the specific `customRewardId` at write time.
```typescript
if (
customerId &&
event !== "custom" &&
reward &&
reward.spendLimitAmount &&
reward.spendLimitInterval
) {
cappedEarnings = await clampEarningsToSpendLimit({
reward,
earnings,
programId,
partnerId,
customerId,
referenceDate: createdAt ?? new Date(),
});
// If spend limit clamped earnings to 0, skip commission creation
if (cappedEarnings === 0) {
return logAndReturn({
commission: null,
outputLog: `Partner ${partnerId} has reached spend limit (${currencyFormatter(reward.spendLimitAmount)} ${reward.spendLimitInterval === "allTime" ? "" : `per ${reward.spendLimitInterval}`}) for ${event} event, skipping commission creation...`,
});
}
}
// Custom reward jobs are queued from a snapshot of eligible enrollments.
// Re-check at write time so we don't pay a partner who was banned, deactivated,
// or moved off this reward before the workflow ran.
// Only jobs that pass rewardId (create-custom-commission) should be gated —
// manual commissions and bounty payouts also use event "custom" but have no rewardId.
const isCustomRewardCommission = event === "custom" && Boolean(rewardId);
const stillOnCustomReward = programEnrollment.customRewardId === rewardId;
if (
isCustomRewardCommission &&
(programEnrollment.status !== "approved" || !stillOnCustomReward)
) {
return logAndReturn({
commission: null,
outputLog: `Partner ${partnerId} is no longer eligible for custom reward ${rewardId} (status: ${programEnrollment.status}), skipping commission creation...`,
});
}
```
Sources: [apps/web/app/ee/api/workflows/create-partner-commission/route.ts:421-462](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L421-L462)
## Referral And Bounty Rewards
### Partner Referral Compensation Rules
The partner referral rule engine processes two-tier affiliate compensation by evaluating whether a commission originates from a source commission or a direct partner approval and commission threshold event. When a partner refers another affiliate, the system prevents self-referrals by checking whether the active partner identifier matches the `referredByPartnerId` context, immediately skipping commission generation if both values are identical.
```typescript
type CreateReferralCommissionProps =
| { sourceCommissionId: string; partnerId?: never; programId?: never } // Based on a source commission
| { sourceCommissionId?: never; partnerId: string; programId: string }; // Based on partner approval and commission threshold
export const createReferralCommission = async (
props: CreateReferralCommissionProps,
) => {
const context = await resolveReferralContext(props);
if (!context) {
return null;
}
const { sourceCommission, programId, partnerId, referredByPartnerId } =
context;
if (partnerId && referredByPartnerId && partnerId === referredByPartnerId) {
console.log(
`Skipping referral commission creation for self-referral (partner ${partnerId}).`,
);
return null;
}
```
Sources: [apps/web/lib/partner-referrals/create-referral-commission.ts:14-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-referral-commission.ts#L14-L35)
Reward structures for referrals are split into percentage and flat triggers. Percentage triggers evaluate commission basis rules using predefined percentage events, whereas flat triggers operate on specific partner milestones such as partner approval or commission thresholds.
| Trigger Category | Trigger Identifier | Description & Behaviour |
| :--- | :--- | :--- |
| Percentage | `saleRecorded` | Evaluates percentage reward based on recorded sales. |
| Percentage | `commissionEarned` | Evaluates percentage reward based on earned partner commissions. |
| Flat | `partnerApproved` | Triggers flat reward immediately upon partner approval (clears `maxDuration`). |
| Flat | `commissionThreshold` | Triggers flat reward when accumulated commissions hit a defined threshold in cents. |
Sources: [apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx:6-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx#L6-L11), [apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx:56-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx#L56-L101), [apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx:207-214](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx#L207-L214)
> [!CAUTION]
> Flat referral triggers such as `partnerApproved` and `commissionThreshold` do not support duration limits. Whenever a flat trigger becomes active, the builder automatically forces `maxDuration` to `null`. Switching back to a percentage trigger automatically restores `maxDuration` to `Infinity` if it was previously cleared.
Sources: [apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx:77-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx#L77-L101)
### Manual Bounty Submission Criteria
Bounty programs manage time-bound content challenges through submission requirements that dictate whether creators must attach proof URLs or image files. The manual submission criteria engine reads submission options from the bounty form context, tracking requirement flags and configuration limits for images and URLs.
```tsx
export function BountyCriteriaManualSubmission() {
const { watch, setValue } = useBountyFormContext();
const [submissionRequirements, rewardType = "flat"] = watch([
"submissionRequirements",
"rewardType",
]);
const requireImage = !!submissionRequirements?.image;
const requireUrl = !!submissionRequirements?.url;
const imageMax = submissionRequirements?.image?.max;
const urlMax = submissionRequirements?.url?.max;
const urlDomains = submissionRequirements?.url?.domains ?? [];
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx:48-61](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx#L48-L61)
Bounty payouts support two reward structure types managed via interactive badges: flat rate payouts and custom descriptions. Flat rate bounties validate numeric currency amounts greater than or equal to zero, while custom bounties require a text description limited to 100 characters.
| Reward Type | Value Identifier | Validation Rule | Display Formatting |
| :--- | :--- | :--- | :--- |
| Flat Rate | `flat` | `rewardAmount != null && !isNaN && rewardAmount >= 0` | Formatted via `currencyFormatter` in cents. |
| Custom Amount | `custom` | `!rewardDescription?.trim()` (max 100 characters) | Displays trimmed description text or fallback placeholder. |
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx:22-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx#L22-L31), [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx:384-436](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx#L384-L436)
> [!NOTE]
> When configuring custom bounty rewards, input values matching an empty string are explicitly converted to `null` before updating form state, and the controller enforces a strict maximum length rule of 100 characters.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx:418-435](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx#L418-L435)
## Form Construction And Tooltips
Visual program builders construct and edit reward structures through interactive form contexts, field arrays, and natural-language description engines. The reward form interface manages conditional rule groups, payout rates, and cadence configurations via react-hook-form state management. When configuring custom interval rewards, builders parse custom cadence configurations using `customConfigSchema` and format schedule descriptions and duration labels dynamically.
Sources: [apps/web/ui/partners/rewards/rewards-logic.tsx:55-102](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/rewards-logic.tsx#L55-L102), [apps/web/ui/partners/rewards/custom-reward-builder.tsx:40-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/custom-reward-builder.tsx#L40-L51), [apps/web/ui/partners/custom-reward-description.tsx:12-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/custom-reward-description.tsx#L12-L38)
Natural-language formatting functions convert raw reward objects and condition clauses into human-readable text strings for tooltips, embeds, and summary rows. The `formatRewardDescription` utility processes event types, flat or percentage amounts, duration constraints, and spend limit intervals into polished payout descriptions.
| Event Type | Condition Clause Formatter | Duration Suffix Logic | Spend Limit Integration |
| :--- | :--- | :--- | :--- |
| `sale` | `formatRewardConditionClause` | `for the customer's lifetime` or `for N months` / `for N years` | Appends `, up to [amount] [interval] per customer` |
| `referral` | `formatReferralRewardDescription` | `for the referred partner's lifetime` or `one time` | None |
| `custom` | `formatCustomRewardDescription` | `for [durationLabel]` | None |
| `lead` / `click` | Default event clause | None | None |
Sources: [apps/web/lib/rewards/format-reward-condition.ts:47-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/format-reward-condition.ts#L47-L70), [apps/web/ui/partners/format-reward-description.ts:14-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/format-reward-description.ts#L14-L78)
Reward quality grading evaluates configured amounts and durations against predefined competitiveness tiers, surfacing visual indicators with descriptive tooltips. The quality engine categorizes rewards into four discrete quality levels based on event type, payout structure, and duration thresholds.
| Reward Quality | Target Event & Criteria | Visual Badge Styling | Tooltip Summary |
| :--- | :--- | :--- | :--- |
| `low` | Clicks `< $0.03`, leads `< $1`, or percentage sales `< 10%` | Orange background (`bg-orange-100`), orange text | May struggle to attract partners |
| `limited` | One-time flat sales or short duration caps (`maxDuration === 1`) | Orange background (`bg-orange-100`), orange text | No long term earning potential |
| `good` | Clicks `0.03–0.05`, leads `1–10`, percentage sales `10–20%` | Cyan background (`bg-cyan-200`), cyan text | Solid reward with room to grow |
| `strong` | Clicks `> 0.05`, leads `> 10`, percentage sales `> 20%` with lifetime/12m+ duration | Green background (`bg-green-200`), green text | High earning potential for partners |
Sources: [apps/web/ui/partners/rewards/reward-quality.tsx:10-125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/reward-quality.tsx#L10-L125), [apps/web/ui/partners/rewards/reward-quality.tsx:127-165](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/rewards/reward-quality.tsx#L127-L165)
> [!NOTE]
> AI consistency auditing uses Anthropic Claude Sonnet via streaming server actions (`generateReward` and `reviewRewardTooltip`) to check whether partner-facing copy contradicts structured reward conditions, automatically enforcing confidence floors of `0.5` and filtering out uninstalled customer source integrations.
Sources: [apps/web/lib/ai/generate-reward.ts:192-202](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/ai/generate-reward.ts#L192-L202), [apps/web/lib/ai/review-reward-tooltip.ts:221-238](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/ai/review-reward-tooltip.ts#L221-L238), [apps/web/lib/rewards/validate-tooltip-suggestion.ts:1-8](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/validate-tooltip-suggestion.ts#L1-L8), [apps/web/lib/rewards/validate-tooltip-suggestion.ts:194-204](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewards/validate-tooltip-suggestion.ts#L194-L204)
## Related
- [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine)
- [Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs)
---
## Technical docs: GET Get admin partner details
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminpartner
## Parameters
## Responses
## Try It
---
## Technical docs: Partner Programs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/actions/partners/create-program-application.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/create-program-application.ts)
- [apps/web/lib/partners/complete-program-applications.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/complete-program-applications.ts)
- [apps/web/app/ee/partners.dub.co/dashboard/programs/programSlug/apply/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/%5BprogramSlug%5D/apply/page.tsx)
- [apps/web/app/ee/api/track/application/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts)
- [apps/web/lib/middleware/partners.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/partners.ts)
- [apps/web/app/ee/partners.dub.co/dashboard/programs/programSlug/apply/program-sidebar.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/%5BprogramSlug%5D/apply/program-sidebar.tsx)
- [apps/web/app/ee/partners.dub.co/apply/programSlug/default/apply/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(apply)/%5BprogramSlug%5D/(default)/apply/page.tsx)
- [apps/web/app/api/callback/plain/partner/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/plain/partner/route.ts)
- [apps/web/app/ee/api/partner-profile/programs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/route.ts)
- [apps/web/app/ee/api/partners/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partners/route.ts)
- [apps/web/lib/program-applications/approve-program-application.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/program-applications/approve-program-application.ts)
- [apps/web/app/ee/partners.dub.co/apply/programSlug/default/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(apply)/%5BprogramSlug%5D/(default)/page.tsx)
- [apps/web/app/ee/api/program-applications/approve/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/program-applications/approve/route.ts)
- [apps/web/lib/actions/partners/create-program.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/create-program.ts)
- [apps/web/lib/actions/partners/approve-program-application.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/approve-program-application.ts)
- [apps/web/prisma/schema/program.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/program.prisma)
- [apps/web/ui/program-marketplace/marketplace-program-header-controls.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/marketplace-program-header-controls.tsx)
- [apps/web/app/api/og/program/route.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/route.tsx)
- [apps/web/app/ee/partners.dub.co/apply/programSlug/default/apply/success/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(apply)/%5BprogramSlug%5D/(default)/apply/success/page.tsx)
- [apps/web/lib/lemonsqueezy/import-partners.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/lemonsqueezy/import-partners.ts)
- [apps/web/app/ee/partners.dub.co/apply/programSlug/default/layout.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(apply)/%5BprogramSlug%5D/(default)/layout.tsx)
- [apps/web/prisma/schema/application.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/application.prisma)
- [apps/web/lib/jobs/handlers/auto-approve-partner-job.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/auto-approve-partner-job.ts)
- [apps/web/lib/firstpromoter/import-partners.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-partners.ts)
- [apps/web/app/ee/partners.dub.co/dashboard/programs/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx)
- [apps/web/lib/network/get-network-approval-requirements.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/network/get-network-approval-requirements.ts)
- [apps/web/lib/webhook/sample-events/program-application-submitted.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/sample-events/program-application-submitted.json)
- [apps/web/ui/partners/program-card.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/program-card.tsx)
- [apps/web/lib/application-events/mark-application-event-submitted-network.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/application-events/mark-application-event-submitted-network.ts)
- [apps/web/lib/partner-referrals/attribute-referring-partner.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/attribute-referring-partner.ts)
## Overview
Partner Programs manage the lifecycle of affiliate relationships within Dub, connecting prospective promoters with workspace-owned programs through structured entry points, eligibility verification, and state-managed enrollments. The architecture governs how prospective affiliates transition from landing pages and marketplace discoveries into evaluated applicants, tracks identity credentials across network and program boundaries, and exposes administrative mechanisms for programmatic and manual approvals.
Sources: [apps/web/prisma/schema/program.prisma:27-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/program.prisma#L27-L100)
At the core of the subsystem are three principal variants operating in concert: Partner Applications, Partner Portal, and Partner Programs, each sharing a common interface foundation defined by workspace configurations and Prisma database models.
Sources: [apps/web/lib/middleware/partners.ts:1-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/partners.ts#L1-L33)
---
## Partner Applications
Prospective affiliates enter partner programs via custom landing pages, marketplace links, or direct invitation URLs. The application process begins with event tracking and form rendering governed by program slugs and group slugs. When a user requests a program application page, the system fetches the underlying program and its default or custom partner group, verifying that the application form is published.
Sources: [apps/web/app/ee/partners.dub.co/dashboard/programs/programSlug/apply/page.tsx:15-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/%5BprogramSlug%5D/apply/page.tsx#L15-L30)
```mermaid
sequenceDiagram
participant Partner as Prospective Partner
participant Web as Application Route
participant DB as Prisma Database
participant Job as QStash / Job Handler
Partner->>Web: Submit application payload
Web->>Web: assertRateLimit (3 req/min/IP)
Web->>DB: Fetch program, groups, session
alt Partner Logged In
Web->>DB: Check network profile & existing enrollment
DB-->>Web: Partner profile & programs
Web->>Web: evaluateApplicationRequirements()
Web->>DB: Create ProgramApplication & ProgramEnrollment ($transaction)
else Unauthenticated Partner
Web->>DB: Create ProgramApplication (pending status)
DB-->>Web: Application record created
Web->>Job: Dispatch programApplicationReminderJob (15 min delay)
end
Web-->>Partner: Return application confirmation
```
Sources: [apps/web/lib/actions/partners/create-program-application.ts:121-140](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/create-program-application.ts#L121-L140)
When an application is submitted via `createProgramApplicationAction`, the request is first subjected to rate-limiting (`RATELIMIT_POLICIES.createProgramApplication`) restricting requests to 3 per minute per program per IP. The system resolves the target program and partner group, checking whether the submitting user possesses an active partner session. If the partner is already logged in, the system validates their network profile checklist progress (`getNetworkProfileChecklistProgress`) and verifies that their `networkStatus` is either `approved` or `trusted`. If requirements fail, execution halts with a descriptive error. Otherwise, `createApplicationAndEnrollment` executes a Prisma transaction creating both a `ProgramApplication` (`pga_`) and a `ProgramEnrollment` (`pge_`).
Sources: [apps/web/lib/actions/partners/create-program-application.ts:141-224](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/create-program-application.ts#L141-L224)
Unauthenticated applicants create standalone `ProgramApplication` records. A delayed reminder job (`programApplicationReminderJob`) is queued with a 15-minute delay to follow up on incomplete onboarding steps. When a user subsequently creates their partner profile, `completeProgramApplications` scans outstanding applications matching the user's email, deduplicates them by `programId`, and provisions corresponding program enrollments.
Sources: [apps/web/lib/actions/partners/create-program-application.ts:225-241](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/create-program-application.ts#L225-L241), [apps/web/lib/partners/complete-program-applications.ts:24-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/complete-program-applications.ts#L24-L80)
---
## Partner Portal
The Partner Portal provides the authenticated interface where partners monitor their performance, track application statuses, and manage their network profile. The dashboard client fetches all program enrollments (excluding invited or declined states) and renders interactive cards via `ProgramCard`.
Sources: [apps/web/app/ee/partners.dub.co/dashboard/programs/page-client.tsx:11-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx#L11-L21)
```mermaid
flowchart TD
A["Partner Dashboard /programs"] --> B{"Fetch Program Enrollments"}
B -->|Status: approved| C["Render ProgramCardEarnings (Timeseries & Commissions)"]
B -->|Status: pending| D["Render 'Applied [Date]' badge"]
B -->|Status: rejected| E["Render Rejection Tooltip (Reason, Notes, Date)"]
B -->|Status: banned / deactivated| F["Render Support Outreach Prompt"]
```
Sources: [apps/web/ui/partners/program-card.tsx:100-156](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/program-card.tsx#L100-L156)
When a program enrollment is in an active `approved` state, `ProgramCard` displays real-time earnings data queried via `usePartnerEarningsTimeseries` alongside interactive currency flows powered by NumberFlow. Non-approved statuses invoke conditional renders: pending enrollments display submission timestamps; rejected applications expose a rich tooltip breakdown containing reviewed dates, structured rejection reasons (`getProgramApplicationRejectionReasonLabel`), and custom notes; and banned or deactivated states provide direct links to reach out to the program support team via `/messages/[programSlug]`.
Sources: [apps/web/ui/partners/program-card.tsx:158-216](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/program-card.tsx#L158-L216)
Profile completeness is enforced through a rigid checklist verified by `getNetworkApprovalRequirements`. Partners must fulfill specific prerequisites before unlocking program application actions across the marketplace and individual program landers.
Sources: [apps/web/lib/network/get-network-approval-requirements.ts:35-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/network/get-network-approval-requirements.ts#L35-L82)
| Checklist Requirement | Evaluation Logic | Target Anchor |
| :--- | :--- | :--- |
| **Upload your logo** | `!!partner.image` | `#info` |
| **Verify social accounts** | `>= 2` verified platforms via `PARTNER_PLATFORM_FIELDS` | `#platforms` |
| **Profile description** | `!!partner.description` | `#about` |
| **Estimated monthly traffic** | `!!partner.monthlyTraffic` | `#traffic` |
| **Earning structures** | `Boolean(partner.preferredEarningStructures?.length)` | `#earning-structures` |
| **Sales channels** | `Boolean(partner.salesChannels?.length)` | `#channels` |
Sources: [apps/web/lib/network/get-network-approval-requirements.ts:48-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/network/get-network-approval-requirements.ts#L48-L81)
---
## Partner Programs
The `Program` and `ProgramEnrollment` data models serve as the structural backbone for multi-tenant affiliate infrastructure. Programs belong to a workspace project and maintain associations with [reward rules](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/reward-rules), discount codes, partner groups, bounties, and fraud rule configurations.
Sources: [apps/web/prisma/schema/program.prisma:27-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/program.prisma#L27-L100)
```mermaid
erDiagram
Program ||--o{ ProgramEnrollment : enrolls
Program ||--o{ ProgramApplication : receives
Program ||--o{ PartnerGroup : categorizes
Partner ||--o{ ProgramEnrollment : participates
Partner ||--o{ ProgramApplication : submits
ProgramEnrollment }|--|| PartnerGroup : belongs_to
ProgramEnrollment ||--o| ProgramApplication : generates
```
Sources: [apps/web/prisma/schema/program.prisma:151-165](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/program.prisma#L151-L165)
Program enrollments track granular attribution metrics including aggregate clicks, leads, conversions, sales volume, commission totals, net revenue, earnings per click (EPC), and consistency scores.
Sources: [apps/web/prisma/schema/program.prisma:107-150](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/program.prisma#L107-L150)
> [!NOTE]
> Program enrollment status transitions follow a strict state machine defined by `ProgramEnrollmentStatus`. Once an enrollment is marked as `approved`, workspace usage counters (`partnersUsage`) increment atomically within a Prisma transaction, subject to workspace plan limits (`throwIfPartnersLimitExceeded`).
Sources: [apps/web/prisma/schema/program.prisma:1-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/program.prisma#L1-L10), [apps/web/lib/program-applications/approve-program-application.ts:90-138](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/program-applications/approve-program-application.ts#L90-L138)
The approval mechanism is centralized within `approveProgramApplication`. When invoked by an authorized workspace member or background job, it executes the following operations:
1. Validates that the target program enrollment exists and is currently in a `pending` or `rejected` state.
2. Resolves the target partner group, falling back to the enrollment's group ID or the program's `defaultGroupId`.
3. Opens a Prisma transaction (`prisma.$transaction`) to enforce plan partner limits, update enrollment status to `approved`, reset application review metadata, and increment `partnersUsage`.
4. Dispatches asynchronous background tasks via `waitUntil` to queue search index synchronization (`queuePartnerSearchSync`), record activity logs (`trackActivityLog`), track application lifecycle events (`trackApplicationEvents`), and trigger post-approval workflows (`dispatchWorkflows`).
Sources: [apps/web/lib/program-applications/approve-program-application.ts:24-178](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/program-applications/approve-program-application.ts#L24-L178)
## Related
- [Reward Rules](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/reward-rules)
- [Fraud Prevention](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/fraud-prevention)
- [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement)
---
## Technical docs: PATCH Update partner country
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/updateadminpartnercountry
## Parameters
## Request Body
Country update payload
## Responses
## Try It
---
## Technical docs: Bounties & Submissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/bounties-submissions
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/api/bounties/bountyId/sync-social-metrics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/bounties/%5BbountyId%5D/sync-social-metrics/route.ts)
- [apps/web/app/ee/api/cron/bounties/sync-social-metrics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/bountyId/bounty-submission-details-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/%5BbountyId%5D/bounty-submission-details-sheet.tsx)
- [apps/web/lib/bounty/api/create-bounty-submission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts)
- [apps/web/app/ee/api/bounties/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/bounties/route.ts)
- [apps/web/app/ee/api/cron/bounties/upsert-draft-submissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx)
- [apps/web/app/ee/api/partner-profile/programs/programId/bounties/bountyId/social-content-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/bounties/%5BbountyId%5D/social-content-stats/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/bountyId/bounty-submissions-table.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/%5BbountyId%5D/bounty-submissions-table.tsx)
- [apps/web/lib/bounty/api/get-social-metrics-updates.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/get-social-metrics-updates.ts)
- [apps/web/app/ee/api/embed/referrals/bounties/bountyId/social-content-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/bounties/%5BbountyId%5D/social-content-stats/route.ts)
- [apps/web/app/ee/api/cron/bounties/queue-sync-social-metrics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/bounties/submission-form.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-form.tsx)
- [apps/web/lib/zod/schemas/bounties.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/bounties.ts)
- [apps/web/lib/bounty/api/approve-bounty-submission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/approve-bounty-submission.ts)
- [apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx)
- [apps/web/lib/bounty/social-metrics-milestones.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/social-metrics-milestones.ts)
- [apps/web/ui/partners/bounties/bounty-social-content.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-social-content.tsx)
- [apps/web/app/ee/api/embed/referrals/bounties/bountyId/submissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/bounties/%5BbountyId%5D/submissions/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/add-edit-bounty/bounty-criteria.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/add-edit-bounty/bounty-criteria.tsx)
- [apps/web/app/ee/app.dub.co/embed/referrals/bounties/detail.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx)
- [apps/web/ui/partners/bounties/claim-bounty-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx)
- [apps/web/app/ee/app.dub.co/embed/referrals/bounties/submission-detail.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-detail.tsx)
- [apps/web/ui/partners/bounties/use-social-metrics-milestones.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/use-social-metrics-milestones.ts)
- [apps/web/ui/partners/bounties/bounty-submission-requirements.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx)
- [apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/bounties/index.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx)
- [apps/web/prisma/schema/bounty.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma)
- [apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts)
- [apps/web/ui/partners/bounties/bounty-social-content-preview.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx)
## Overview
The bounties and submissions subsystem in Dub powers partner incentive programs by supporting both performance-based tracking and social content verification [apps/web/prisma/schema/bounty.prisma:1-4](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L1-L4), [apps/web/lib/bounty/api/create-bounty-submission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts). It enables program operators to define flexible reward structures, configure automated submissions [apps/web/app/ee/api/cron/bounties/upsert-draft-submissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts), and synchronize external metrics via scheduled cron jobs [apps/web/app/ee/api/cron/bounties/sync-social-metrics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts). Partners can submit proof through file uploads, custom URLs, or social media links tied to verified accounts, while program managers inspect submissions [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/%5BbountyId%5D/bounty-submission-details-sheet.tsx), manage milestone approvals [apps/web/lib/bounty/api/approve-bounty-submission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/approve-bounty-submission.ts), and trigger commission payouts.
## Bounty Data Models and Periodicity
### Bounty Types and Performance Scopes
The `Bounty` data model supports two primary variants defined by `BountyType`: `performance` tracking and manual `submission` verification [apps/web/prisma/schema/bounty.prisma:1-4](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L1-L4). Performance bounties evaluate partner metrics using a `BountyPerformanceScope` which can be set to either `new` or `lifetime` activity [apps/web/prisma/schema/bounty.prisma:6-9](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L6-L9). Lifecycle and availability are further controlled by `BountyStartMode`, supporting `absolute` calendar dates (`startsAt` and `endsAt`) or `relative` durations calculated via `endsAfterDays` [apps/web/prisma/schema/bounty.prisma:32-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L32-L35), [apps/web/prisma/schema/bounty.prisma:44-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L44-L47).
| Enum / Type | Values | Description |
| :--- | :--- | :--- |
| `BountyType` | `performance`, `submission` | Distinguishes automated performance tracking from manual proof submissions [apps/web/prisma/schema/bounty.prisma:1-4](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L1-L4). |
| `BountyPerformanceScope` | `new`, `lifetime` | Determines whether performance metrics evaluate new actions or cumulative history [apps/web/prisma/schema/bounty.prisma:6-9](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L6-L9). |
| `BountyStartMode` | `absolute`, `relative` | Controls schedule boundaries using fixed timestamps or relative day offsets [apps/web/prisma/schema/bounty.prisma:32-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L32-L35). |
Sources: [apps/web/prisma/schema/bounty.prisma:1-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L1-L35)
> [!NOTE]
> During updates via `updateBountySchema`, the bounty `type` and `performanceScope` are strictly omitted and cannot be modified after initial creation [apps/web/lib/zod/schemas/bounties.ts:221-226](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/bounties.ts#L221-L226).
Sources: [apps/web/lib/zod/schemas/bounties.ts:221-226](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/zod/schemas/bounties.ts#L221-L226)
### Submission Lifecycles and Frequencies
Bounty submissions progress through specific lifecycle states defined by `BountySubmissionStatus`, accompanied by categorized failure logging via `BountySubmissionRejectionReason` [apps/web/prisma/schema/bounty.prisma:11-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L11-L24). Periodicity and recurrence are structured using `BountySubmissionFrequency` alongside a 1-indexed `periodNumber` [apps/web/prisma/schema/bounty.prisma:26-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L26-L30), [apps/web/prisma/schema/bounty.prisma:110](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L110). Uniqueness constraints on submissions enforce a strict one-submission-per-period rule per partner and bounty [apps/web/prisma/schema/bounty.prisma:124](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L124).
| Status / Reason Enum | Values | Purpose |
| :--- | :--- | :--- |
| `BountySubmissionStatus` | `draft`, `submitted`, `approved`, `rejected` | Represents the execution and review state of a partner's submission [apps/web/prisma/schema/bounty.prisma:11-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L11-L16). |
| `BountySubmissionRejectionReason` | `invalidProof`, `duplicateSubmission`, `outOfTimeWindow`, `didNotMeetCriteria`, `other` | Categorizes why a submission failed operator review [apps/web/prisma/schema/bounty.prisma:18-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L18-L24). |
| `BountySubmissionFrequency` | `day`, `week`, `month` | Defines recurring temporal intervals for periodic bounty submissions [apps/web/prisma/schema/bounty.prisma:26-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L26-L30). |
Sources: [apps/web/prisma/schema/bounty.prisma:11-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L11-L30)
> [!CAUTION]
> The database schema enforces a unique composite index `@@unique([bountyId, partnerId, periodNumber])` on `BountySubmission`, preventing duplicate active or draft submissions within the exact same periodic window [apps/web/prisma/schema/bounty.prisma:124](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L124).
Sources: [apps/web/prisma/schema/bounty.prisma:124](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/bounty.prisma#L124)
## Partner Submission Ingestion and Validation
### Submission Pipeline Execution Flow
The `BountySubmissionHandler` coordinates submission ingestion and validation [apps/web/lib/bounty/api/create-bounty-submission.ts:48-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L48-L111). The `submit` method executes a sequential series of validation checks and state operations before persisting the record:
```mermaid
flowchart TD
A["fetchBountyAndEnrollment()"] --> B["resolvePeriodNumber()"]
B --> C["validateEligibility()"]
C --> D["validateRequirements()"]
D --> E["validateFiles()"]
E --> F["validateSocialContent()"]
F --> G["mergeSubmissionData()"]
G --> H["persist()"]
H --> I["sendNotifications(submission)"]
```
Sources: [apps/web/lib/bounty/api/create-bounty-submission.ts:91-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L91-L111)
> [!WARNING]
> If a submission exists for the `finalPeriodNumber`, `persist()` performs an update on the existing record's ID instead of creating a duplicate row [apps/web/lib/bounty/api/create-bounty-submission.ts:587-607](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L587-L607).
Sources: [apps/web/lib/bounty/api/create-bounty-submission.ts:587-607](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L587-L607)
### Requirement Rules and UI Integration
Partners interact with the submission pipeline via EmbedBountySubmissionForm or the claim bounty sheet UI [apps/web/app/ee/app.dub.co/embed/referrals/bounties/submission-form.tsx:68-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/ee/app.dub.co/embed/referrals/bounties/submission-form.tsx#L68-L88), [apps/web/ui/partners/bounties/claim-bounty-sheet.tsx:364-369](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx#L364-L369). Requirements are parsed dynamically to enforce file uploads and URL constraints [apps/web/ui/partners/bounties/bounty-submission-requirements.tsx:5-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx#L5-L38).
| Requirement Type | Schema Field | Validation Rule |
| :--- | :--- | :--- |
| Image | `submissionRequirements.image` | Optional max limit; validates attached file array size when required [apps/web/ui/partners/bounties/bounty-submission-requirements.tsx:11-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx#L11-L17). |
| URL | `submissionRequirements.url` | Optional max limit and required allowed domain whitelist [apps/web/ui/partners/bounties/bounty-submission-requirements.tsx:19-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx#L19-L28). |
| Social Content | `bountyInfo.hasSocialMetrics` | Requires a connected partner account platform link posted after the bounty start date [apps/web/ui/partners/bounties/bounty-submission-requirements.tsx:30-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx#L30-L35). |
Sources: [apps/web/ui/partners/bounties/bounty-submission-requirements.tsx:5-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx#L5-L38)
> [!NOTE]
> Social metrics bounties automatically bypass manual file requirements and restrict URL inputs to a single content link, syncing external metrics directly during validation [apps/web/lib/bounty/api/create-bounty-submission.ts:543-561](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L543-L561), [apps/web/lib/bounty/api/create-bounty-submission.ts:578-581](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L578-L581).
Sources: [apps/web/lib/bounty/api/create-bounty-submission.ts:543-561](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L543-L561), [apps/web/lib/bounty/api/create-bounty-submission.ts:578-581](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/create-bounty-submission.ts#L578-L581)
### Social Content Verification
Social content requirements evaluate whether a post belongs to the partner's verified platform handle and meets temporal boundaries [apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts:8-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts#L8-L32).
```typescript
export function evaluateSocialContentRequirements({
content,
bounty,
partnerPlatform,
}: {
content?: SocialContent | null;
bounty: Pick;
partnerPlatform?: Pick;
}) {
const isPostedFromYourAccount =
!!content &&
!!partnerPlatform &&
!!partnerPlatform.verifiedAt &&
partnerPlatform.identifier.toLowerCase() === content.handle?.toLowerCase();
const isAfterStartDate =
!!content?.publishedAt &&
!!bounty.startsAt &&
!isBefore(content.publishedAt, bounty.startsAt);
return {
isPostedFromYourAccount,
isAfterStartDate,
};
}
```
Sources: [apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts:8-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts#L8-L32)
## Social Content Metrics and Synchronization
### Stats Scraping and API Endpoints
Social content metrics require periodic scraping of external platform stats. Endpoints such as `GET /api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats` and `GET /api/embed/referrals/bounties/[bountyId]/social-content-stats` validate partner credentials, enforce rate limits via `RATELIMIT_POLICIES.socialContentStats`, verify bounty eligibility, and query external platform metrics using `getSocialContent`.
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/bounties/bountyId/social-content-stats/route.ts:21-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/bounties/%5BbountyId%5D/social-content-stats/route.ts#L21-L91), [apps/web/app/ee/api/embed/referrals/bounties/bountyId/social-content-stats/route.ts:21-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/bounties/%5BbountyId%5D/social-content-stats/route.ts#L21-L80)
> [!WARNING]
> Live metric scraping requests are rate-limited per partner identifier to prevent abuse of external scrapers when partners test or preview submission links.
Sources: [apps/web/app/ee/api/partner-profile/programs/programId/bounties/bountyId/social-content-stats/route.ts:27-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/programs/%5BprogramId%5D/bounties/%5BbountyId%5D/social-content-stats/route.ts#L27-L30), [apps/web/app/ee/api/embed/referrals/bounties/bountyId/social-content-stats/route.ts:26-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/bounties/%5BbountyId%5D/social-content-stats/route.ts#L26-L29)
### Cron Scheduling and Queueing
The synchronization of social metrics runs periodically through background jobs managed via QStash. The `GET /api/cron/bounties/queue-sync-social-metrics` route queries active submission bounties containing social metrics requirements and chunks them into batches of 100 to enqueue jobs to `/api/cron/bounties/sync-social-metrics`.
Sources: [apps/web/app/ee/api/cron/bounties/queue-sync-social-metrics/route.ts:12-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts#L12-L45)
```typescript
export const GET = withCron(async () => {
const bounties = await prisma.bounty.findMany({
where: {
type: "submission",
submissionRequirements: {
path: "$.socialMetrics",
not: Prisma.JsonNull,
},
...buildBountyActivePeriodWhere(),
},
select: {
id: true,
},
});
if (bounties.length === 0) {
return logAndRespond("No bounties to sync social metrics for.");
}
const chunks = chunk(bounties, 100);
for (const chunk of chunks) {
await enqueueBatchJobs(
chunk.map((bounty) => ({
queueName: "sync-bounty-social-metrics",
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/sync-social-metrics`,
deduplicationId: bounty.id,
body: {
bountyId: bounty.id,
},
})),
);
}
return logAndRespond(
`Queued ${bounties.length} bounties to sync social metrics.`,
);
});
```
Sources: [apps/web/app/ee/api/cron/bounties/queue-sync-social-metrics/route.ts:12-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts#L12-L48)
### Synchronization Call-Chain Execution
When synchronizing metrics for a bounty or individual submission, the system evaluates earning caps and milestones.
1. `POST` request or cron handler invokes `hasReachedSocialMetricsEarningCap` with the bounty and submission.
2. `hasReachedSocialMetricsEarningCap` calls `getSocialMetricsEarningCap`.
3. `getSocialMetricsEarningCap` invokes `getSocialMetricsMilestones` to retrieve all payable milestones.
4. `getSocialMetricsMilestones` resolves bounty details and extracts configured thresholds and bonuses.
Sources: [apps/web/app/ee/api/bounties/bountyId/sync-social-metrics/route.ts:123-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/bounties/%5BbountyId%5D/sync-social-metrics/route.ts#L123-L129), [apps/web/lib/bounty/social-metrics-milestones.ts:84-109](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/social-metrics-milestones.ts#L84-L109)
```mermaid
sequenceDiagram
participant Route as POST /api/bounties/[bountyId]/sync-social-metrics
participant Milestones as hasReachedSocialMetricsEarningCap
participant Cap as getSocialMetricsEarningCap
participant List as getSocialMetricsMilestones
Route->>Milestones: Check if submission reached earning cap
Milestones->>Cap: Get maximum milestone threshold
Cap->>List: Calculate all payable milestones
List-->>Cap: Return milestone array
Cap-->>Milestones: Return earning cap threshold
Milestones-->>Route: Return boolean status
```
Sources: [apps/web/app/ee/api/bounties/bountyId/sync-social-metrics/route.ts:123-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/bounties/%5BbountyId%5D/sync-social-metrics/route.ts#L123-L129), [apps/web/lib/bounty/social-metrics-milestones.ts:33-92](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/social-metrics-milestones.ts#L33-L92)
## Milestone Calculation and Submission Approval
### Milestone Generation and Structure
The system calculates payable milestones for social metrics bounties by establishing an initial base tier followed by incremental bonus tiers. The function `getSocialMetricsMilestones` extracts the configured `minCount` and `rewardAmount` from bounty details to form the primary base milestone where `fromThreshold` is `0`. If an `incrementalBonus` object is defined with valid parameters including `incrementCount`, `bonusPerIncrement`, and `maxCount`, additional milestone tiers are generated sequentially starting from `minCount + incrementCount` up to `maxCount`. Each intermediate milestone records its preceding boundary in `fromThreshold`, the target metric count in `threshold`, and the payout in `rewardAmount`.
Sources: [apps/web/lib/bounty/social-metrics-milestones.ts:33-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/social-metrics-milestones.ts#L33-L81)
```typescript
export function getSocialMetricsMilestones(
bounty: BountyInfoInput | undefined | null,
): SocialMetricsMilestone[] {
const bountyInfo = resolveBountyDetails(bounty);
const socialMetrics = bountyInfo?.socialMetrics;
const rewardAmount = bounty?.rewardAmount ?? 0;
if (!socialMetrics?.metric || !socialMetrics.minCount || rewardAmount <= 0) {
return [];
}
const { minCount, incrementalBonus } = socialMetrics;
const milestones: SocialMetricsMilestone[] = [
{
fromThreshold: 0,
threshold: minCount,
rewardAmount,
},
];
if (incrementalBonus) {
const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
const hasValidIncrementalBonus =
incrementCount != null &&
bonusPerIncrement != null &&
maxCount != null &&
incrementCount > 0;
if (hasValidIncrementalBonus) {
for (
let t = minCount + incrementCount;
t <= maxCount;
t += incrementCount
) {
milestones.push({
fromThreshold: t - incrementCount,
threshold: t,
rewardAmount: bonusPerIncrement,
});
}
}
}
return milestones;
}
```
Sources: [apps/web/lib/bounty/social-metrics-milestones.ts:33-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/social-metrics-milestones.ts#L33-L81)
> [!NOTE]
> The earning cap for a social metrics bounty is determined by `getSocialMetricsEarningCap`, which evaluates the `threshold` value of the final element in the generated milestones array. When a partner submission reaches or exceeds this metric count, `hasReachedSocialMetricsEarningCap` returns true and disables further synchronization needs.
Sources: [apps/web/lib/bounty/social-metrics-milestones.ts:84-109](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/social-metrics-milestones.ts#L84-L109)
### Submission Approval and Commission Queueing
When a program operator approves milestones for a submission through `approveSocialMetricsMilestones`, the system identifies pending tiers via `getPendingSocialMetricsMilestones` where the milestone threshold falls between the submission's current `socialMetricCount` and its previously `approvedSocialMetricThreshold`. The approval transaction updates the submission record, advancing the `approvedSocialMetricThreshold` to the highest pending milestone's threshold and setting the submission status to `approved` if `completesEarningCap` is met, or keeping it `submitted` for intermediate progress.
Sources: [apps/web/lib/bounty/api/approve-bounty-submission.ts:204-274](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/approve-bounty-submission.ts#L204-L274)
Concurrently, a descriptive commission entry is generated using `buildMilestonesCommissionDescription` and enqueued via `queuePartnerCommissionCreation`. The total reward is calculated by summing the `rewardAmount` across all pending milestones in the batch.
Sources: [apps/web/lib/bounty/api/approve-bounty-submission.ts:271-304](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/approve-bounty-submission.ts#L271-L304)
```typescript
const rewardAmount = pendingMilestones.reduce(
(sum, { rewardAmount }) => sum + rewardAmount,
0,
);
const description = buildMilestonesCommissionDescription({
bountyName: bounty.name,
metric,
milestone: {
fromThreshold: firstPendingMilestone.fromThreshold,
threshold: approvedThreshold,
},
});
await queuePartnerCommissionCreation({
event: "custom",
partnerId: submission.partnerId,
programId: submission.programId,
amount: rewardAmount,
quantity: 1,
userId: user.id,
source: CommissionSource.user,
description,
bountySubmissionId: submissionId,
metadata: {
socialMetrics: {
metric,
fromThreshold: firstPendingMilestone.fromThreshold,
threshold: approvedThreshold,
milestones: pendingMilestones,
},
},
});
```
Sources: [apps/web/lib/bounty/api/approve-bounty-submission.ts:271-304](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/approve-bounty-submission.ts#L271-L304)
## Performance Submissions and Automated Upserts
### QStash Trigger Pipeline for Draft Submissions
The system automates performance-based referral tracking by triggering draft bounty submissions through QStash. When `triggerDraftBountySubmissionCreation` is invoked, it evaluates program enrollments and finds matching performance bounties that use lifetime statistics (`BountyPerformanceScope.lifetime`). Eligible partner identifiers are collected, and individual JSON publish requests are dispatched to the cron route `/api/cron/bounties/upsert-draft-submissions`.
```typescript
const results = await Promise.allSettled(
bountySubmissionCreationData.map(({ bountyId, partnerIds }) =>
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
body: {
bountyId,
partnerIds,
},
...(idempotencyKey && {
deduplicationId: `${idempotencyKey}-${bountyId}`,
}),
}),
),
);
```
Sources: [apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts:131-144](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts#L131-L144)
> [!NOTE]
> If an `idempotencyKey` is provided when triggering draft submissions, QStash uses a composite deduplication identifier (`${idempotencyKey}-${bountyId}`) to prevent duplicate execution of the same bounty batch.
Sources: [apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts:15-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts#L15-L20), [apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts:139-141](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts#L139-L141)
### Cron Upsert Route Processing
The POST endpoint at `/api/cron/bounties/upsert-draft-submissions` validates incoming QStash signatures, parses request bodies with Zod, and queries the target bounty along with its workflow trigger conditions and program settings.
```typescript
const schema = z.object({
bountyId: z.string(),
partnerIds: z.array(z.string()).optional(),
page: z.number().optional().default(0),
});
const MAX_PAGE_SIZE = 100;
```
Sources: [apps/web/app/ee/api/cron/bounties/upsert-draft-submissions/route.ts:20-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts#L20-L26)
The route enforces several guard clauses before planning submission upserts:
- Bounties starting 10 or more minutes in the future are deferred.
- Non-performance bounties or bounties restricted to new stats (`performanceScope === "new"`) skip submission creation.
- Bounties missing associated workflow triggers are aborted.
Sources: [apps/web/app/ee/api/cron/bounties/upsert-draft-submissions/route.ts:68-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts#L68-L90)
Program enrollments are fetched matching commission-eligible statuses (`COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES`), grouped by group IDs and partner tag filters, and paginated up to `MAX_PAGE_SIZE` (100). Link metrics—including clicks, sales, leads, conversions, and sale amounts—are aggregated via `aggregatePartnerLinksStats` and planned into create or update actions through `planDraftBountySubmissionUpserts`.
```typescript
const createdBountySubmissions =
toCreate.length > 0
? await prisma.bountySubmission.createMany({
data: toCreate,
skipDuplicates: true,
})
: { count: 0 };
if (toUpdate.length > 0) {
await Promise.allSettled(
toUpdate.map((update) =>
prisma.bountySubmission.update({
where: {
id: update.id,
status: "draft", // in case of race condition, we don't want to update an already submitted entry
},
data: {
performanceCount: update.performanceCount,
...(update.promoteToSubmitted && {
status: "submitted",
completedAt: new Date(),
}),
},
}),
),
);
}
```
Sources: [apps/web/app/ee/api/cron/bounties/upsert-draft-submissions/route.ts:203-228](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts#L203-L228)
> [!CAUTION]
> When updating existing draft submissions, the update query explicitly checks `status: "draft"` to prevent race conditions from overwriting submissions that partners have already promoted to submitted status.
Sources: [apps/web/app/ee/api/cron/bounties/upsert-draft-submissions/route.ts:214-218](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts#L214-L218)
## Program Operator Review and UI
### Submission Inspection and Rich Previews
Program operators inspect partner bounty submissions through dedicated management views, such as `BountySubmissionDetailsSheet` and `BountySubmissionsTable`. For bounties with social metrics requirements, the inspection interface automatically renders rich platform embeds via `BountySocialContentPreview`. This component parses submission URLs to generate embedded iframes for supported social platforms, applying platform-specific aspect ratios.
```typescript
function getSocialContentEmbedAspectRatio({
platform,
url,
}: GetSocialContentEmbedAspectRatioParams) {
try {
const parsed = new URL(url);
const pathname = parsed.pathname;
if (platform === "youtube") {
return pathname.includes("/shorts/") ? "aspect-[9/16]" : "aspect-video";
}
if (platform === "tiktok") {
return "aspect-[9/16]";
}
if (platform === "instagram") {
return pathname.includes("/reel/") ? "aspect-[9/16]" : "aspect-square";
}
if (platform === "twitter") {
return "aspect-square";
}
if (platform === "linkedin") {
return "aspect-video";
}
return "aspect-video";
} catch {
return "aspect-video";
}
}
```
Sources: [apps/web/ui/partners/bounties/bounty-social-content-preview.tsx:121-153](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx#L121-L153)
> [!NOTE]
> The embed generator supports exact hostnames and URL path patterns for `youtube`, `instagram`, `tiktok`, `twitter`, and `linkedin`, extracting unique post or video identifiers to construct clean iframe source URLs.
Sources: [apps/web/ui/partners/bounties/bounty-social-content-preview.tsx:31-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx#L31-L118)
### Status Badges and Filtering
Operator dashboards categorize submissions using `BountySubmissionStatusBadges`, providing quick visibility into submission lifecycles. Table filters built via `BountySubmissionFilters` allow operators to isolate submissions awaiting review and refresh social metrics synchronization status on demand.
| Status / Filter Element | Target State / Component | Purpose |
| :--- | :--- | :--- |
| `submitted` | Pending review | Isolates submissions that require program manager moderation |
| `approved` | Approved | Indicates submissions that have successfully passed inspection |
| `rejected` | Rejected | Denotes submissions declined by operators |
| Awaiting review button | `BountySubmissionFilters` | Quick-action button displaying the live count of pending submissions |
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/bounties/bountyId/bounty-submissions-table.tsx:508-544](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/bounties/%5BbountyId%5D/bounty-submissions-table.tsx#L508-L544), [apps/web/app/ee/app.dub.co/embed/referrals/bounties/submission-detail.tsx:214-217](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-detail.tsx#L214-L217)
## Related
- [Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs)
- [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine)
---
## Technical docs: GET Get shared platforms
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminpartnersharedplatforms
## Parameters
## Responses
## Try It
---
## Technical docs: POST Verify partner identity
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/verifyadminpartneridentity
## Parameters
## Responses
## Try It
---
## Technical docs: Program Marketplace
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/program-marketplace
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/api/cron/network/calculate-program-similarities/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/route.ts)
- [packages/ui/src/nav/content/program-marketplace.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/ui/src/nav/content/program-marketplace.tsx)
- [apps/web/lib/api/network/calculate-partner-ranking.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/network/calculate-partner-ranking.ts)
- [apps/web/prisma/schema/network.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/network.prisma)
- [apps/web/ui/program-marketplace/program-marketplace-card.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/program-marketplace-card.tsx)
- [apps/web/app/ee/api/track/application/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts)
- [apps/web/app/ee/api/network/partners/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/network/partners/route.ts)
- [apps/web/app/ee/api/cron/network/calculate-program-similarities/calculate-performance-similarity.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/calculate-performance-similarity.ts)
- [apps/web/ui/program-marketplace/pages/marketplace-programs-list-page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/pages/marketplace-programs-list-page.tsx)
- [apps/web/app/app.dub.co/marketplace/...segments/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/marketplace/%5B%5B...segments%5D%5D/page.tsx)
- [apps/web/app/ee/api/cron/network/calculate-program-similarities/calculate-partner-similarity.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/calculate-partner-similarity.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx)
- [apps/web/lib/fetchers/get-marketplace-programs-summary.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/fetchers/get-marketplace-programs-summary.ts)
- [apps/web/ui/program-marketplace/featured-program-card.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/featured-program-card.tsx)
- [apps/web/ui/program-marketplace/program-marketplace-banner.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/program-marketplace-banner.tsx)
- [apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx)
- [apps/web/app/api/og/program/categories/route.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/categories/route.tsx)
- [apps/web/app/ee/api/cron/network/calculate-program-similarities/calculate-category-similarity.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/calculate-category-similarity.ts)
- [apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx)
- [apps/web/app/ee/api/marketplace/programs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/marketplace/programs/route.ts)
- [apps/web/ui/program-marketplace/program-card.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/program-card.tsx)
- [apps/web/app/sitemap.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/sitemap.ts)
- [apps/web/ui/program-marketplace/marketplace-program-hero.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/marketplace-program-hero.tsx)
- [apps/web/ui/program-marketplace/external/marketplace-external-list-page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/external/marketplace-external-list-page.tsx)
- [apps/web/app/ee/partners.dub.co/dashboard/programs/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/program-empty-state.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/program-empty-state.tsx)
- [apps/web/lib/fetchers/get-public-network-programs.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/fetchers/get-public-network-programs.ts)
- [apps/web/app/app.dub.co/onboarding/onboarding/steps/program/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/page.tsx)
- [apps/web/app/ee/api/admin/partners/partnerId/shared-platforms/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/%5BpartnerId%5D/shared-platforms/route.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/programs/recent/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/recent/page.tsx)
## Overview
The Program Marketplace serves as Dub's centralized directory for discovering, exploring, and applying to network affiliate and referral programs. It connects prospective affiliates with top SaaS programs through public listings, category filtering, and targeted search capabilities. By bridging public-facing discovery directories with internal workspace tooling, the marketplace enables administrators to curate featured collections and metadata while giving partners streamlined access to program enrollments and [conversion tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking).
Sources: [apps/web/app/app.dub.co/marketplace/...segments/page.tsx:22-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/marketplace/%5B%5B...segments%5D%5D/page.tsx#L22-L39), [apps/web/lib/fetchers/get-public-network-programs.ts:26-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/fetchers/get-public-network-programs.ts#L26-L96), [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx:27-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx#L27-L37)
## Public Marketplace Data Fetching
### Server Fetchers and Prisma Queries
Discoverable network programs are retrieved through server-side fetchers powered by Prisma and cached via React's `cache` utility. The primary data retrieval function, `getPublicNetworkPrograms`, accepts query parameters including `category`, `rewardType`, `featured`, `search`, sorting fields (`popularity`, `recency`), pagination limits, and sort orders. Programs are filtered to include only those where `addedToMarketplaceAt` is not null. When search queries are present, Prisma evaluates an `OR` condition matching program name, slug, domain, url, or description. Reward type filtering evaluates the default partner group (`DEFAULT_PARTNER_GROUP.slug`) for specific relation IDs such as `saleRewardId`, `leadRewardId`, `clickRewardId`, or `discountId`.
```typescript
export const getPublicNetworkPrograms = cache(
async (
params: Partial> = {},
) => {
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" }
: {
```
Sources: [apps/web/lib/fetchers/get-public-network-programs.ts:11-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/fetchers/get-public-network-programs.ts#L11-L96)
Summary summaries for marketplace home pages are fetched via `getMarketplaceProgramsSummary`, which queries marketplace-enabled programs, groups them into featured sets, most popular lists, recent additions, and category rows according to `MARKETPLACE_HOME_CATEGORIES`.
```typescript
export const getMarketplaceProgramsSummary = cache(async () => {
const programs = await prisma.program.findMany({
where: {
addedToMarketplaceAt: {
not: null,
},
},
include: programInclude,
});
const programMeta = programs.map(toProgramMeta);
const usedIds = new Set();
const selectRow = (
candidates: ProgramRecord[],
sortFn: (a: ProgramRecord, b: ProgramRecord) => number,
) =>
selectPrograms(
candidates,
usedIds,
MARKETPLACE_HOME_ROW_PAGE_SIZE,
sortFn,
).map(formatNetworkProgram);
const featuredPrograms = programs
.filter((program) => program.featuredOnMarketplaceAt)
.sort(() => Math.random() - 0.5)
.map(formatNetworkProgram);
const mostPopular = selectRow(programs, byMarketplaceRanking);
const newPrograms = selectPrograms(
programs,
new Set(),
MARKETPLACE_HOME_ROW_PAGE_SIZE,
byRecency,
).map(formatNetworkProgram);
const categoryRows = selectCategoryRows(programMeta, usedIds);
const categories = Object.fromEntries(
Object.values(Category).map((category) => [
category,
(categoryRows.get(category) ?? []).map(formatNetworkProgram),
]),
);
return MarketplaceProgramsSummarySchema.parse({
featuredPrograms,
mostPopular,
newPrograms,
categories,
});
});
```
Sources: [apps/web/lib/fetchers/get-marketplace-programs-summary.ts:146-197](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/fetchers/get-marketplace-programs-summary.ts#L146-L197)
> [!NOTE]
> Reward extraction logic inspects `program.groups[0]`, collecting click, lead, and sale rewards into an array while attaching the associated discount object. Programs lacking groups return empty reward arrays.
Sources: [apps/web/lib/fetchers/get-public-network-programs.ts:98-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/fetchers/get-public-network-programs.ts#L98-L112)
### Public API Routes and Edge Caching
The public marketplace HTTP endpoint exposes filtered and searched program lists at `/api/marketplace/programs`. The route handler parses incoming URL search parameters using `parsePublicMarketplaceQuery` before delegating execution to `getPublicNetworkPrograms`.
```typescript
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);
}
```
Sources: [apps/web/app/ee/api/marketplace/programs/route.ts:9-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/marketplace/programs/route.ts#L9-L16)
> [!TIP]
> Route responses are configured with an edge revalidation window of 3,600 seconds (`revalidate = 3600`), caching filtered directory listings publicly at the edge without partner-scoped session overhead.
Sources: [apps/web/app/ee/api/marketplace/programs/route.ts:5-6](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/marketplace/programs/route.ts#L5-L6)
### Program Categories
Network programs can be categorized across thirteen industry domains defined by the `Category` enum in the Prisma schema.
| Category Enum Value | Description / Domain |
| :--- | :--- |
| `AI` | Artificial intelligence applications and tools |
| `Development` | Developer tools and engineering infrastructure |
| `Design` | Design systems, assets, and creative software |
| `Productivity` | Workflow enhancement and productivity applications |
| `Finance` | Financial technology, banking, and accounting |
| `Marketing` | Marketing automation, SEO, and growth tools |
| `Ecommerce` | E-commerce platforms and merchant tooling |
| `Security` | Cybersecurity, identity management, and compliance |
| `Education` | Learning management systems and educational resources |
| `Health` | Healthtech, fitness, and wellness applications |
| `Consumer` | Consumer-facing software and hardware services |
| `Support` | Customer support, helpdesk, and ticketing systems |
```
enum Category {
AI
Development
Design
Productivity
Finance
Marketing
Ecommerce
Security
Education
Health
Consumer
Support
}
```
Sources: [apps/web/prisma/schema/network.prisma:1-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/network.prisma#L1-L14)
## Program Similarity Computation Engine
### Scheduled Execution and Batching Strategy
The network similarity engine operates via a scheduled QStash cron job running every 12 hours (`0 */12 * * *`) at the endpoint `/api/cron/network/calculate-program-similarities`. The handler validates incoming QStash signatures, parses request payloads using Zod with `currentProgramId` and `comparisonBatchCursor` parameters, and processes programs in batches of 10 (`PROGRAMS_PER_BATCH`).
```typescript
const payloadSchema = z.object({
currentProgramId: z
.string()
.optional()
.describe("Current program being compared."),
comparisonBatchCursor: z
.string()
.optional()
.describe("Cursor for programs to compare against."),
});
const PROGRAMS_PER_BATCH = 10;
// This route is used to calculate program similarities in the network
// Runs once every 12 hours (0 */12 * * *)
// POST /api/cron/network/calculate-program-similarities
export async function POST(req: Request) {
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/route.ts:14-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/route.ts#L14-L30)
Programs are targeted for comparison if they are not deactivated (`deactivatedAt: null`) and are visible in either the marketplace (`addedToMarketplaceAt` is not null) or the partner network (`partnerNetworkEnabledAt` is not null). When a batch finishes processing, the job automatically schedules the next batch or advances to the subsequent target program via QStash JSON publishing.
```typescript
const programs = await prisma.program.findMany({
where: {
id: {
gt: currentProgram.id,
},
deactivatedAt: null,
OR: [
{
addedToMarketplaceAt: {
not: null,
},
},
{
partnerNetworkEnabledAt: {
not: null,
},
},
],
},
...(comparisonBatchCursor && {
cursor: {
id: comparisonBatchCursor,
},
}),
skip: comparisonBatchCursor ? 1 : 0,
orderBy: {
id: "asc",
},
take: PROGRAMS_PER_BATCH,
select: {
id: true,
name: true,
},
});
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/route.ts:64-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/route.ts#L64-L97)
> [!NOTE]
> Program pairs resulting in a combined similarity score exceeding `PROGRAM_SIMILARITY_SCORE_THRESHOLD` are persisted bidirectionally (`programId` and `similarProgramId` entries) within a Prisma transaction after purging stale records for the batch.
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/route.ts:147-183](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/route.ts#L147-L183)
### Multi-Dimensional Similarity Metrics
The final similarity score is computed as a weighted aggregate of three distinct vector and set-based dimensions: category similarity (weighted at 50%), partner similarity (weighted at 30%), and performance similarity (weighted at 20%).
```typescript
const [
categorySimilarityScore,
partnerSimilarityScore,
performanceSimilarityScore,
] = await Promise.all([
calculateCategorySimilarity(program1.id, program2.id),
calculatePartnerSimilarity(program1.id, program2.id),
calculatePerformanceSimilarity(program1.id, program2.id),
]);
const similarityScore =
categorySimilarityScore * 0.5 +
partnerSimilarityScore * 0.3 +
performanceSimilarityScore * 0.2;
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/route.ts:122-136](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/route.ts#L122-L136)
| Similarity Dimension | Mathematical Approach | Implementation File | Weight |
| :--- | :--- | :--- | :--- |
| **Category Similarity** | Jaccard Similarity | `calculate-category-similarity.ts` | 0.5 |
| **Partner Similarity** | Jaccard Similarity | `calculate-partner-similarity.ts` | 0.3 |
| **Performance Similarity** | Cosine Similarity | `calculate-performance-similarity.ts` | 0.2 |
```typescript
const similarityScore =
categorySimilarityScore * 0.5 +
partnerSimilarityScore * 0.3 +
performanceSimilarityScore * 0.2;
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/route.ts:132-135](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/route.ts#L132-L135)
### Component Algorithm Implementation
Category and partner similarities utilize Jaccard coefficients calculated from database relations. Category similarity compares distinct assigned categories via `prisma.programCategory`, while partner similarity executes a raw SQL join across `ProgramEnrollment` records to evaluate shared affiliate overlap.
```typescript
export async function calculateCategorySimilarity(
program1Id: string,
program2Id: string,
): Promise {
const [categories1, categories2] = await Promise.all([
prisma.programCategory.findMany({
where: {
programId: program1Id,
},
select: {
category: true,
},
}),
prisma.programCategory.findMany({
where: {
programId: program2Id,
},
select: {
category: true,
},
}),
]);
const categories1Set = new Set(categories1.map(({ category }) => category));
const categories2Set = new Set(categories2.map(({ category }) => category));
const sharedCount = [...categories1Set].filter((c) =>
categories2Set.has(c),
).length;
const totalUniqueCount =
categories1Set.size + categories2Set.size - sharedCount;
if (totalUniqueCount === 0) {
return 0;
}
return sharedCount / totalUniqueCount;
}
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/calculate-category-similarity.ts:4-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/calculate-category-similarity.ts#L4-L43)
Performance similarity builds vectors from averaged enrollment metrics across five specific keys: `totalClicks`, `totalLeads`, `totalConversions`, `totalSales`, and `totalSaleAmount`. It then computes the cosine similarity between the resulting vectors for the two programs.
```typescript
const METRIC_KEYS = [
"totalClicks",
"totalLeads",
"totalConversions",
"totalSales",
"totalSaleAmount",
] as const;
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/calculate-performance-similarity.ts:3-9](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/calculate-performance-similarity.ts#L3-L9)
```typescript
export async function calculatePerformanceSimilarity(
program1Id: string,
program2Id: string,
): Promise {
const [performance1, performance2] = await Promise.all([
prisma.programEnrollment.aggregate({
where: {
programId: program1Id,
},
_avg: {
totalClicks: true,
totalLeads: true,
totalSales: true,
totalConversions: true,
totalSaleAmount: true,
},
}),
prisma.programEnrollment.aggregate({
where: {
programId: program2Id,
},
_avg: {
totalClicks: true,
totalLeads: true,
totalSales: true,
totalConversions: true,
totalSaleAmount: true,
},
}),
]);
const program1Vector = METRIC_KEYS.map((key) => performance1._avg[key] ?? 0);
const program2Vector = METRIC_KEYS.map((key) => performance2._avg[key] ?? 0);
const dotProduct = program1Vector.reduce(
(sum, val, i) => sum + val * program2Vector[i],
0,
);
const magnitude1 = Math.sqrt(
program1Vector.reduce((sum, val) => sum + val ** 2, 0),
);
const magnitude2 = Math.sqrt(
program2Vector.reduce((sum, val) => sum + val ** 2, 0),
);
if (magnitude1 === 0 || magnitude2 === 0) {
return 0;
}
return dotProduct / (magnitude1 * magnitude2);
}
```
Sources: [apps/web/app/ee/api/cron/network/calculate-program-similarities/calculate-performance-similarity.ts:12-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/network/calculate-program-similarities/calculate-performance-similarity.ts#L12-L65)
## Partner Ranking and Discovery Scoring
### Discoverability and Ranking Algorithm
Workspace partner search operations evaluate eligibility and calculate scores via `calculatePartnerRanking`. Partners must meet baseline criteria: their network status must be either `"approved"` or `"trusted"`, their click-to-conversion rate must be strictly below 1, they must not have an active enrollment (`enrolled.id IS NULL`), and they must not be marked as ignored (`dp.ignoredAt IS NULL`).
```typescript
const conditions: Prisma.Sql[] = [
Prisma.sql`p.networkStatus IN ("approved", "trusted")`,
Prisma.sql`COALESCE(pe.clickToConversionRate, 0) < 1`,
Prisma.sql`(dp.ignoredAt IS NULL OR dp.id IS NULL)`,
Prisma.sql`enrolled.id IS NULL`,
];
```
Sources: [apps/web/lib/api/network/calculate-partner-ranking.ts:77-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/network/calculate-partner-ranking.ts#L77-L82)
The scoring model for the discovery tab yields a total score between 0 and 265+ points, synthesized from three additive components:
| Scoring Component | Point Range | Weight / Calculation Mechanics |
| :--- | :--- | :--- |
| **Trusted Partner Bonus** | 200 points | Applied exclusively when `networkStatus = "trusted"` to ensure top-tier priority boost. |
| **Similarity Score** | 0–50 points | Weighted performance across similar programs where similarity score exceeds 0.3. |
| **Program Match Score** | 0–15 points | 2 points per similar program the partner is enrolled in (capped at 15 points). |
```typescript
* Scoring Breakdown (0-65+ points):
*
* 1. Trusted Partner Bonus (200 points): Top priority boost
* - Partners with networkStatus = "trusted" get 200 bonus points
* - This ensures trusted partners appear at the very top
*
* 2. Similarity Score (0-50 points): Performance in similar programs
* - Sums weighted performance across similar programs (similarityScore > 0.3)
* - Each program's performance weighted by its similarity score
* - Partners with more similar programs score higher (capped at 50)
* - Includes: consistency (20%), conversion rate (10%), LTV (15%), commissions (5%)
*
* 3. Program Match Score (0-15 points): Count of similar programs
* - Rewards partners enrolled in many similar programs
* - 2 points per similar program (capped at 15)
*
* Final Score = Trusted Bonus + Similarity + Match (0-265+ points)
*
```
Sources: [apps/web/lib/api/network/calculate-partner-ranking.ts:18-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/network/calculate-partner-ranking.ts#L18-L35)
> [!NOTE]
> The similarity score sums individual program performance metrics using specific internal weights: consistency at 20%, conversion rate at 10%, LTV at 15%, and commissions at 5%.
Sources: [apps/web/lib/api/network/calculate-partner-ranking.ts:28-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/network/calculate-partner-ranking.ts#L28-L29)
### Sorting and Shared Platform Resolution
The sorting mechanism is handled by `buildOrderByClause`, which accepts `starred`, `sortBy`, and `platform` arguments. If `starred` is true, results are ordered descending by `dp.starredAt`. If sorting by subscribers with an active platform filter, the query extracts the maximum verified subscriber count for that specific platform type before ordering.
```typescript
function buildOrderByClause({
starred,
sortBy,
platform,
}: {
starred?: boolean | null;
sortBy?: "relevance" | "subscribers";
platform?: PlatformType;
}) {
if (starred === true) {
return Prisma.sql`dp.starredAt DESC`;
}
if (sortBy === "subscribers" && platform) {
return Prisma.sql`(
SELECT COALESCE(MAX(pp_sort.subscribers), 0)
FROM PartnerPlatform pp_sort
WHERE pp_sort.partnerId = p.id
AND pp_sort.type = ${platform}
AND pp_sort.verifiedAt IS NOT NULL
) DESC, p.id ASC`;
}
return Prisma.sql`finalScore DESC, p.id ASC`;
}
```
Sources: [apps/web/lib/api/network/calculate-partner-ranking.ts:40-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/network/calculate-partner-ranking.ts#L40-L64)
Administrators can inspect overlapping partners across the network via the shared platforms route. Verified platforms are filtered, and website identifiers are stripped of their `www` prefix using `getDomainWithoutWWW` to evaluate domain-level matches rather than exact URL strings.
```typescript
const verifiedPlatforms = partner.platforms.filter(
(platform) => platform.verifiedAt !== null,
);
// a partner has at most one platform per type, so there is at most one website
const websitePlatform = verifiedPlatforms.find(
(platform) => platform.type === "website",
);
const websiteDomain = websitePlatform
? getDomainWithoutWWW(websitePlatform.identifier) ?? null
: null;
const matchConditions: Prisma.PartnerPlatformWhereInput[] = [];
for (const platform of verifiedPlatforms) {
if (platform.type === "website") {
// website identifiers are full URLs with inconsistent normalization,
// so match on the domain instead of the exact identifier
if (websiteDomain) {
matchConditions.push({
identifier: {
contains: websiteDomain,
},
type: platform.type,
});
}
```
Sources: [apps/web/app/ee/api/admin/partners/partnerId/shared-platforms/route.ts:23-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/%5BpartnerId%5D/shared-platforms/route.ts#L23-L49)
> [!WARNING]
> Website matches utilizing `contains` queries are post-processed to verify exact domain equality (`getDomainWithoutWWW(match.identifier) === websiteDomain`), preventing partial substring collisions such as matching `example.com` against `notexample.com`.
Sources: [apps/web/app/ee/api/admin/partners/partnerId/shared-platforms/route.ts:95-103](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/%5BpartnerId%5D/shared-platforms/route.ts#L95-L103)
## Marketplace UI and Navigation Surfaces
### Public Directory Layout and Navigation Surfaces
The program marketplace features multiple navigation entry points and directory layouts. In public navigation menus, `ProgramMarketplaceSection` renders a navigation link pointing to `/marketplace` with dynamic UTM tracking parameters (`NAV_UTM_PARAMS`) where `utm_content` is explicitly set to `"Program Marketplace"`. The navigation item incorporates a decorative floating grid pattern via `Grid` with a cell size of 60 and pattern offsets of `[-12, -32]`. It also features animated company logo nodes floating via motion transitions.
```tsx
export function ProgramMarketplaceSection({ domain }: { domain: string }) {
return (
{/* offset so a horizontal cell edge sits just below the middle of the bar */}
```
Sources: [packages/ui/src/nav/content/program-marketplace.tsx:100-119](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/ui/src/nav/content/program-marketplace.tsx#L100-L119)
> [!NOTE]
> The floating logo canvas (`ProgramMarketplaceLogos`) uses deterministic drift physics based on slot indices, calculating movement amplitudes (`amplitude = 0.6 + depth * 0.8`) with `Math.sin` and `Math.cos` to simulate water buoyancy and parallax depth across 16 predefined company logo slots.
Sources: [packages/ui/src/nav/content/program-marketplace.tsx:9-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/ui/src/nav/content/program-marketplace.tsx#L9-L50)
External routing is structured around dynamic segments at `/marketplace/[[...segments]]`. Metadata generation (`generateMetadata`) parses segment lengths to construct context-aware SEO titles, descriptions, and OpenGraph images. Specifically, category paths matching `/marketplace/c/[category]` resolve human-readable labels from `PROGRAM_CATEGORIES_MAP` and generate category-specific OpenGraph image endpoints.
```tsx
export async function generateMetadata(props: {
params: Promise<{ segments?: string[] }>;
}): Promise {
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} Affiliate Program`;
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} SaaS 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()}`;
}
}
```
Sources: [apps/web/app/app.dub.co/marketplace/...segments/page.tsx:14-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/marketplace/%5B%5B...segments%5D%5D/page.tsx#L14-L59)
### Category Navigation and Promo Banners
The marketplace home view (`MarketplaceHomePage`) aggregates summary statistics via `/api/network/programs/summary` using SWR, rendering featured programs, category sections via `MarketplaceCategoriesSection`, and organized rows using `MarketplaceProgramRow` driven by `MARKETPLACE_HOME_ROWS`.
```tsx
export function MarketplaceHomePage() {
const { data: summary } = useSWR(
"/api/network/programs/summary",
fetcher,
{ revalidateOnFocus: false },
);
return (
{summary ? (
) : (
)}
{MARKETPLACE_HOME_ROWS.map((row) => (
))}
```
Sources: [apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx:19-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/pages/marketplace-home-page.tsx#L19-L47)
For partner dashboards, promotional visibility is handled by `ProgramMarketplaceBanner` and `ProgramMarketplaceCard`, which check partner profile state and promo status. The banner supports animated expansion and collapse states, offering a direct call-to-action to view the marketplace alongside a dismiss button that downgrades the promo state to a card variant.
```tsx
export function ProgramMarketplaceBanner() {
const { partner } = usePartnerProfile();
const { status, setStatus } = useProgramMarketplacePromo();
return (
{partner && status === "banner" && (
```
Sources: [apps/web/ui/program-marketplace/program-marketplace-banner.tsx:12-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/program-marketplace-banner.tsx#L12-L25)
The internal programs list page (`MarketplaceProgramsListPage`) manages pagination and active filters by querying `/api/network/programs` with query parameters derived from the active category pathname. Pagination uses `PROGRAM_NETWORK_MAX_PAGE_SIZE` and renders `PaginationControls` inside a sticky bottom bar when program counts exceed single-page limits.
```tsx
export function MarketplaceProgramsListPage() {
const pathname = usePathname();
const { getQueryString, searchParamsObj } = useRouterStuff();
const categoryParam = getMarketplaceCategoryFromPathname(pathname);
const queryString = getQueryString(
categoryParam ? { category: categoryParam } : undefined,
);
const { data: programsCount, error: countError } = useNetworkProgramsCount({
query: categoryParam ? { category: categoryParam } : undefined,
});
const {
data: programs,
error,
isValidating,
} = useSWR(
`/api/network/programs${queryString}`,
fetcher,
{ revalidateOnFocus: false, keepPreviousData: true },
);
const { pagination, setPagination } = usePagination(
PROGRAM_NETWORK_MAX_PAGE_SIZE,
);
const { activeFilters, onRemoveAll } = useProgramNetworkFilters();
const hasActiveFilters =
activeFilters.length > 0 || Boolean(searchParamsObj.search);
return (
{error || countError ? (
Failed to load programs
) : !programs || programs?.length ? (
{programs ? (
) : (
)}
`program${p ? "s" : ""}`}
/>
```
Sources: [apps/web/ui/program-marketplace/pages/marketplace-programs-list-page.tsx:19-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/pages/marketplace-programs-list-page.tsx#L19-L79)
### Card Visualizations and Accent Color Extraction
Program representations utilize specialized card components including `FeaturedProgramCard`, `MarketplaceProgramCard`, and `MarketplaceProgramHero`. Each card dynamically computes aesthetic backdrops using image accent color extraction hooks (`useImageAccentColor`). If color extraction is pending or blocked, cards fall back to deterministic palette arrays.
| Card Component | Layout Structure | Primary Visual Elements |
| :--- | :--- | :--- |
| **FeaturedProgramCard** | Responsive flex layout with header banner integration (`sm:min-h-[340px]`) | Program logo, status badge, description, rewards summary, and external website link with globe icon. |
| **MarketplaceProgramCard** | Vertical grid cell card with hover drop shadow (`hover:drop-shadow-card-hover`) | Circular avatar, program name, truncated 2-line description, and structured reward badges. |
| **MarketplaceProgramHero** | Extended full-width hero header with banner image slot (`min-h-[640px]` when banner active) | Large avatar, title, category tags via `ProgramCategory`, website link, and action slot container. |
```tsx
export function FeaturedProgramCard({
program,
externalMarketplace = false,
colorIndex = 0,
}: {
program: NetworkProgramProps;
externalMarketplace?: boolean;
colorIndex?: number;
}) {
const router = useRouter();
const rewards = program.rewards;
// Derive the tint from the program's image
// Fall back to the palette if extraction is blocked
const { color: accentColor, ready: accentReady } = useImageAccentColor(
program.marketplaceHeaderImage ?? program.logo,
);
const backgroundColor = accentColor ?? getFeaturedCardBackground(colorIndex);
return (
```
Sources: [apps/web/ui/program-marketplace/featured-program-card.tsx:35-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/featured-program-card.tsx#L35-L55)
> [!IMPORTANT]
> `FeaturedProgramCard` cycles through an array of 10 pastel background hex codes (`FEATURED_CARD_BACKGROUNDS`) using modulo arithmetic (`colorIndex % length`), guaranteeing consistent chromatic distribution across items when image accent extraction is not yet ready.
Sources: [apps/web/ui/program-marketplace/featured-program-card.tsx:14-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/featured-program-card.tsx#L14-L33)
## Application Analytics and Conversion Tracking
### Visitor Device Context and URL Path Routing
Tracking marketplace visitor interactions and application clicks involves capturing client device contexts and resolving incoming request URLs into network program slugs. The tracking subsystem parses user-agent headers to record operating system details, browser context, architecture, and referral origins. When an external program page initializes via `MarketplaceExternalProgramPage`, it mounts an `ApplicationAnalytics` component alongside the external shell wrapper and apply button.
```tsx
return (
<>
[!NOTE]
> If `getNetworkProgram` fails to resolve a valid program record for a given `programSlug`, `MarketplaceExternalProgramPage` immediately triggers a server-side redirect to `/marketplace`.
Sources: [apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx:18-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/program-marketplace/external/marketplace-external-program-page.tsx#L18-L24)
### Program Slug Identification Routing
The route tracking logic uses `identityProgramSlug` to map incoming request URLs to specific program slugs or marketplace directory partitions. The parser evaluates pathname segments against known route patterns to determine whether a request targets an individual program, a category view, or platform registration.
| Route Pattern | Parsed Path Structure | Output Slug and Marketplace Flag |
| :--- | :--- | :--- |
| Root Marketplace | `/marketplace` | `programSlug: null`, `isMarketplace: true` |
| Category View | `/marketplace/c/{category}` | `programSlug: null`, `isMarketplace: true` |
| Reserved Slug Check | `/marketplace/{reservedSlug}` | `programSlug: null`, `isMarketplace: true` |
| Direct Marketplace Program | `/marketplace/{programSlug}` | `programSlug: parts[1].toLowerCase()`, `isMarketplace: true` |
| Legacy Marketplace Program | `/programs/marketplace/{programSlug}` | `programSlug: parts[2].toLowerCase()`, `isMarketplace: true` |
| Standard Program Path | `/programs/{programSlug}` | `programSlug: parts[1].toLowerCase()`, `isMarketplace: false` |
| Platform Registration | `/register` | `programSlug: NETWORK_PROGRAM_SLUG`, `isMarketplace: false` |
| Short Slug Route | `/{programSlug}` | `programSlug: parts[0].toLowerCase()`, `isMarketplace: false` |
```typescript
function identityProgramSlug(url: string) {
try {
const urlObj = new URL(url);
const parts = urlObj.pathname.split("/").filter(Boolean);
if (parts.length === 0) {
return { programSlug: null, isMarketplace: false };
}
if (parts[0] === "register") {
return { programSlug: NETWORK_PROGRAM_SLUG, isMarketplace: false };
}
if (parts[0] === "marketplace") {
if (parts.length === 1) {
return { programSlug: null, isMarketplace: true };
}
if (parts[1] === "c") {
return { programSlug: null, isMarketplace: true };
}
if (parts.length === 2) {
if (MARKETPLACE_RESERVED_SLUGS.has(parts[1])) {
return { programSlug: null, isMarketplace: true };
}
return {
programSlug: parts[1].toLowerCase(),
isMarketplace: true,
};
}
return { programSlug: null, isMarketplace: true };
}
if (parts[0] === "programs" && parts[1] === "marketplace") {
if (!parts[2] || MARKETPLACE_RESERVED_SLUGS.has(parts[2])) {
return { programSlug: null, isMarketplace: false };
}
return {
programSlug: parts[2].toLowerCase(),
isMarketplace: true,
};
}
if (parts[0] === "programs") {
if (!parts[1]) {
return { programSlug: null, isMarketplace: false };
}
return {
programSlug: parts[1].toLowerCase(),
isMarketplace: false,
};
}
return {
programSlug: parts[0].toLowerCase(),
isMarketplace: false,
};
```
Sources: [apps/web/app/ee/api/track/application/route.ts:419-480](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts#L419-L480)
> [!CAUTION]
> The `identityProgramSlug` function wraps its URL parsing inside a `try...catch` block; malformed or unparseable URL strings do not throw errors but instead silently return a fallback object with `programSlug: null` and `isMarketplace: false`.
Sources: [apps/web/app/ee/api/track/application/route.ts:481-484](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts#L481-L484)
## Marketplace Administration and Metadata Operations
### Admin Dashboard and Program Sorting
Administrative management of marketplace listings is handled through designated administrative dashboard views where operators can update program descriptions, manage category classifications, and alter display rankings. The administrative interface manages ranking positions by tracking original and modified index states, computing updates when programs are reordered, and falling back to `MAX_MARKETPLACE_RANKING` (`2147483647`) for unranked items.
```tsx
const MAX_MARKETPLACE_RANKING = 2147483647;
type MarketplaceProgram = {
id: string;
name: string;
slug: string;
logo: string | null;
url: string | null;
description: string | null;
addedToMarketplaceAt: string | Date;
marketplaceRanking: number;
categories: Category[];
};
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx:25-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx#L25-L38)
> [!WARNING]
> Programs assigned `MAX_MARKETPLACE_RANKING` are excluded from standard positional sequencing calculations, ensuring unranked entries do not disrupt custom ordering among featured marketplace listings.
Sources: [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx:97-138](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx#L97-L138)
Operators can also review recent programs via a dedicated administration view that filters workspaces by plan tier and exposes direct actions to add unlisted programs into the public marketplace directory.
```tsx
const filters = useMemo(
() => [
{
key: "plan",
icon: CreditCard,
label: "Plan",
singleSelect: true,
options: plans.map((value) => ({
value,
label: capitalize(value) ?? value,
})),
},
],
[],
);
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/programs/recent/page.tsx:59-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/recent/page.tsx#L59-L73)
### Sitemap Generation and Category Metadata
Search engine optimization and metadata generation leverage automated sitemap compilation routines alongside dynamic Open Graph image generators. The sitemap generation routine inspects incoming request host headers to determine domain context and construct corresponding URL entries.
| Host Context | Query Target | Generated Sitemap Paths |
| :--- | :--- | :--- |
| Partners Hostname (`PARTNERS_HOSTNAMES`) | `prisma.program.findMany` with published default groups | `https://partners.dub.co/{program.slug}` |
| Application Hostname (`isAppHostname`) | `prisma.program.findMany` where `addedToMarketplaceAt` is not null | `https://dub.co/marketplace`, `https://dub.co/marketplace/programs`, category paths, and individual program URLs |
```typescript
if (PARTNERS_HOSTNAMES.has(domain)) {
const programs = await prisma.program.findMany({
where: {
groups: {
some: {
slug: "default",
landerData: {
not: Prisma.AnyNull,
},
landerPublishedAt: {
not: null,
},
},
},
},
orderBy: {
slug: "asc",
},
});
return programs.map((program) => ({
url: `https://partners.dub.co/${program.slug}`,
lastModified: new Date(),
}));
}
```
Sources: [apps/web/app/sitemap.ts:20-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/sitemap.ts#L20-L44)
> [!IMPORTANT]
> When executing on application hostnames, the sitemap generator iterates over all values of the Prisma `Category` enum to construct category-specific directory links alongside individual marketplace program records.
Sources: [apps/web/app/sitemap.ts:78-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/sitemap.ts#L78-L86)
Category-specific Open Graph images are dynamically rendered using Next.js image response utilities. The category OG route extracts the `categorySlug` search parameter, matches it against `PROGRAM_CATEGORIES`, and renders a styled SVG grid layout with Inter typography and category metadata.
```tsx
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,
});
}
```
Sources: [apps/web/app/api/og/program/categories/route.tsx:15-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/og/program/categories/route.tsx#L15-L32)
### Onboarding Integration
Workspace onboarding connects new affiliate programs to the application routing flow by validating active user sessions and project domain bindings. The onboarding step retrieves domain records stored in Redis or workspace configurations, redirecting unconfigured users to domain setup before rendering the client onboarding page.
```tsx
const data = await redis.get<{ domain: string; userId: string }>(
`onboarding-domain:${workspace.id}`,
);
const onboardingDomain =
data && data.domain && data.userId === user.id ? data.domain : null;
const domain = onboardingDomain || workspace.domains[0]?.slug;
if (!domain)
redirect(`/onboarding/domain?workspace=${slug}&product=partners`);
```
Sources: [apps/web/app/app.dub.co/onboarding/onboarding/steps/program/page.tsx:38-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/page.tsx#L38-L49)
Workspaces lacking configured programs display an empty state component featuring partner preview cells that utilize repeating coordinate mappings over a shared asset sprite.
```tsx
const EXAMPLE_PARTNERS = [
{
name: "Lauren Anderson",
country: "US",
revenue: 1_800,
payouts: 550,
index: 0,
},
{
name: "Elias Weber",
country: "DE",
revenue: 783,
payouts: 235,
index: 4,
},
{
name: "Hiroshi Tanaka",
country: "JP",
revenue: 19_200,
payouts: 5_700,
index: 3,
},
{
name: "Mia Taylor",
country: "US",
revenue: 22_600,
payouts: 6_800,
index: 1,
},
];
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/program-empty-state.tsx:60-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/program-empty-state.tsx#L60-L90)
## Related
- [Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs)
---
## Technical docs: Workspace Subscriptions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/workspace-subscriptions
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/swr/use-webhooks.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-webhooks.ts)
- [apps/web/app/ee/api/stripe/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts)
- [apps/web/app/ee/api/stripe/webhook/checkout-session-completed.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts)
- [apps/web/app/ee/api/stripe/webhook/utils/update-workspace-plan.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts)
- [apps/web/app/api/callback/plain/workspace/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/plain/workspace/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/billing/manage/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/manage/route.ts)
- [apps/web/app/ee/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/invoice-paid.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts)
- [apps/web/app/api/webhooks/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/billing/upgrade/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/upgrade/route.ts)
- [apps/web/app/ee/api/singular/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts)
- [apps/web/app/ee/api/stripe/connect/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts)
- [apps/web/app/api/dub/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/billing/payment-methods/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/payment-methods/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/billing/invoices/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/invoices/route.ts)
- [apps/web/app/ee/api/stripe/webhook/customer-subscription-updated.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts)
- [apps/web/app/ee/api/hubspot/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/billing/plan-usage.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/billing/plan-usage.tsx)
- [apps/web/app/ee/api/stripe/webhook/invoice-payment-failed.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/app/ee/api/stripe/webhook/charge-dispute-created.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/billing/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/billing/page.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/webhooks/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/webhooks/page-client.tsx)
- [packages/stripe-app/src/utils/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/dub.ts)
- [apps/web/app/api/workspaces/idOrSlug/billing/activate-paid-plan/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/activate-paid-plan/route.ts)
- [apps/web/app/api/dub/webhook/lead-created.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/lead-created.ts)
- [packages/stripe-app/src/hooks/use-workspace.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/hooks/use-workspace.ts)
- [apps/web/ui/workspaces/subscription-menu.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/workspaces/subscription-menu.tsx)
- [apps/web/lib/api/billing/recompute-workspace-usage.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/billing/recompute-workspace-usage.ts)
## Overview
Workspace Subscriptions manages enterprise billing integration, subscription lifecycles, and plan quotas through Stripe webhooks, [REST API](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api) endpoints, and Tinybird metrics tracking. It automates workspace plan upgrades, trial enforcement, payment delinquency handling, and billing portal access while synchronizing customer subscription states with the Plain CRM dashboard.
Sources: [apps/web/app/ee/api/stripe/webhook/route.ts:33-104](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts#L33-L104), [apps/web/app/api/workspaces/idOrSlug/billing/manage/route.ts:8-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/manage/route.ts#L8-L35), [apps/web/lib/api/billing/recompute-workspace-usage.ts:8-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/billing/recompute-workspace-usage.ts#L8-L50)
## Workspace Billing Endpoints
### Portal Management and Plan Upgrades
Dub exposes workspace-authenticated REST API routes under `/api/workspaces/[idOrSlug]/billing/` to manage subscriptions, payment methods, invoices, and billing portal sessions via Stripe. These endpoints require appropriate permissions such as `billing.write` or `workspaces.read` through the `withWorkspace` middleware wrapper.
The billing management and upgrade routes interface directly with Stripe sessions. The portal management endpoint creates a Stripe billing portal session restricted by configuration `bpc_1UEvGVAlJJEpqkPVpP38ZUNj` for updating billing details, redirecting users back to `${APP_DOMAIN}/${workspace.slug}/settings/billing`. Enterprise workspaces are restricted from this endpoint, throwing a `forbidden` `DubApiError` because their billing is handled by the account team.
```typescript
if (workspace.plan === "enterprise") {
throw new DubApiError({
code: "forbidden",
message:
"Since you're on an Enterprise plan, billing is managed by your account team. Please reach out to them to manage your subscription.",
});
}
try {
const { url } = await stripe.billingPortal.sessions.create({
customer: workspace.stripeId,
configuration: "bpc_1UEvGVAlJJEpqkPVpP38ZUNj", // custom configuration for changing billing info only
return_url: `${APP_DOMAIN}/${workspace.slug}/settings/billing`,
});
```
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/manage/route.ts:14-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/manage/route.ts#L14-L27)
The upgrade route parses requests against `upgradePlanSchema`, accepting `plan` (`pro`, `business`, `advanced`), `period` (`monthly`, `yearly`), optional `tier` (1 to 3), an `onboarding` boolean flag, and a `baseUrl` validated to start with `APP_DOMAIN`. If a workspace has an active trialing subscription, upgrades update the subscription directly with `proration_behavior: "none"` without issuing invoices or immediate charges. For active non-trialing subscriptions, the endpoint generates a Stripe billing portal session configured with `subscription_update_confirm`. If no subscription exists, it initiates a Stripe checkout session with automatic tax and tax ID collection enabled, setting trial periods via `DUB_TRIAL_PERIOD_DAYS` when eligible.
```typescript
const upgradePlanSchema = z.object({
plan: z.enum(["pro", "business", "advanced"]),
period: z.enum(["monthly", "yearly"]),
tier: z.number().min(1).max(3).optional().default(1),
baseUrl: z.string().refine((url) => url.startsWith(APP_DOMAIN), {
message: "Invalid baseUrl.",
}),
onboarding: booleanQuerySchema.nullish(),
});
```
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/upgrade/route.ts:12-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/upgrade/route.ts#L12-L20), [apps/web/app/api/workspaces/idOrSlug/billing/upgrade/route.ts:68-84](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/upgrade/route.ts#L68-L84), [apps/web/app/api/workspaces/idOrSlug/billing/upgrade/route.ts:103-123](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/upgrade/route.ts#L103-L123), [apps/web/app/api/workspaces/idOrSlug/billing/upgrade/route.ts:141-191](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/upgrade/route.ts#L141-L191)
> [!WARNING]
> Preview environments running on Vercel (`VERCEL === "1"` and `VERCEL_ENV === "preview"`) enforce an administrative role check on plan upgrades; unauthenticated requests or users without a Dub admin role receive an `unauthorized` error.
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/upgrade/route.ts:57-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/upgrade/route.ts#L57-L65)
### Payment Methods and Invoices
Payment methods are retrieved, added, updated, and removed via `/api/workspaces/[idOrSlug]/billing/payment-methods`. The `GET` handler merges Stripe payment methods with pending microdeposits and reorders direct debit methods to the front of the list. The `POST` handler supports adding custom payment types or returning a billing portal session for payment method updates.
```typescript
const [paymentMethods, customer] = await Promise.all([
stripe.paymentMethods.list({
customer: workspace.stripeId,
}),
stripe.customers.retrieve(workspace.stripeId),
]);
const pendingMicrodeposits = await listPendingMicrodeposits(
workspace.stripeId,
).catch(() => []);
const defaultPaymentMethod =
customer.deleted !== true
? customer.invoice_settings?.default_payment_method
: null;
const defaultPaymentMethodId =
typeof defaultPaymentMethod === "string"
? defaultPaymentMethod
: defaultPaymentMethod?.id ?? null;
const methods = withMicrodepositStatus({
paymentMethods: paymentMethods.data,
pendingMicrodeposits,
});
// reorder to put direct debit first
const directDebit = methods.find((method) =>
DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(method.type),
);
return NextResponse.json({
paymentMethods: [
...(directDebit ? [directDebit] : []),
...methods.filter((method) => method.id !== directDebit?.id),
],
defaultPaymentMethodId,
});
```
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/payment-methods/route.ts:62-99](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/payment-methods/route.ts#L62-L99)
| HTTP Method | Request Body / Schema | Action & Behavior |
| :--- | :--- | :--- |
| `GET` | None (Query params optional) | Retrieves customer payment methods, pending microdeposits, and invoice settings default payment method. |
| `POST` | `addPaymentMethodSchema` (`method?: string`) | Creates a Stripe setup checkout session for a specific payment method or opens a billing portal session. |
| `PATCH` | `updatePaymentMethodSchema` (`paymentMethodId: string`) | Sets the default payment method on Stripe customer invoice settings (direct debits disallowed). |
| `DELETE` | `deletePaymentMethodSchema` (`paymentMethodId: string`) | Detaches and removes the specified payment method from the Stripe customer. |
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/payment-methods/route.ts:20-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/payment-methods/route.ts#L20-L30), [apps/web/app/api/workspaces/idOrSlug/billing/payment-methods/route.ts:51-236](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/payment-methods/route.ts#L51-L236)
Invoice listing is handled by `/api/workspaces/[idOrSlug]/billing/invoices`, which accepts query parameters validated against `querySchema`. It supports retrieving Stripe subscription invoices (`type: "subscription"`) limited to 100 entries, as well as internal Prisma-stored invoices for partner payouts (`partnerPayout`) and domain renewals (`domainRenewal`).
```typescript
const querySchema = z.object({
type: z
.enum(["subscription", "partnerPayout", "domainRenewal"])
.optional()
.default("subscription"),
stripeStatus: z.enum(["open"]).optional(), // only for Stripe subscription invoices
});
```
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/invoices/route.ts:9-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/invoices/route.ts#L9-L15), [apps/web/app/api/workspaces/idOrSlug/billing/invoices/route.ts:24-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/invoices/route.ts#L24-L34)
### Trial Activation
The `/api/workspaces/[idOrSlug]/billing/activate-paid-plan` endpoint immediately terminates any active trial for the workspace by setting `trial_end` to `"now"` and `cancel_at_period_end` to `false` on the Stripe subscription, triggering an immediate charge and transitioning the subscription to active status.
```typescript
const { data: trialingSubs } = await stripe.subscriptions.list({
customer: workspace.stripeId,
status: "trialing",
limit: 1,
});
const trialingSubscription = trialingSubs[0];
if (trialingSubscription) {
await stripe.subscriptions.update(trialingSubscription.id, {
trial_end: "now",
cancel_at_period_end: false,
});
return NextResponse.json({ ok: true });
}
```
Sources: [apps/web/app/api/workspaces/idOrSlug/billing/activate-paid-plan/route.ts:13-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/billing/activate-paid-plan/route.ts#L13-L26)
## Stripe Webhook Dispatching
### Webhook Route and Signature Verification
Incoming Stripe webhooks are received at the `POST /api/stripe/webhook` route wrapped with `withAxiom`. The handler reads the raw request body as text and extracts the `Stripe-Signature` header alongside the `STRIPE_WEBHOOK_SECRET` environment variable. If either the signature or the secret is missing, it responds immediately with an `Invalid request` status of 400 via `logAndRespond`. Otherwise, `stripe.webhooks.constructEvent` verifies the cryptographic payload signature, returning a typed `Stripe.Event` object or catching parsing errors to log and return a 400 response.
```typescript
export const POST = withAxiom(async (req: Request) => {
const buf = await req.text();
const sig = req.headers.get("Stripe-Signature") as string;
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
let event: Stripe.Event;
try {
if (!sig || !webhookSecret) {
return logAndRespond("Invalid request", { status: 400 });
}
event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
} catch (err: any) {
console.log(`❌ Error message: ${err.message}`);
return new Response(`Webhook Error: ${err.message}`, {
status: 400,
});
}
```
Sources: [apps/web/app/ee/api/stripe/webhook/route.ts:33-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts#L33-L48)
> [!WARNING]
> Requests lacking a valid `Stripe-Signature` header or evaluated against an unconfigured `STRIPE_WEBHOOK_SECRET` are short-circuited with a 400 error before any event parsing occurs.
Sources: [apps/web/app/ee/api/stripe/webhook/route.ts:39-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts#L39-L41)
### Event Demultiplexing and Handler Routing
Once constructed, the event type is checked against a predefined `relevantEvents` set. Events not present in this set are ignored, returning a 200 status response with `Unsupported event, skipping...`. Relevant events pass through a `switch` statement that routes each payload to its dedicated handler function. Any unhandled execution error within a handler is caught, logged to Axiom with `log`, and returned as a 400 webhook error response.
| Event Type | Handler Function |
| :--- | :--- |
| `charge.succeeded` | `chargeSucceeded(event)` |
| `charge.failed` | `chargeFailed(event)` |
| `charge.refunded` | `chargeRefunded(event)` |
| `charge.dispute.created` | `chargeDisputeCreated(event)` |
| `checkout.session.completed` | `checkoutSessionCompleted(event)` |
| `customer.subscription.created` | `customerSubscriptionCreated(event)` |
| `customer.subscription.updated` | `customerSubscriptionUpdated(event)` |
| `customer.subscription.deleted` | `customerSubscriptionDeleted(event)` |
| `invoice.payment_failed` | `invoicePaymentFailed(event)` |
| `payment_intent.requires_action` | `paymentIntentRequiresAction(event)` |
| `transfer.reversed` | `transferReversed(event)` |
Sources: [apps/web/app/ee/api/stripe/webhook/route.ts:18-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts#L18-L30), [apps/web/app/ee/api/stripe/webhook/route.ts:50-93](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts#L50-L93)
### Subscription Update Processing
The `customerSubscriptionUpdated` function processes updates for subscriptions with status values of `"active"`, `"trialing"`, or `"past_due"`. Any other subscription status causes the handler to skip processing and return an invalid status message. Workspaces are queried via Prisma using the subscription's customer string mapped to `stripeId`, selecting workspace owner users (excluding machine users) and restricted tokens.
```typescript
export async function customerSubscriptionUpdated(
event: Stripe.CustomerSubscriptionUpdatedEvent,
) {
const updatedSubscription = event.data.object;
const priceId = updatedSubscription.items.data[0].price.id;
if (
![
"active",
"trialing",
"past_due", // special case for handling past_due subscriptions (after a free trial)
].includes(updatedSubscription.status)
) {
return `Invalid updated subscription status "${updatedSubscription.status}" for subscription ${updatedSubscription.id}, skipping...`;
}
const stripeId = updatedSubscription.customer.toString();
const workspace = await prisma.project.findUnique({
where: {
stripeId,
},
include: {
users: {
select: {
user: {
select: {
email: true,
name: true,
},
},
},
where: {
role: "owner",
user: {
isMachine: false,
},
},
},
restrictedTokens: {
select: {
hashedKey: true,
},
},
},
});
```
Sources: [apps/web/app/ee/api/stripe/webhook/customer-subscription-updated.ts:8-53](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts#L8-L53)
> [!NOTE]
> When a subscription enters the `past_due` state, the handler checks if the workspace trial ended less than 2 hours ago. If so, it reverts the workspace plan limits back to `TRIAL_LIMITS` values across all tracked resource quotas.
Sources: [apps/web/app/ee/api/stripe/webhook/customer-subscription-updated.ts:59-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts#L59-L89)
If the subscription status is active or trialing, `updateWorkspacePlan` is invoked with the workspace, price ID, and subscription object. If `cancel_at_period_end` is enabled, owner details and cancellation feedback are extracted to dispatch cancellation feedback notifications.
```typescript
await updateWorkspacePlan({
workspace,
priceId,
subscription: updatedSubscription,
});
if (updatedSubscription.cancel_at_period_end) {
const owners = workspace.users.map(({ user }) => user);
const cancelReason = updatedSubscription.cancellation_details?.feedback;
await sendCancellationFeedback({
workspace,
owners,
reason: cancelReason,
});
return `Sent cancellation feedback to ${owners.length} workspace owners for workspace ${workspace.slug}.`;
}
```
Sources: [apps/web/app/ee/api/stripe/webhook/customer-subscription-updated.ts:93-109](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts#L93-L109)
## Subscription Lifecycle and Plan Changes
### Checkout Session Fulfillment and Limits
When a Stripe checkout session completes successfully, `checkoutSessionCompleted` validates that the session mode is set to `"subscription"` and that the payment status is either `"paid"` or `"no_payment_required"`. Setup sessions or uncompleted payments are skipped. The system retrieves the associated Stripe subscription, extracts the price ID, and maps it to a plan and tier using `getPlanAndTierFromPriceId`. If `client_reference_id` or `customer` is missing, an error is logged and processing terminates.
```typescript
if (checkoutSession.mode === "setup") {
return "Session is setup mode, skipping...";
}
if (checkoutSession.mode === "subscription") {
if (
checkoutSession.payment_status !== "paid" &&
checkoutSession.payment_status !== "no_payment_required"
) {
return "Subscription checkout session not completed (payment status), skipping...";
}
} else {
return `Session mode ${checkoutSession.mode} is not handled here, skipping...`;
}
if (
checkoutSession.client_reference_id === null ||
checkoutSession.customer === null
) {
await log({
message: "Missing items in Stripe webhook callback",
type: "errors",
});
return "Missing client_reference_id or customer in checkout session.";
}
```
Sources: [apps/web/app/ee/api/stripe/webhook/checkout-session-completed.ts:24-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts#L24-L48)
Workspace limits are calculated through `getWorkspaceLimitsFromStripeSubscription`. When a subscription is in a trial state, restricted trial quotas from `TRIAL_LIMITS` are applied across all tracked metrics instead of standard plan limits. For active non-trial yearly subscriptions, limits for clicks, links, payouts, and AI capabilities are multiplied by 12 to reflect the annual billing period allocation.
```typescript
export function getWorkspaceLimitsFromStripeSubscription({
planLimits,
subscription,
}: {
planLimits: PlanDetails["limits"];
subscription: Stripe.Subscription;
}): PlanDetails["limits"] {
if (subscription.status !== "trialing") {
const subscriptionPeriod =
getPlanPeriodFromStripeSubscription(subscription);
return {
...planLimits,
...(subscriptionPeriod === "yearly"
? {
clicks: planLimits.clicks * 12,
links: planLimits.links * 12,
payouts: planLimits.payouts * 12,
ai: planLimits.ai * 12,
}
: {}),
};
}
return {
...planLimits,
links: TRIAL_LIMITS.links,
clicks: TRIAL_LIMITS.clicks,
payouts: TRIAL_LIMITS.payouts,
users: TRIAL_LIMITS.users,
domains: TRIAL_LIMITS.domains,
tags: TRIAL_LIMITS.tags,
partnerTags: TRIAL_LIMITS.partnerTags,
folders: TRIAL_LIMITS.folders,
groups: TRIAL_LIMITS.groups,
networkInvites: TRIAL_LIMITS.networkInvites,
partners: TRIAL_LIMITS.partners,
ai: TRIAL_LIMITS.ai,
api: TRIAL_LIMITS.api,
analyticsApi: TRIAL_LIMITS.analyticsApi,
};
```
Sources: [apps/web/app/ee/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts:5-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts#L5-L44)
> [!NOTE]
> Trial limits strictly override standard plan limits regardless of the base plan tier selected during checkout, enforcing a uniform constraint on features like links, clicks, and API access until the trial period expires and converts to a paid subscription.
Sources: [apps/web/app/ee/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts:28-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts#L28-L44)
### Plan Upgrades and Downgrade Mitigation
The `updateWorkspacePlan` utility manages transitions when a workspace modifies its subscription plan, tier, or billing period. If a workspace shifts from a yearly to a monthly billing period, `recomputeWorkspaceUsage` recalculates current usage metrics against the reduced limits.
```typescript
const isYearlyToMonthly =
workspace.planPeriod === "yearly" && planPeriod === "monthly";
const recomputedUsage = isYearlyToMonthly
? await recomputeWorkspaceUsage(workspace)
: null;
```
Sources: [apps/web/app/ee/api/stripe/webhook/utils/update-workspace-plan.ts:108-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts#L108-L114)
```mermaid
flowchart TD
A["Subscription Event Received"] --> B{"Session Mode Valid?"}
B -- No --> C["Skip Processing"]
B -- Yes --> D["Retrieve Stripe Subscription"]
D --> E["Extract Price ID & Map Plan"]
E --> F{"Subscription Status"}
F -- Trialing --> G["Apply TRIAL_LIMITS"]
F -- Active/Other --> H["Calculate Plan Limits"]
G --> I["Update Workspace Project Record"]
H --> I
I --> J["Complete Onboarding & Token Cache Expire"]
J --> K["Dispatch Welcome or Trial Emails"]
```
Sources: [apps/web/app/ee/api/stripe/webhook/checkout-session-completed.ts:24-74](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts#L24-L74), [apps/web/app/ee/api/stripe/webhook/checkout-session-completed.ts:138-174](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts#L138-L174), [apps/web/app/ee/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts:5-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts#L5-L44)
## Usage Recomputation and Quota Accounting
### Aggregating Metrics Across Billing Windows
When a workspace transitions from a yearly to a monthly plan period, usage metrics are explicitly recomputed via `recomputeWorkspaceUsage`. This function determines the current billing start date using `getBillingStartDate` based on the workspace's `billingCycleStart` field, setting the end date to the current timestamp.
```typescript
export async function recomputeWorkspaceUsage(
workspace: Pick,
) {
const billingStart = getBillingStartDate(workspace.billingCycleStart);
const billingEnd = new Date();
```
Sources: [apps/web/lib/api/billing/recompute-workspace-usage.ts:8-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/billing/recompute-workspace-usage.ts#L8-L13)
Three concurrent data aggregation queries execute to assemble the updated usage state: click events and link counts fetched from Tinybird via `getWorkspaceUsage`, alongside completed partner payout invoice amounts aggregated from Prisma.
```typescript
const [clicksData, linksData, payoutsUsage] = await Promise.all([
getWorkspaceUsage({
workspaceId: workspace.id,
resource: "events",
start: billingStart,
end: billingEnd,
}),
getWorkspaceUsage({
workspaceId: workspace.id,
resource: "links",
start: billingStart,
end: billingEnd,
}),
prisma.invoice.aggregate({
where: {
workspaceId: workspace.id,
type: "partnerPayout",
status: "completed",
paidAt: {
gte: billingStart,
lte: billingEnd,
},
},
_sum: {
amount: true,
},
}),
]);
```
Sources: [apps/web/lib/api/billing/recompute-workspace-usage.ts:14-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/billing/recompute-workspace-usage.ts#L14-L43)
### Recomputation Parameters and Operations
The recomputation routine processes event and resource streams across specific parameters before mapping them to workspace project columns.
| Metric Resource | Source Provider | Aggregation Logic | Target Project Field |
| :--- | :--- | :--- | :--- |
| `events` | Tinybird (`getWorkspaceUsage`) | Sum of array values (`d.value`) | `usage` |
| `links` | Tinybird (`getWorkspaceUsage`) | Sum of array values (`d.value`) | `linksUsage` |
| `partnerPayout` | Prisma Invoice model | Aggregate sum where status is `completed` | `payoutsUsage` |
Sources: [apps/web/lib/api/billing/recompute-workspace-usage.ts:14-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/billing/recompute-workspace-usage.ts#L14-L49), [apps/web/app/ee/api/stripe/webhook/utils/update-workspace-plan.ts:154-157](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts#L154-L157)
> [!NOTE]
> When `recomputedUsage` is generated during a yearly-to-monthly downgrade, the update payload also deletes existing usage limit notification emails (`firstUsageLimitEmail`, `secondUsageLimitEmail`, `firstLinksLimitEmail`, and `secondLinksLimitEmail`) from the `sentEmails` relation to reset warning thresholds for the new billing cycle.
Sources: [apps/web/app/ee/api/stripe/webhook/utils/update-workspace-plan.ts:154-170](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts#L154-L170)
## Delinquency Handling and Dispute Enforcement
### Invoice Payment Failure Processing
When Stripe fires an `invoice.payment_failed` event, the system extracts the customer ID, attempt count, and amount due. It queries the `project` model in Prisma using the Stripe customer ID to identify the workspace and filters workspace users to exclude machine accounts where `isMachine` is true.
```tsx
export async function invoicePaymentFailed(
event: Stripe.InvoicePaymentFailedEvent,
) {
const {
customer: stripeId,
attempt_count: attemptCount,
amount_due: amountDue,
} = event.data.object;
if (!stripeId) {
return "No customer found in invoice.payment_failed event.";
}
const workspace = await prisma.project.findUnique({
where: {
stripeId: stripeId.toString(),
},
select: {
id: true,
name: true,
slug: true,
plan: true,
defaultProgramId: true,
users: {
select: {
user: {
select: {
name: true,
email: true,
},
},
},
where: {
user: {
isMachine: false,
},
},
},
},
});
```
Sources: [apps/web/app/ee/api/stripe/webhook/invoice-payment-failed.tsx:6-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx#L6-L45)
The workspace record receives a timestamp update on its `paymentFailedAt` field, while notification emails are dispatched concurrently using `Promise.allSettled` to all eligible human users. The email subject dynamically adjusts based on the payment `attemptCount` value.
| Attempt Count | Email Subject Prefix |
| :--- | :--- |
| `1` | `Your payment for Dub.co failed` |
| `2` | `2nd notice: Your payment for Dub.co failed` |
| `3` | `3rd notice: Your payment for Dub.co failed` |
| `4+` (default) | `Final notice: Your payment for Dub.co failed` |
Sources: [apps/web/app/ee/api/stripe/webhook/invoice-payment-failed.tsx:51-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx#L51-L86)
> [!WARNING]
> `invoicePaymentFailed` uses `Promise.allSettled` when updating the project timestamp and dispatching notification emails. If individual email deliveries fail for specific users, the workspace payment failure timestamp update still resolves successfully.
Sources: [apps/web/app/ee/api/stripe/webhook/invoice-payment-failed.tsx:51-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx#L51-L86)
### Charge Dispute Enforcement
When a charge dispute is created via `charge_dispute.created`, the system retrieves the associated Stripe charge and expands its customer object to locate the corresponding workspace by `stripeId`.
```typescript
export async function chargeDisputeCreated(
event: Stripe.ChargeDisputeCreatedEvent,
) {
const dispute = event.data.object;
const chargeId =
typeof dispute.charge === "string" ? dispute.charge : dispute.charge.id;
const charge = await stripe.charges.retrieve(chargeId, {
expand: ["customer"],
});
const { customer: customerObj, payment_method_details } = charge;
const customer = customerObj as Stripe.Customer;
const workspace = await prisma.project.findUnique({
where: {
stripeId: customer.id,
},
});
// should never happen, but just in case
if (!workspace) {
return `Workspace with stripeId ${customer.id} not found.`;
}
```
Sources: [apps/web/app/ee/api/stripe/webhook/charge-dispute-created.ts:9-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts#L9-L32)
Upon locating the workspace, the system executes a sequence of security and restriction measures:
1. Disables all workspace short links via `disableWorkspaceLinks`.
2. Demotes all workspace users to the `viewer` role, excluding the constant `LEGAL_USER_ID`.
3. Upserts or creates `LEGAL_USER_ID` as the workspace `owner`.
4. Timestamps the workspace `disabledAt` field.
5. Registers the customer ID, customer email, and payment method card fingerprint into Stripe fraud value lists via `addToStripeFraudValueLists`.
6. Cancels the active Stripe subscription with the reason `"Workspace banned due to charge dispute"`.
```typescript
await disableWorkspaceLinks(workspace.id);
// Update all users to viewer role except for LEGAL_USER_ID
const updatedUsers = await prisma.projectUsers.updateMany({
where: {
projectId: workspace.id,
userId: {
not: LEGAL_USER_ID,
},
},
data: {
role: "viewer",
},
});
console.log(`Updated ${updatedUsers.count} users to viewer role`);
// Add LEGAL_USER_ID as owner
await prisma.projectUsers.upsert({
where: {
userId_projectId: {
projectId: workspace.id,
userId: LEGAL_USER_ID,
},
},
update: {
role: "owner",
},
create: {
projectId: workspace.id,
userId: LEGAL_USER_ID,
role: "owner",
},
});
console.log(
`Added legal user ${LEGAL_USER_ID} as owner to workspace ${workspace.id}`,
);
await prisma.project.update({
where: {
id: workspace.id,
},
data: {
disabledAt: new Date(),
},
});
await addToStripeFraudValueLists({
customerId: customer.id,
customerEmail: customer.email,
cardFingerprint: payment_method_details?.card?.fingerprint,
});
await cancelSubscription({
customerId: customer.id,
reason: "Workspace banned due to charge dispute",
});
```
Sources: [apps/web/app/ee/api/stripe/webhook/charge-dispute-created.ts:34-92](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts#L34-L92)
> [!CAUTION]
> A charge dispute event immediately revokes owner privileges from all standard workspace members by forcing their project roles to `viewer`, elevates `LEGAL_USER_ID` to sole owner, disables all links, and terminates the underlying subscription.
Sources: [apps/web/app/ee/api/stripe/webhook/charge-dispute-created.ts:34-92](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts#L34-L92)
## Billing Dashboard and Plan Management UI
### Client-Side Billing Views and Usage Metrics
The workspace billing interface renders detailed plan usage PlanUsage, consumption totals, and active subscription status WorkspaceBilling. The `PlanUsage` component retrieves workspace metadata from `useWorkspace()` to evaluate real-time usage metrics across tracked events, links created, and payouts sent.
```tsx
export default function PlanUsage() {
const {
id: workspaceId,
slug,
plan,
role,
stripeId,
usage,
usageLimit,
linksUsage,
linksLimit,
totalLinks,
payoutsUsage,
payoutsLimit,
payoutFee,
payoutFeeWaiverLimit,
payoutFeeWaiverUsage,
domains,
domainsLimit,
foldersUsage,
foldersLimit,
partnersUsage,
partnersLimit,
groupsLimit,
tagsLimit,
usersLimit,
billingCycleStart,
planPeriod,
trialEndsAt,
subscriptionCanceledAt,
billingCycleEndsAt,
defaultProgramId,
loading,
mutate,
} = useWorkspace();
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/billing/plan-usage.tsx:56-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/billing/plan-usage.tsx#L56-L90)
The interface dynamically builds resource utilization tabs using `useMemo`, conditionally prepending the links tab if total usage exceeds `MEGA_WORKSPACE_LINKS_LIMIT` or appending the payouts tab when a default program identifier is present.
| Resource Tab | Icon Component | Associated Limit Constant / Field |
| :--- | :--- | :--- |
| `events` | `CursorRays` | `usageLimit` |
| `links` | `Hyperlink` | `linksLimit` |
| `payouts` | `MoneyBills2` | `payoutsLimit` |
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/billing/plan-usage.tsx:132-179](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/billing/plan-usage.tsx#L132-L179)
> [!NOTE]
> The payouts resource tab is reserved during initial loading states to prevent layout shifts while asynchronous SWR hooks resolve workspace properties.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/billing/plan-usage.tsx:157-167](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/billing/plan-usage.tsx#L157-L167)
### Subscription Modals and Plan Management
The `SubscriptionMenu` component exposes administrative controls for enterprise and non-enterprise workspaces SubscriptionMenu. Non-enterprise workspaces render a popover menu containing actions to open the Stripe billing portal or cancel the active subscription.
```tsx
export default function SubscriptionMenu() {
const {
id: workspaceId,
role,
plan,
defaultProgramId,
billingCycleEndsAt,
subscriptionCanceledAt,
mutate,
} = useWorkspace();
const router = useRouter();
const permissionsError = clientAccessCheck({
action: "billing.write",
role,
}).error;
const [isOpen, setIsOpen] = useState(false);
const [clicked, setClicked] = useState(false);
const openBillingPortal = async () => {
setIsOpen(false);
setClicked(true);
return fetch(`/api/workspaces/${workspaceId}/billing/manage`, {
method: "POST",
})
.then(async (res) => {
if (res.ok) {
const { url } = await res.json();
router.push(url);
} else {
const { error } = await res.json();
toast.error(error.message);
}
})
.finally(() => {
setClicked(false);
});
};
```
Sources: [apps/web/ui/workspaces/subscription-menu.tsx:24-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/workspaces/subscription-menu.tsx#L24-L62)
When canceling a subscription, the client verifies whether the workspace would lose partner access by evaluating `wouldLosePartnerAccess`. If partner access is affected, selecting cancellation triggers a plan change confirmation modal before opening the cancellation dialog.
```tsx
// Check if canceling would lose partner access
const losesPartnerAccess =
plan &&
defaultProgramId &&
wouldLosePartnerAccess({ currentPlan: plan, newPlan: null });
const { setShowCancelSubscriptionModal, CancelSubscriptionModal } =
useCancelSubscriptionModal({
billingCycleEndsAt,
onConfirm: handleCancellation,
});
const { setShowPlanChangeConfirmationModal, PlanChangeConfirmationModal } =
usePlanChangeConfirmationModal({
newPlan: "free",
newPeriod: "monthly",
newTier: 1,
onConfirm: async () => {
setShowPlanChangeConfirmationModal(false);
setShowCancelSubscriptionModal(true);
},
});
const handleCancelSubscription = () => {
setIsOpen(false);
if (losesPartnerAccess) {
setShowPlanChangeConfirmationModal(true);
} else {
setShowCancelSubscriptionModal(true);
}
};
```
Sources: [apps/web/ui/workspaces/subscription-menu.tsx:97-127](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/workspaces/subscription-menu.tsx#L97-L127)
### Plain CRM Plan Synchronization
Customer support workflows integrate with Plain CRM via webhook callbacks that authenticate requests using the `X-Plain-Webhook-Secret` header POST.
```typescript
export async function POST(req: NextRequest) {
// authenticate webhook X-Plain-Webhook-Secret
const token = req.headers.get("X-Plain-Webhook-Secret");
if (token !== process.env.PLAIN_WEBHOOK_SECRET) {
return new Response("Unauthorized", { status: 401 });
}
```
Sources: [apps/web/app/api/callback/plain/workspace/route.ts:20-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/plain/workspace/route.ts#L20-L25)
Upon receiving a valid callback for a customer, the system resolves the associated user, verifies email blacklist status, upserts customer metadata, and queries the primary workspace ordered by usage limits POST.
```typescript
let { customer } = plainCallbackSchema.parse(await req.json());
const user = await prisma.user.findUnique({
where: customer.externalId
? { id: customer.externalId }
: { email: customer.email },
});
if (!user || !user.email) {
const isBannedUser = await isBlacklistedEmail(customer.email);
if (isBannedUser) {
await plain.addCustomerToCustomerGroups({
customerId: customer.id,
customerGroupIdentifiers: [
{
customerGroupKey: "banned_users",
},
],
});
}
return NextResponse.json({
cards: [
{
key: "workspace",
components: [plainEmptyContainer("No user found.")],
},
],
});
}
if (!customer.externalId) {
customer.externalId = user.id;
await upsertPlainCustomer({
id: user.id,
name: user.name,
email: user.email,
});
}
waitUntil(syncUserPlanToPlain(user));
const topWorkspace = await prisma.project.findFirst({
where: {
users: {
some: {
userId: customer.externalId,
},
},
},
include: {
_count: {
select: {
domains: true,
users: true,
},
},
},
orderBy: {
usageLimit: "desc",
},
take: 1,
});
```
Sources: [apps/web/app/api/callback/plain/workspace/route.ts:27-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/plain/workspace/route.ts#L27-L89)
The endpoint returns dynamic Plain CRM card components that format plan badges with specific colors corresponding to the workspace subscription tier.
| Plan Tier / Identifier | Plain Badge Color |
| :--- | :--- |
| `enterprise` | `RED` |
| `advanced` | `YELLOW` |
| `business*` (starts with) | `GREEN` |
| `pro` | `BLUE` |
| Other / Free | `GREY` |
Sources: [apps/web/app/api/callback/plain/workspace/route.ts:157-166](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/plain/workspace/route.ts#L157-L166)
## Related
- [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement)
---
## Technical docs: POST Delete partner account
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/deleteadminpartneraccount
## Request Body
Partner delete parameters
## Responses
## Try It
---
## Technical docs: GET Get fraud alerts
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminpartnerfraudalerts
## Parameters
## Responses
## Try It
---
## Technical docs: Commission Engine
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/lemonsqueezy/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/lemonsqueezy/import-commissions.ts)
- [apps/web/lib/partnerstack/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partnerstack/import-commissions.ts)
- [apps/web/app/ee/api/workflows/create-partner-commission/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts)
- [apps/web/lib/tapfiliate/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tapfiliate/import-commissions.ts)
- [apps/web/lib/tolt/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-commissions.ts)
- [apps/web/scripts/programs/backfill-reuse-commission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/backfill-reuse-commission.ts)
- [apps/web/lib/rewardful/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-commissions.ts)
- [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/process/route.ts)
- [apps/web/lib/firstpromoter/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts)
- [apps/web/scripts/customers/beehiiv/fix-case-a-complex.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/beehiiv/fix-case-a-complex.ts)
- [apps/web/app/ee/api/commissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/commissions/route.ts)
- [apps/web/lib/api/commissions/create-manual-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/create-manual-commissions.ts)
- [apps/web/lib/partner-referrals/create-referral-commission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-referral-commission.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/commissions/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/commissions/page.tsx)
- [apps/web/ui/activity-logs/commission-activity.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/activity-logs/commission-activity.tsx)
- [apps/web/lib/api/sales/calculate-sale-earnings.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/calculate-sale-earnings.ts)
- [apps/web/scripts/customers/framer/tally-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/framer/tally-commissions.ts)
- [apps/web/lib/api/commissions/get-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/get-commissions.ts)
- [apps/web/lib/partner-referrals/create-network-referral-commission.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts)
- [apps/web/scripts/customers/upheal/sync-stripe-invoices.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/upheal/sync-stripe-invoices.ts)
- [apps/web/lib/api/customers/reattribute-customer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts)
- [apps/web/scripts/programs/5-import-customer-sales.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/5-import-customer-sales.ts)
- [apps/web/app/ee/api/admin/commissions/get-commissions-timeseries.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts)
- [apps/web/lib/api/partners/sync-total-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/partners/sync-total-commissions.ts)
- [apps/web/scripts/programs/update-commissions-canceled.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/update-commissions-canceled.ts)
- [apps/web/lib/api/commissions/track-commission-update-activity-log.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts)
- [apps/web/scripts/programs/create-zero-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/create-zero-commissions.ts)
- [apps/web/prisma/schema/commission.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma)
- [apps/web/app/ee/api/cron/commissions/referrals/backfill/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts)
- [apps/web/app/ee/api/cron/commissions/referrals/create/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/commissions/referrals/create/route.ts)
## Overview
The Commission Engine powers Dub's [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs) by tracking, calculating, and managing financial rewards across affiliate click, lead, sale, referral, and custom commission types. It processes asynchronous event pipelines, evaluates complex [reward rules](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/reward-rules), handles multi-currency conversions, and executes historical batch migrations from platforms such as Lemon Squeezy, PartnerStack, Tolt, Tapfiliate, FirstPromoter, and Rewardful. Sources: [apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts:182-218](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L182-L218)
Sources: [apps/web/prisma/schema/commission.prisma:37-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L37-L62)
Sources: [apps/web/lib/lemonsqueezy/import-commissions.ts:336-375](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/lemonsqueezy/import-commissions.ts#L336-L375)
## Data model and commission states
### Commission Enumerations and Status Lifecycle
The commission engine relies on a relational Prisma schema centered around the `Commission` model, backed by enums for lifecycle status (`CommissionStatus`), event classification (`CommissionType`), and data ingestion origin (`CommissionSource`). Sources: [apps/web/prisma/schema/commission.prisma:1-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L1-L35)
```
enum CommissionStatus {
pending
processed
paid
refunded
duplicate
fraud
canceled
hold
}
enum CommissionType {
click
lead
sale
referral
custom
}
enum CommissionSource {
api // track lead/sale API
user // manual creates with userId (manual commissions, bounty submission approvals, submitted leads/sales)
stripe
shopify
hubspot
appsflyer
singular
rewardful
partnerstack
firstpromoter
tolt
tapfiliate
lemonsqueezy
affiliatewp
}
```
Sources: [apps/web/prisma/schema/commission.prisma:1-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L1-L35)
The `Commission` model records financial metrics, idempotency identifiers, external references, and relations to programs, partners, payouts, invoices, and customers. Sources: [apps/web/prisma/schema/commission.prisma:37-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L37-L87)
```
model Commission {
id String @id
programId String
partnerId String
rewardId String?
linkId String?
payoutId String?
invoiceId String? // only for sales (idempotency key, each sale event is associated with a unique invoice)
customerId String? // only for leads and sales
eventId String? @unique // only for leads and sales
description String? @db.Text
type CommissionType
amount Int // only for sales (amount of the sale event)
quantity Int // only for clicks/leads (quantity of the event)
earnings Int @default(0) // amount earned by the partner
currency String @default("usd")
status CommissionStatus @default(pending)
userId String? // user who created the manual commission
source CommissionSource?
sourceCommissionId String?
sourcePartnerId String?
bountySubmissionId String?
metadata Json? @db.Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
program Program @relation(fields: [programId], references: [id])
partner Partner @relation(fields: [partnerId], references: [id])
programEnrollment ProgramEnrollment @relation(fields: [programId, partnerId], references: [programId, partnerId])
payout Payout? @relation(fields: [payoutId], references: [id])
link Link? @relation(fields: [linkId], references: [id])
customer Customer? @relation(fields: [customerId], references: [id])
reward Reward? @relation(fields: [rewardId], references: [id])
bountySubmission BountySubmission? @relation(fields: [bountySubmissionId], references: [id], onDelete: SetNull)
user User? @relation(fields: [userId], references: [id])
@@unique([invoiceId, programId])
@@index([earnings, programId, partnerId, status]) // old index
@@index([programId, partnerId]) // for programEnrollment relation (used in cron/payouts/aggregate-due-commissions)
@@index([programId, status, createdAt, amount, earnings]) // for program/commissions (scoped by programId)
@@index([createdAt, status, programId, earnings]) // for admin/commissions
@@index([partnerId, customerId, type, createdAt]) // for finding the firstCommission in create-partner-commission workflow
@@index(payoutId)
@@index(customerId)
@@index(linkId)
@@index(type)
@@index(status)
@@index(rewardId)
@@index(userId)
@@index(bountySubmissionId)
}
```
Sources: [apps/web/prisma/schema/commission.prisma:37-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L37-L87)
Commissions move through distinct lifecycle states managed by background processing crons and administrative scripts. The table below outlines the available enums for status, type, and source. Sources: [apps/web/prisma/schema/commission.prisma:1-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L1-L35)
| Enum Category | Allowed Values | Sources |
| --- | --- | --- |
| `CommissionStatus` | `pending`, `processed`, `paid`, `refunded`, `duplicate`, `fraud`, `canceled`, `hold` | [apps/web/prisma/schema/commission.prisma:1-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L1-L10) |
| `CommissionType` | `click`, `lead`, `sale`, `referral`, `custom` | [apps/web/prisma/schema/commission.prisma:12-18](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L12-L18) |
| `CommissionSource` | `api`, `user`, `stripe`, `shopify`, `hubspot`, `appsflyer`, `singular`, `rewardful`, `partnerstack`, `firstpromoter`, `tolt`, `tapfiliate`, `lemonsqueezy`, `affiliatewp` | [apps/web/prisma/schema/commission.prisma:20-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/commission.prisma#L20-L35) |
> [!WARNING]
> When updating commission statuses from `pending` or `processed` to `canceled` via maintenance scripts, associated payout references (`payoutId`) must be explicitly nulled and payout balances must be retallied using `retallyPayoutsAmount` to prevent accounting discrepancies. Sources: [apps/web/scripts/programs/update-commissions-canceled.ts:42-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/update-commissions-canceled.ts#L42-L58)
## Partner commission creation workflow
### Execution Pipeline and Earnings Calculation
The step-based commission creation workflow (`stepCreateCommission`) evaluates incoming events through a structured validation and calculation pipeline. Click and referral events are explicitly skipped as they are not processed by this workflow. For lead and sale events, the engine validates that the partner's program enrollment has an eligible status before proceeding. Sources: [apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts:212-230](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L212-L230)
```typescript
// Skip invalid reward events (should never happen, but just in case)
if (event === "click" || event === "referral") {
return logAndReturn({
commission: null,
outputLog: `"${event}" commissions are not created via this workflow. Skipping commission creation...`,
});
}
// for lead / sale rewards, we need to check if the partner is eligible for commissions
if (
["lead", "sale"].includes(event) &&
!COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES.includes(programEnrollment.status)
) {
return logAndReturn({
commission: null,
outputLog: `Partner ${partnerId} is not eligible for commissions (status: ${programEnrollment.status}) in program ${programId}, skipping ${event} commission creation...`,
});
}
```
Sources: [apps/web/app/ee/api/workflows/create-partner-commission/route.ts:212-230](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L212-L230)
When a customer identifier is present, the pipeline queries historical records to locate the initial commission for that partner-customer pair. This establishes the subscription start date and duration months, classifying sales as either `new` or `recurring`. The engine then determines applicable partner rewards and calculates sale earnings based on reward type and sale quantity or amount. Sources: [apps/web/lib/api/sales/calculate-sale-earnings.ts:8-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/calculate-sale-earnings.ts#L8-L28)
```typescript
export const calculateSaleEarnings = ({
reward,
sale,
}: {
reward: Pick;
sale: Pick;
}) => {
if (!reward) {
return 0;
}
const amount = getRewardAmount(reward);
if (reward.type === "flat") {
return sale.quantity * amount;
} else if (reward.type === "percentage") {
return Math.round((sale.amount * amount) / 100);
}
return 0;
};
```
Sources: [apps/web/lib/api/sales/calculate-sale-earnings.ts:8-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/sales/calculate-sale-earnings.ts#L8-L28)
> [!CAUTION]
> If a prior commission for the customer is marked as `fraud` or `canceled`, the execution pipeline terminates immediately and skips commission creation entirely, preventing fraudulent or revoked transactions from generating new payouts. Sources: [apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts:312-319](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L312-L319)
### Deduplication and Spend Limit Windows
The workflow enforces strict deduplication and duration boundaries for lead and sale events. If a lead reward has already been issued for a customer, duplicate lead commissions are dropped. For recurring sales, the pipeline evaluates `maxDuration` constraints against subscription duration months to ensure commissions are only created within allowed windows. Sources: [apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts:321-384](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L321-L384)
```typescript
// for lead events, we need to check if the partner has already been issued a lead reward for this customer
if (event === "lead") {
return logAndReturn({
commission: null,
outputLog: `Partner ${partnerId} has already been issued a lead reward for this customer ${customerId}, skipping commission creation...`,
});
// for sale rewards, we need to check if partner's reward was updated and different from the first commission's reward
// we need to make sure it wasn't changed from one-time to recurring so we don't create a new commission
} else {
if (
firstCommission.rewardId &&
firstCommission.rewardId !== reward.id
) {
const originalReward = await prisma.reward.findUnique({
where: {
id: firstCommission.rewardId,
},
select: {
id: true,
maxDuration: true,
modifiers: true,
},
});
const originalMaxDuration = originalReward
? getRewardMaxDurationForContext({
reward: originalReward,
context,
})
: null;
if (
typeof originalMaxDuration === "number" &&
originalMaxDuration === 0
) {
return logAndReturn({
commission: null,
outputLog: `Partner ${partnerId} is only eligible for first-sale commissions based on the original reward ${originalReward?.id}, skipping commission creation...`,
});
}
}
// for sale rewards with a max duration, we need to check if the first commission is within the max duration
// if it's beyond the max duration, we should not create a new commission
if (typeof reward?.maxDuration === "number") {
// One-time sale reward (maxDuration === 0)
if (reward.maxDuration === 0) {
return logAndReturn({
commission: null,
outputLog: `Partner ${partnerId} is only eligible for first-sale commissions, skipping commission creation...`,
});
}
// Recurring sale reward (maxDuration > 0)
else {
const subscriptionDurationMonths = differenceInMonths(
createdAt ?? new Date(), // account for custom commission creation date
firstCommission.createdAt,
);
if (subscriptionDurationMonths >= reward.maxDuration) {
return logAndReturn({
commission: null,
```
Sources: [apps/web/app/ee/api/workflows/create-partner-commission/route.ts:321-384](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L321-L384)
> [!NOTE]
> Custom commission types bypass standard reward evaluation entirely, directly assigning the input amount as earnings while zeroing out the base amount. Sources: [apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts:239-242](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts#L239-L242)
## Manual and batch commission ingestion
Workspace users with owner or member roles on business, advanced, or enterprise plans can create manual commissions through the [REST API](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api) endpoint at `/api/commissions`. The endpoint parses incoming payloads using Zod validation schemas and executes manual creation handlers. When the request specifies a custom commission with a negative amount, the response designates the transaction as a clawback queued for the partner with a 202 status code. Sources: [apps/web/app/(ee)/api/commissions/route.ts:74-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/commissions/route.ts#L74-L105)
```typescript
export const POST = withWorkspace(
async ({ workspace, session, req }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
const body = createManualCommissionBodySchema.parse(
await parseRequestBody(req),
);
console.time("createManualCommissions");
await createManualCommissions({
...body,
workspace,
programId,
user: session.user,
});
console.timeEnd("createManualCommissions");
const isClawback = body.type === "custom" && body.amount < 0;
const response = createCommissionResponseSchema.parse({
success: true,
message: isClawback
? "A clawback has been queued for the partner!"
: "Your commissions are being created and will appear shortly.",
});
return NextResponse.json(response, {
status: 202,
});
},
```
Sources: [apps/web/app/ee/api/commissions/route.ts:74-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/commissions/route.ts#L74-L105)
The ingestion logic handles custom, lead, and sale event types. For custom commissions, it queues partner commission creation directly with user source attribution and aggregate trigger flags. For sale events, if `importStripeInvoices` is enabled, the handler validates that the workspace maintains an active Stripe Connect integration and that the target customer has an associated Stripe Customer ID. It also performs invoice binding checks to verify whether a commission for the given invoice identifier already exists within the program. Sources: [apps/web/lib/api/commissions/create-manual-commissions.ts:123-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/create-manual-commissions.ts#L123-L164)
```typescript
if (type === "sale") {
const { importStripeInvoices, sale } = args;
if (importStripeInvoices) {
if (!workspace.stripeConnectId) {
throw new DubApiError({
code: "bad_request",
message: `Your workspace isn't connected to Stripe yet. Please install the Stripe integration to continue: https://app.dub.co/${workspace.slug}/settings/integrations/stripe`,
});
}
if (targetCustomer && !targetCustomer.stripeCustomerId) {
throw new DubApiError({
code: "bad_request",
message: `Customer ${targetCustomer.id} does not have a Stripe Customer ID configured. Please update the customer record at https://app.dub.co/${workspace.slug}/program/customers/${targetCustomer.id}`,
});
}
}
const invoiceId = sale?.invoiceId ?? args.invoiceId;
if (invoiceId) {
const commission = await prisma.commission.findUnique({
where: {
invoiceId_programId: {
invoiceId,
programId,
},
},
select: {
id: true,
},
});
if (commission) {
throw new DubApiError({
code: "conflict",
message: `There is already a commission for the invoice ${invoiceId}.`,
});
}
}
}
```
Sources: [apps/web/lib/api/commissions/create-manual-commissions.ts:123-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/create-manual-commissions.ts#L123-L164)
> [!WARNING]
> Attempting to ingest a manual sale commission with an `invoiceId` that already exists for the program throws a conflict API error (`409`), preventing duplicate payouts for the same invoice. Sources: [apps/web/lib/api/commissions/create-manual-commissions.ts:144-163](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/create-manual-commissions.ts#L144-L163)
Batch ingestion scripts can also synchronize paid invoices directly from Stripe for enrolled customers. The synchronization script queries paid invoices, filters out zero-amount invoices, and checks for existing commission records by matching either the `invoiceId` or checking if the amount matches within a one-hour timestamp window of the invoice creation time. Sources: [apps/web/scripts/customers/upheal/sync-stripe-invoices.ts:69-84](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/upheal/sync-stripe-invoices.ts#L69-L84)
```typescript
const invoicesToProcess = invoices.data.filter((invoice) => {
// skip $0 invoices
if (invoice.amount_paid === 0) {
return false;
}
const existingCommission = existingCommissions.find(
(commission) =>
commission.invoiceId === invoice.id ||
(commission.amount === invoice.amount_paid &&
new Date(commission.createdAt).getTime() >=
new Date(invoice.created * 1000).getTime() - 60 * 60 * 1000 &&
new Date(commission.createdAt).getTime() <=
new Date(invoice.created * 1000).getTime() + 60 * 60 * 1000),
);
return !existingCommission;
});
```
Sources: [apps/web/scripts/customers/upheal/sync-stripe-invoices.ts:69-84](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/upheal/sync-stripe-invoices.ts#L69-L84)
> [!TIP]
> Stripe invoice synchronization scripts match existing commissions by checking invoice IDs or by verifying amount equality within a 60-minute window of the Stripe invoice creation timestamp to prevent duplicate batch creations. Sources: [apps/web/scripts/customers/upheal/sync-stripe-invoices.ts:74-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/upheal/sync-stripe-invoices.ts#L74-L82)
## Partner and network referral commissions
### Scheduled Cron Pipelines and Backfill Mechanics
Referral commissions evaluate multi-tier partner relationships and platform network payouts through automated cron jobs. The backfill endpoint at `/api/cron/commissions/referrals/backfill` inspects program application events to locate a referring partner (`referredByPartnerId`) and evaluates the referrer's `referralReward` configuration triggers. Depending on the trigger configuration, the cron dispatches batch jobs to the creation handler. Sources: [apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts:75-130](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts#L75-L130)
| Trigger Type | Eligible Source Event | Enqueued Job Target | Sources |
| :--- | :--- | :--- | :--- |
| `commissionThreshold` / `partnerApproved` | Program application or partner threshold approval | `/api/cron/commissions/referrals/create` with `programId` and `partnerId` | [apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts:75-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts#L75-L91) |
| `saleRecorded` / `commissionEarned` | Existing sale commissions with `pending`, `processed`, or `paid` status | `/api/cron/commissions/referrals/create` chunked in batches of 50 with `sourceCommissionId` | [apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts:93-130](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/commissions/referrals/backfill/route.ts#L93-L130) |
The execution endpoint at `/api/cron/commissions/referrals/create` receives the payload and delegates execution to `createReferralCommission`. This function blocks self-referrals by checking whether the target `partnerId` matches the `referredByPartnerId`. Sources: [apps/web/lib/partner-referrals/create-referral-commission.ts:30-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-referral-commission.ts#L30-L35)
```typescript
if (partnerId && referredByPartnerId && partnerId === referredByPartnerId) {
console.log(
`Skipping referral commission creation for self-referral (partner ${partnerId}).`,
);
return null;
}
```
Sources: [apps/web/lib/partner-referrals/create-referral-commission.ts:30-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-referral-commission.ts#L30-L35)
> [!WARNING]
> If a partner's ID matches their `referredByPartnerId`, the referral commission pipeline halts immediately and skips creation to prevent circular self-referral payouts. Sources: [apps/web/lib/partner-referrals/create-referral-commission.ts:30-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-referral-commission.ts#L30-L35)
### Network Program Payout Fees and Duration Limits
Network referral commissions governed by `createNetworkReferralCommission` calculate earnings based on a partner's payout event within the Dub network workspace (`NETWORK_WORKSPACE_ID`). The function validates that the payout does not originate from internal platform programs (`NETWORK_PROGRAM_ID`, `ACME_PROGRAM_ID`, or `DEMO_PROGRAM_ID`) and estimates a 3% average payout fee (`payoutFeeEarned`) from the total payout amount. Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:44-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L44-L55)
```typescript
if (
[NETWORK_PROGRAM_ID, ACME_PROGRAM_ID, DEMO_PROGRAM_ID].includes(
payout.programId,
)
) {
console.error(
`Payout ${payout.id} is from Network, Acme, or Demo program, skipping...`,
);
return null;
}
const payoutFeeEarned = Math.floor(payout.amount * 0.03); // assumes 3% average payout fee for all payouts
```
Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:44-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L44-L55)
The pipeline checks if the referring partner is actively enrolled in the network program and inspects prior commission history against maximum duration bounds. Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:199-211](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L199-L211)
```typescript
if (firstCommission) {
const durationMonths = differenceInMonths(
new Date(),
firstCommission.createdAt,
);
if (durationMonths >= NETWORK_REFERRAL_REWARD.maxDuration) {
console.log(
`Referrer partner ${partner.referredByPartnerId} has reached max duration for network bonus.`,
);
return null;
}
}
```
Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:199-211](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L199-L211)
> [!NOTE]
> Network referral bonuses enforce a strict maximum duration (`NETWORK_REFERRAL_REWARD.maxDuration`) calculated from the creation date of the very first network commission (`firstCommission.createdAt`). Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:199-211](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L199-L211)
When database unique constraint violations (`P2002`) occur during commission insertion due to race conditions on the `invoiceId`, the handler catches the error, logs the skip event, and prevents duplicate commission creation. Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:247-252](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L247-L252)
```typescript
if (error.code === "P2002") {
console.log(
`Referral commission already exists for invoiceId ${commissionData.invoiceId}, skipping creation.`,
);
return null;
}
```
Sources: [apps/web/lib/partner-referrals/create-network-referral-commission.ts:247-252](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partner-referrals/create-network-referral-commission.ts#L247-L252)
## Legacy platform commission migration
### Platform Importers and Currency Conversion
Migrating historical affiliate programs into Dub requires dedicated batch importers that process external payloads from Lemon Squeezy, PartnerStack, Tolt, Tapfiliate, and FirstPromoter. Each platform importer normalizes source-specific records into unified Prisma commission schemas while resolving associated partner links, customer identifiers, and lead events. Sources: [apps/web/lib/lemonsqueezy/import-commissions.ts:263-281](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/lemonsqueezy/import-commissions.ts#L263-L281)
Importers retrieve historical conversions, invoices, or commissions in paginated chunks and evaluate currency formats. Non-USD values are converted into standard amounts using real-time foreign exchange rates via `convertCurrencyWithFxRates`. Lemon Squeezy imports map affiliate invoices to `saleEvents`, falling back to `firstOrderItemPrice` when initial order subtotals are zero. PartnerStack, Tolt, Tapfiliate, and FirstPromoter handle manual line items or transactional sales by querying matching customer records and verifying deduplication windows. Sources: [apps/web/lib/partnerstack/import-commissions.ts:177-185](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partnerstack/import-commissions.ts#L177-L185)
| Platform Importer Source | Entity Identifier | Core Deduplication Key / Fallback | Currency Handling & Conversion | Sources |
| :--- | :--- | :--- | :--- | :--- |
| Lemon Squeezy | `invoiceId` (`ls_invoice_${id}`) | `invoiceId_programId` unique index | Resolved via `resolveAmountUsd` or fx rates | [apps/web/lib/lemonsqueezy/import-commissions.ts:265-274](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/lemonsqueezy/import-commissions.ts#L265-L274) |
| PartnerStack | `commission.key` | `invoiceId_programId` or $\pm 1$ hour window check | `convertCurrencyWithFxRates` if not USD | [apps/web/lib/partnerstack/import-commissions.ts:156-166](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partnerstack/import-commissions.ts#L156-L166) |
| Tapfiliate | `commission.id` | `invoiceId_programId` using conversion ID | `convertCurrencyWithFxRates` for sub-amounts and earnings | [apps/web/lib/tapfiliate/import-commissions.ts:167-176](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tapfiliate/import-commissions.ts#L167-L176) |
| Tolt | `commission.id` | `transaction_id` or $\pm 1$ hour window check | Converted via `convertCurrencyWithFxRates` against program currency | [apps/web/lib/tolt/import-commissions.ts:178-199](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-commissions.ts#L178-L199) |
| Rewardful | `commission.id` | `sale.id` or Stripe customer ID $\pm 1$ hour window check | Converted via `convertCurrencyWithFxRates` for cents and earnings | [apps/web/lib/rewardful/import-commissions.ts:163-197](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-commissions.ts#L163-L197) |
| FirstPromoter | `${commission.id}` | `${commission.id}` or customer $\pm 1$ hour window check | `convertCurrencyWithFxRates` for original sale amount | [apps/web/lib/firstpromoter/import-commissions.ts:178-209](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts#L178-L209) |
> [!WARNING]
> Platforms like PartnerStack, Tolt, and Rewardful that omit native Stripe invoice identifiers during migration rely on a fallback window query checking for matching customer IDs and amounts within a $\pm 1$ hour timeframe of `chargedAt` to prevent duplicate imports during transition periods. Sources: [apps/web/lib/partnerstack/import-commissions.ts:290-306](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partnerstack/import-commissions.ts#L290-L306)
Sources: [apps/web/lib/tolt/import-commissions.ts:251-264](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-commissions.ts#L251-L264)
Sources: [apps/web/lib/rewardful/import-commissions.ts:237-252](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-commissions.ts#L237-L252)
## Customer reattribution and clawback reconciliation
### Transfer execution and adjustments
When a customer is reattributed between partners, the engine manages clawback adjustments and replacement commission generation. If paid commissions exist on the old customer record, their `eventId` and `invoiceId` fields are cleared to prevent constraint violations, and a negative adjustment commission with the type `custom`, description `tracking_error`, and earnings set to negative paid earnings is queued for the old partner using a unique execution key. Sources: [apps/web/lib/api/customers/reattribute-customer.ts:729-771](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L729-L771)
```typescript
if (plan.shouldClearIdentifiers && plan.paidCommissionIds.length > 0) {
await prisma.commission.updateMany({
where: {
id: { in: plan.paidCommissionIds },
},
data: {
eventId: null,
invoiceId: null,
},
});
}
await runOnce({
key: `reattribute-customer:${oldCustomerId}:clawback`,
fn: async () => {
const existingClawback = await prisma.commission.findFirst({
where: {
customerId: oldCustomerId,
partnerId: oldPartnerId,
programId,
type: "custom",
description: "tracking_error",
earnings: { lt: 0 },
},
select: { id: true },
});
if (existingClawback) {
return;
}
await queuePartnerCommissionCreation({
event: "custom",
partnerId: oldPartnerId,
programId,
customerId: oldCustomerId,
amount: -plan.paidEarnings,
quantity: 1,
description: "tracking_error",
skipWorkflow: true,
});
},
});
```
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:729-771](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L729-L771)
### Replacement commission routing
New lead and sale events are queried for the incoming customer and filtered against existing commissions to prevent duplicates. Lead reattribution evaluates whether the old customer generated a paid lead while the new partner has no existing lead. Sale events match paid invoice identifiers or supplement invoiceless sales up to the prior paid count. Sources: [apps/web/lib/api/customers/reattribute-customer.ts:773-821](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L773-L821)
```typescript
const [newEvents, existingNewCommissions] = await Promise.all([
getCustomerReattributeEvents(newCustomerId),
prisma.commission.findMany({
where: {
customerId: newCustomerId,
partnerId: newPartnerId,
type: { in: ["lead", "sale"] },
},
select: {
type: true,
invoiceId: true,
},
}),
]);
const hasExistingLead = existingNewCommissions.some(
(commission) => commission.type === "lead",
);
const leadEvent =
plan.hasPaidLead && !hasExistingLead
? newEvents.find((event) => event.event === "lead") ?? null
: null;
const paidInvoiceIds = new Set(plan.paidInvoiceIds);
const existingInvoiceIds = new Set(
existingNewCommissions
.map((commission) => commission.invoiceId)
.filter((invoiceId): invoiceId is string => Boolean(invoiceId)),
);
const existingInvoicelessCount = existingNewCommissions.filter(
(commission) => commission.type === "sale" && !commission.invoiceId,
).length;
const saleEvents = [
...newEvents.filter(
(event) =>
event.event === "sale" &&
event.invoice_id &&
paidInvoiceIds.has(event.invoice_id) &&
!existingInvoiceIds.has(event.invoice_id),
),
...newEvents
.filter((event) => event.event === "sale" && !event.invoice_id)
.slice(
0,
Math.max(0, plan.paidInvoicelessCount - existingInvoicelessCount),
),
];
```
Sources: [apps/web/lib/api/customers/reattribute-customer.ts:773-821](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L773-L821)
> [!CAUTION]
> Customer reattribution requires running synchronization across both old and old/new partner totals via `syncTotalCommissions` immediately after queueing replacement events to prevent payout imbalances. Sources: [apps/web/lib/api/customers/reattribute-customer.ts:864-874](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts#L864-L874)
## Status tracking and balance aggregation
### Activity log auditing
Dub tracks commission updates and status transitions by parsing activity change sets and recording structured snapshots. The `trackCommissionStatusUpdate` utility captures bulk operations such as aggregation, bans, and payouts by mapping commission records and generating activity logs through `trackCommissionActivityLog` with `amount`, `earnings`, and `status` fields. Sources: [apps/web/lib/api/commissions/track-commission-update-activity-log.ts:79-99](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts#L79-L99)
```typescript
export async function trackCommissionStatusUpdate({
commissions,
newStatus,
...baseInput
}: {
commissions: Pick[];
newStatus: CommissionStatus;
} & Pick) {
if (commissions.length === 0) {
return;
}
return trackCommissionActivityLog({
...baseInput,
old: commissions,
new: commissions.map((commission) => ({
...commission,
status: newStatus,
})),
});
}
```
Sources: [apps/web/lib/api/commissions/track-commission-update-activity-log.ts:79-99](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts#L79-L99)
> [!NOTE]
> When processing payouts spanning multiple programs, `trackCommissionStatusUpdatesByProgram` groups commissions by program ID and resolves the correct workspace context before invoking individual status updates. Sources: [apps/web/lib/api/commissions/track-commission-update-activity-log.ts:103-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/track-commission-update-activity-log.ts#L103-L142)
### Redis stream events and synchronization
Partner commission totals are synchronized using Upstash Redis streams via `syncTotalCommissions`. When an event is published, the system attempts to dispatch through the Redis stream infrastructure. If a failure occurs, it falls back to a direct database transaction that aggregates earnings across non-zero, active commission states (`pending`, `processed`, and `paid`) to update the corresponding `ProgramEnrollment` record. Sources: [apps/web/lib/api/partners/sync-total-commissions.ts:37-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/partners/sync-total-commissions.ts#L37-L59)
```typescript
export const syncTotalCommissions = async ({
partnerId,
programId,
}: {
partnerId: string;
programId: string;
}) => {
try {
return await publishPartnerActivityEvent({
programId,
partnerId,
eventType: "commission",
timestamp: new Date().toISOString(),
});
} catch (error) {
console.error(
`[syncTotalCommissionsError]: Failed to sync total commissions for partner ${partnerId} in program ${programId}, falling back to direct database update...`,
error,
);
return await aggregateAndUpdateTotalCommissions({ partnerId, programId });
}
};
```
Sources: [apps/web/lib/api/partners/sync-total-commissions.ts:37-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/partners/sync-total-commissions.ts#L37-L59)
> [!CAUTION]
> Direct database aggregation inside `aggregateAndUpdateTotalCommissions` executes within a Prisma transaction (`tx`) to prevent race conditions when concurrent payouts or status updates modify enrollment totals. Sources: [apps/web/lib/api/partners/sync-total-commissions.ts:11-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/partners/sync-total-commissions.ts#L11-L34)
## Commission querying and analytics reporting
### Filtering and pagination parameters
The commission retrieval engine processes requests through `getCommissions` by evaluating filters across identifiers, metadata queries, and pagination constraints. When an `invoiceId` is supplied, the query searches uniquely within the specified program and metadata parameters. Otherwise, pagination queries use cursor-based navigation validated against `startingAfter` or `endingBefore` parameters. Sources: [apps/web/lib/api/commissions/get-commissions.ts:35-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/get-commissions.ts#L35-L89)
```typescript
export async function getCommissions(filters: CommissionsFilters) {
const {
invoiceId,
programId,
partnerId,
status,
type,
customerId,
payoutId,
bountySubmissionId,
groupId,
partnerTagId,
fraudEventGroupId,
start,
end,
interval,
timezone,
startingAfter,
endingBefore,
query,
} = filters;
// Metadata filter
const parsedMetadataQuery = parseCommissionMetadataQuery(query);
const metadataWhere = buildCommissionMetadataWhere(parsedMetadataQuery);
// InvoiceId is unique within a program
if (invoiceId) {
return await prisma.commission.findMany({
where: {
invoiceId,
programId,
...metadataWhere,
},
include: {
...commissionIncludes,
},
});
}
const paginationQuery = buildPaginationQuery(filters);
// Validate the provided cursor ID
const cursorId = startingAfter || endingBefore;
if (cursorId) {
const commission = await prisma.commission.findUnique({
where: {
id: cursorId,
},
select: {
id: true,
programId: true,
},
});
```
Sources: [apps/web/lib/api/commissions/get-commissions.ts:35-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/get-commissions.ts#L35-L89)
> [!CAUTION]
> If a cursor ID is provided in commission queries, the engine performs a validation lookup to ensure the record exists and belongs to the active `programId`, throwing a `unprocessable_entity` API error if the check fails. Sources: [apps/web/lib/api/commissions/get-commissions.ts:80-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/get-commissions.ts#L80-L97)
### Time-series aggregation endpoints
Time-series metrics are compiled via raw SQL queries in `getCommissionsTimeseries` using granularity mappings from `sqlGranularityMap`. The pipeline aggregates earnings grouped by time intervals, excluding duplicate, fraudulent, or canceled commission states while filtering out internal programs (`ACME_PROGRAM_ID` and `DEMO_PROGRAM_ID`) when no specific program is requested. Sources: [apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts:13-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts#L13-L41)
```typescript
export async function getCommissionsTimeseries({
programId,
startDate,
endDate,
granularity,
timezone,
}: {
programId?: string;
startDate: Date;
endDate: Date;
granularity: string;
timezone: string;
}) {
const { dateFormat, dateIncrement, startFunction, formatString } =
sqlGranularityMap[granularity];
const commissions = await prisma.$queryRaw`
SELECT
DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
SUM(earnings) AS commissions
FROM Commission
WHERE
createdAt >= ${startDate}
AND createdAt < ${endDate}
AND status IN ("pending", "processed", "paid")
AND ${programId ? Prisma.sql`programId = ${programId}` : Prisma.sql`programId NOT IN (${ACME_PROGRAM_ID}, ${DEMO_PROGRAM_ID})`}
GROUP BY start
ORDER BY start ASC;`;
```
Sources: [apps/web/app/ee/api/admin/commissions/get-commissions-timeseries.ts:13-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts#L13-L41)
## Related
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
- [Reward Rules](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/reward-rules)
- [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement)
---
## Technical docs: Payout Settlement
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/partners/create-stablecoin-payout.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stablecoin-payout.ts)
- [apps/web/app/ee/api/cron/payouts/process/process-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts)
- [apps/web/app/ee/api/cron/payouts/balance-available/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/balance-available/route.ts)
- [apps/web/app/ee/api/cron/payouts/send-stripe-payout/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts)
- [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts)
- [apps/web/lib/partners/create-stripe-transfer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts)
- [apps/web/lib/payouts/get-partner-payout-methods.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/payouts/get-partner-payout-methods.ts)
- [apps/web/app/ee/api/cron/payouts/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/route.ts)
- [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/process/route.ts)
- [apps/web/lib/actions/partners/confirm-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts)
- [apps/web/lib/tremendous/send-tremendous-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tremendous/send-tremendous-payouts.ts)
- [apps/web/lib/payouts/recompute-partner-payout-state.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/payouts/recompute-partner-payout-state.ts)
- [apps/web/app/ee/api/cron/payouts/send-tremendous-payout/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/send-tremendous-payout/route.ts)
- [apps/web/app/ee/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts)
- [apps/web/app/ee/api/cron/trigger-withdrawal/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/trigger-withdrawal/route.ts)
- [apps/web/app/ee/api/cron/payouts/force-withdrawals/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/force-withdrawals/route.ts)
- [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts)
- [apps/web/lib/actions/partners/force-withdrawal.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/force-withdrawal.ts)
- [apps/web/ui/partners/confirm-payouts-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/confirm-payouts-sheet.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/payouts/payout-table.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/payouts/payout-table.tsx)
- [apps/web/scripts/customers/framer/split-bounty-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/framer/split-bounty-payouts.ts)
- [apps/web/app/ee/partners.dub.co/onboarding/onboarding/payouts/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx)
- [apps/web/app/ee/api/cron/payouts/process/split-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts)
- [apps/web/app/ee/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts)
- [apps/web/ui/partners/payouts/use-payout-connect-flow.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/payouts/use-payout-connect-flow.tsx)
- [apps/web/ui/partners/payouts/payout-method-config.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/payouts/payout-method-config.ts)
- [apps/web/app/ee/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts)
- [apps/web/app/ee/api/admin/payouts/stablecoin/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/payouts/stablecoin/route.ts)
- [apps/web/app/ee/api/cron/payouts/charge-succeeded/utils.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts)
- [apps/web/lib/api/payouts/get-eligible-payouts.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/payouts/get-eligible-payouts.ts)
## Overview
Payout settlement orchestrates the end-to-end lifecycle of partner compensation, transitioning accumulated referral commissions from pending ledger entries into disbursed funds across multiple financial rails. The system automates commission aggregation against configurable holding periods, splits large payout periods when cutoffs are applied, validates program operator funding, and dispatches multi-rail transfers through Stripe Connect, stablecoins, PayPal, and Tremendous rewards. By handling asynchronous settlement timings, currency conversions, balance availability triggers, and automated force-withdrawals for inactive accounts, the payout engine maintains financial reconciliation across complex partner networks.
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts:12-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts#L12-L14), [apps/web/app/ee/api/cron/payouts/process/split-payouts.ts:61-108](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts#L61-L108), [apps/web/lib/actions/partners/confirm-payouts.ts:189-214](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L189-L214), [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:67-119](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L67-L119), [apps/web/lib/partners/create-stripe-transfer.ts:203-222](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts#L203-L222), [apps/web/lib/partners/create-stablecoin-payout.ts:180-229](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stablecoin-payout.ts#L180-L229), [apps/web/app/ee/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts:58-74](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts#L58-L74), [apps/web/lib/tremendous/send-tremendous-payouts.ts:158-180](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tremendous/send-tremendous-payouts.ts#L158-L180), [apps/web/app/ee/api/cron/payouts/balance-available/route.ts:134-145](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/balance-available/route.ts#L134-L145), [apps/web/app/ee/api/cron/payouts/force-withdrawals/route.ts:34-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/force-withdrawals/route.ts#L34-L44)
## Commission Aggregation and Eligibility
### Scheduled Cron Workflow
The commission aggregation pipeline runs as a scheduled cron job executing once every hour (`0 * * * *`). The root endpoint (`GET /api/cron/payouts/aggregate-due-commissions`) queries all programs containing pending commissions, chunks the program IDs into batches of 50, and enqueues jobs via QStash with a 10-second incremental delay between chunks. Each job is configured with a unique deduplication ID (`aggregate-due-commissions-${programId}`) and flow control parallelism set to 1.
```typescript
// This cron job aggregates due commissions (pending commissions that are past the partner group's holding period) into payouts.
// Runs once every hour (0 * * * *) + calls itself recursively to look through all pending commissions available.
// GET /api/cron/payouts/aggregate-due-commissions
export const GET = withCron(async () => {
const programsWithPendingCommissions = await prisma.program.findMany({
where: {
commissions: {
some: {
status: CommissionStatus.pending,
},
},
},
select: {
id: true,
},
});
const programIds = programsWithPendingCommissions.map((p) => p.id);
if (programIds.length === 0) {
return logAndRespond("No programs with due commissions found. Skipping...");
}
console.log(`Found ${programIds.length} programs with pending commissions.`);
// process 50 programs at a time to avoid overwhelming the database
const programIdChunks = chunk(programIds, 50);
for (const [index, programIdChunk] of programIdChunks.entries()) {
const delaySeconds = index * 10; // delay by 10s between program chunks
const jobs: PublishBatchRequest<{ programId: string }>[] =
programIdChunk.map((programId) => ({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/aggregate-due-commissions/process`,
body: {
programId,
},
deduplicationId: `aggregate-due-commissions-${programId}`,
label: "aggregate-due-commissions",
flowControl: {
key: `aggregate-due-commissions-${programId}`,
parallelism: 1,
},
delay: delaySeconds,
}));
```
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts:12-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts#L12-L56)
### Holding Periods and Processing
The process worker (`POST /api/cron/payouts/aggregate-due-commissions/process`) validates the incoming program ID and groups partner groups by their configured `holdingPeriodDays` in descending order of count. For each holding period tier, the worker fetches pending commissions in batches of 100 (`BATCH_SIZE`), filtering for those whose creation date satisfies the holding period threshold unless the commission type is manual or referral.
```typescript
const BATCH_SIZE = 100;
const inputSchema = z.object({
programId: z.string(),
});
// POST /api/cron/payouts/aggregate-due-commissions/process
export const POST = withCron(async ({ rawBody }) => {
const { programId } = inputSchema.parse(JSON.parse(rawBody));
const program = await prisma.program.findUnique({
where: {
id: programId,
},
select: {
id: true,
name: true,
workspaceId: true,
},
});
if (!program) {
return logAndRespond(`Program ${programId} not found. Skipping...`);
}
const partnerGroupsByHoldingPeriod = await prisma.partnerGroup.groupBy({
by: ["holdingPeriodDays"],
where: {
programId,
},
_count: {
id: true,
},
orderBy: {
_count: {
id: "desc",
},
},
});
for (const { holdingPeriodDays } of partnerGroupsByHoldingPeriod) {
const partnerGroups = await prisma.partnerGroup.findMany({
where: {
holdingPeriodDays,
programId,
},
select: {
id: true,
},
});
console.log(
`Found ${partnerGroups.length} partner groups with holding period days: ${holdingPeriodDays}`,
);
while (true) {
const dueCommissions = await prisma.commission.findMany({
where: {
programId,
status: CommissionStatus.pending,
programEnrollment: {
groupId: {
in: partnerGroups.map((p) => p.id),
},
},
// If holding period days is greater than 0:
// we only process commissions that were created before the holding period
// but custom commissions are always included
...(holdingPeriodDays > 0
? {
OR: [
{
type: {
// includes manual + referral commissions + clawbacks
in: ["custom", "referral"],
},
},
{
createdAt: {
lt: new Date(
```
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/process/route.ts:21-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/process/route.ts#L21-L122)
> [!NOTE]
> Custom and referral commission types (`custom`, `referral`) bypass standard holding period age checks when `holdingPeriodDays > 0`, allowing manual adjustments and specific referral bonuses to aggregate immediately alongside mature entries.
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/process/route.ts:89-106](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/process/route.ts#L89-L106)
### Eligibility Filtering
Eligible payouts are retrieved and filtered by evaluating minimum payout thresholds and external reward network limits. When a `cutoffPeriod` is supplied, associated commission earnings are recalculated and filtered against program minimums and Tremendous disbursement bounds.
| Parameter / Constant | Value / Source | Purpose |
| :--- | :--- | :--- |
| `BATCH_SIZE` | `100` | Number of due commissions processed per database query iteration |
| `maxDuration` | `600` | Maximum execution timeout in seconds for cron worker routes |
| `TREMENDOUS_MIN_PAYOUT_AMOUNT_CENTS` | External constant | Minimum payout limit when default payout method is Tremendous |
| `TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS` | External constant | Maximum payout limit when default payout method is Tremendous |
```typescript
export async function getEligiblePayouts({
program,
cutoffPeriod,
selectedPayoutIds,
excludedPayoutIds,
pageSize,
page = 1,
}: GetEligiblePayoutsProps) {
const cutoffPeriodValue = CUTOFF_PERIOD.find(
(c) => c.id === cutoffPeriod,
)?.value;
let payouts = await prisma.payout.findMany({
where: {
...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program }),
},
include: {
partner: true,
programEnrollment: {
select: {
groupId: true,
tenantId: true,
},
},
...(cutoffPeriodValue && {
commissions: {
where: {
createdAt: {
lt: cutoffPeriodValue,
},
},
},
}),
},
orderBy: {
amount: "desc",
},
...(isFinite(pageSize) && {
skip: (page - 1) * pageSize,
take: pageSize,
}),
});
if (cutoffPeriodValue) {
payouts = payouts
.map((payout) => {
const newPayoutAmount = payout.commissions.reduce((acc, commission) => {
return acc + commission.earnings;
}, 0);
return {
...payout,
amount: newPayoutAmount,
};
})
.filter((payout) => {
if (payout.amount >= program.minPayoutAmount) {
if (payout.partner.defaultPayoutMethod === "tremendous") {
return (
payout.amount >= TREMENDOUS_MIN_PAYOUT_AMOUNT_CENTS &&
payout.amount <= TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS
);
}
return true;
}
return false;
});
}
```
Sources: [apps/web/lib/api/payouts/get-eligible-payouts.ts:22-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/payouts/get-eligible-payouts.ts#L22-L90)
## Payout Processing and Splitting
### Cron Lifecycle and Execution
The payout processing cron job executes via `POST /api/cron/payouts/process`, guarded by `withCron` with a maximum execution duration of 600 seconds. The incoming payload is validated against `processPayoutsCronSchema` to extract workspace identifier, user identifier, invoice identifier, payment method identifier, cutoff period, and optional selected or excluded payout IDs.
```typescript
export const dynamic = "force-dynamic";
export const maxDuration = 600; // This function can run for a maximum of 10 minutes
const processPayoutsCronSchema = z.object({
workspaceId: z.string(),
userId: z.string(),
invoiceId: z.string(),
paymentMethodId: z.string(),
cutoffPeriod: CUTOFF_PERIOD_ENUM,
selectedPayoutIds: z.array(z.string()).optional(),
excludedPayoutIds: z.array(z.string()).optional(),
});
// POST /api/cron/payouts/process
// This route is used to process payouts for a given invoice
// we're intentionally offloading this to a cron job to avoid blocking the main thread
export const POST = withCron(async ({ rawBody }) => {
try {
const {
workspaceId,
userId,
invoiceId,
paymentMethodId,
cutoffPeriod,
selectedPayoutIds,
excludedPayoutIds,
} = processPayoutsCronSchema.parse(JSON.parse(rawBody));
```
Sources: [apps/web/app/ee/api/cron/payouts/process/route.ts:10-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/route.ts#L10-L36)
The handler fetches the unique workspace including programs and the target invoice. If the target invoice is already marked with a `failed` status, the job exits immediately to prevent race conditions with Stripe's `charge.failed` webhook handlers. When a `cutoffPeriod` is provided, `splitPayouts` executes prior to payout status mutations.
```typescript
const workspace = await prisma.project.findUniqueOrThrow({
where: {
id: workspaceId,
},
include: {
programs: true,
invoices: {
where: {
id: invoiceId,
},
},
},
});
// should never happen, but just in case
if (workspace.programs.length === 0) {
return logAndRespond(
`Workspace ${workspaceId} has no programs. Skipping...`,
);
}
const program = workspace.programs[0];
// should never happen, but just in case
if (workspace.invoices.length === 0) {
return logAndRespond(
`Invoice ${invoiceId} not found for workspace ${workspaceId}. Skipping...`,
);
}
const invoice = workspace.invoices[0];
// avoid race condition where Stripe's charge.failed webhook is processed before this cron job
if (invoice.status === "failed") {
return logAndRespond(
`Invoice ${invoiceId} has already been marked as failed. Skipping...`,
);
}
if (cutoffPeriod) {
await splitPayouts({
program,
cutoffPeriod,
selectedPayoutIds,
excludedPayoutIds,
});
}
```
Sources: [apps/web/app/ee/api/cron/payouts/process/route.ts:38-84](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/route.ts#L38-L84)
> [!WARNING]
> If an invoice status is already `failed` when the process cron executes, processing halts instantly. Do not bypass this check, as it prevents double-processing charges whose webhooks have already triggered failures.
Sources: [apps/web/app/ee/api/cron/payouts/process/route.ts:70-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/route.ts#L70-L76)
### Aggregate Payout Splitting Algorithm
The `splitPayouts` function loads eligible payouts along with their associated commissions. For each payout, commissions are partitioned into `previousCommissions` (created prior to `cutoffPeriodValue`) and `currentCommissions` (created on or after `cutoffPeriodValue`), both sorted chronologically by creation timestamp.
Sources: [apps/web/app/ee/api/cron/payouts/process/split-payouts.ts:23-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts#L23-L57)
When `previousCommissionsCount > 0`, the existing payout record is updated: its `periodEnd` is set to the end of the month of the last previous commission, and its `amount` is updated to sum the previous commission earnings. If `currentCommissionsCount > 0`, a new current-month payout record is created with a `po_` prefix ID, assigning current commission earnings and linking them via `payoutId`.
Sources: [apps/web/app/ee/api/cron/payouts/process/split-payouts.ts:58-107](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts#L58-L107)
### Fee Calculation and Currency Conversion
The `processPayouts` function updates matching payout records to `processing` status, links them to `invoice.id`, sets `initiatedAt`, and determines their processing mode based on program configuration (`external` or `internal`). For hybrid programs, payouts belonging to partners with `payoutsEnabledAt` set to `null` are updated to `external` mode.
```typescript
export async function processPayouts({
workspace,
program,
invoice,
userId,
paymentMethodId,
cutoffPeriod,
selectedPayoutIds,
excludedPayoutIds,
}: ProcessPayoutsProps) {
const cutoffPeriodValue = CUTOFF_PERIOD.find(
(c) => c.id === cutoffPeriod,
)?.value;
const res = await prisma.payout.updateMany({
where: {
...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program }),
...(cutoffPeriodValue && {
periodEnd: {
lte: cutoffPeriodValue,
},
}),
},
data: {
invoiceId: invoice.id,
status: "processing",
userId,
initiatedAt: new Date(),
// if the program is in external mode, set the mode to external
// otherwise set it to internal (we'll update specific payouts to "external" later if it's hybrid mode)
mode: program.payoutMode === "external" ? "external" : "internal",
},
});
if (res.count === 0) {
console.log(
`No payouts updated/found for invoice ${invoice.id}. Skipping...`,
);
return;
}
console.log(
`Updated ${res.count} payouts to invoice ${invoice.id} and "processing" status`,
);
// if hybrid mode, we need to update payouts for partners with payoutsEnabledAt = null to external mode
// here we don't need to filter if they have tenantId cause getPayoutEligibilityFilter above already takes care of that
if (program.payoutMode === "hybrid") {
await prisma.payout.updateMany({
where: {
invoiceId: invoice.id,
partner: {
payoutsEnabledAt: null,
},
},
data: {
mode: "external",
},
});
}
```
Sources: [apps/web/app/ee/api/cron/payouts/process/process-payouts.ts:59-119](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts#L59-L119)
| Non-USD Payment Method Type | Target Currency | Stripe API Identifier |
| :--- | :--- | :--- |
| `sepa_debit` | `eur` | SEPA Direct Debit |
| `acss_debit` | `cad` | ACSS Debit (Canada) |
Sources: [apps/web/app/ee/api/cron/payouts/process/process-payouts.ts:25-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts#L25-L28)
Total payout amounts are aggregated by mode, and Stripe payment methods are retrieved to calculate payout fees via `calculatePayoutFeeForMethod` and fee waivers via `calculatePayoutFeeWithWaiver`. Non-USD payment methods invoke `createFxQuote` to obtain real-time exchange rates from Stripe before finalizing charges.
```typescript
const payoutsByMode = await prisma.payout.groupBy({
by: ["mode"],
where: {
invoiceId: invoice.id,
},
_sum: {
amount: true,
},
});
const totalInternalPayoutAmount =
payoutsByMode.find((p) => p.mode === "internal")?._sum.amount ?? 0;
const totalExternalPayoutAmount =
payoutsByMode.find((p) => p.mode === "external")?._sum.amount ?? 0;
const totalPayoutAmount =
totalInternalPayoutAmount + totalExternalPayoutAmount;
const paymentMethod = await stripe.paymentMethods.retrieve(paymentMethodId);
const payoutFee = calculatePayoutFeeForMethod({
paymentMethod: paymentMethod.type,
payoutFee: workspace.payoutFee,
});
if (!payoutFee) {
throw new Error("Failed to calculate payout fee.");
}
console.info(
`Using payout fee of ${payoutFee} for payment method ${paymentMethod.type}`,
);
const {
fee: invoiceFee,
feeFreeAmount,
feeChargedAmount,
feeWaiverRemaining,
} = calculatePayoutFeeWithWaiver({
payoutAmount: totalPayoutAmount,
payoutFee,
payoutFeeWaiverLimit: workspace.payoutFeeWaiverLimit,
payoutFeeWaiverUsage: workspace.payoutFeeWaiverUsage,
paymentMethod: invoice.paymentMethod!,
});
const invoiceTotal = totalPayoutAmount + invoiceFee;
console.log({
totalInternalPayoutAmount,
totalExternalPayoutAmount,
totalPayoutAmount,
invoiceFee,
invoiceTotal,
feeFreeAmount,
feeChargedAmount,
feeWaiverRemaining,
});
await prisma.invoice.update({
where: {
id: invoice.id,
},
data: {
amount: totalPayoutAmount,
externalAmount: totalExternalPayoutAmount,
fee: invoiceFee,
total: invoiceTotal,
},
});
let totalToCharge = invoiceTotal - totalExternalPayoutAmount;
const currency = nonUsdPaymentMethodTypes[paymentMethod.type] || "usd";
// convert the amount to EUR/CAD if the payment method is sepa_debit or acss_debit
if (Object.keys(nonUsdPaymentMethodTypes).includes(paymentMethod.type)) {
const fxQuote = await createFxQuote({
fromCurrency: currency,
toCurrency: "usd",
});
```
Sources: [apps/web/app/ee/api/cron/payouts/process/process-payouts.ts:121-209](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts#L121-L209)
## Program Operator Confirmation
### Confirmation Schema and Validation Rules
The `confirmPayoutsAction` server action validates incoming batch payout requests using a Zod schema defined in `confirm-payouts.ts`. Program operators must specify the `workspaceId`, `paymentMethodId`, `cutoffPeriod`, and numerical billing totals (`amount`, `fee`, `total`). A strict validation refinement prevents combining `selectedPayoutIds` and `excludedPayoutIds` within the same request.
```typescript
const confirmPayoutsSchema = z
.object({
workspaceId: z.string(),
paymentMethodId: z.string(),
cutoffPeriod: CUTOFF_PERIOD_ENUM,
selectedPayoutIds: z.array(z.string()).optional(),
excludedPayoutIds: z.array(z.string()).optional(),
fastSettlement: z.boolean().optional().default(false),
amount: z.number(),
fee: z.number(),
total: z.number(),
})
.superRefine((data, ctx) => {
if (data.selectedPayoutIds?.length && data.excludedPayoutIds?.length) {
ctx.addIssue({
code: "custom",
message:
"Cannot combine selectedPayoutIds with excludedPayoutIds in the same request.",
});
}
});
```
Sources: [apps/web/lib/actions/partners/confirm-payouts.ts:30-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L30-L50)
Prior to initiating invoice creation, the action enforces permission checks for the `payouts.write` role, verifies that the workspace has a valid `stripeId`, checks workspace usage quotas against `payoutsLimit`, and validates that the payout amount satisfies the minimum invoice requirement of $10 (`INVOICE_MIN_PAYOUT_AMOUNT_CENTS`).
```typescript
throwIfNoPermission({
role: workspace.role,
requiredPermissions: ["payouts.write"],
});
if (!workspace.stripeId) {
throw new Error("Workspace does not have a valid Stripe ID.");
}
if (fastSettlement && !workspace.fastDirectDebitPayouts) {
throw new Error(
"Fast settlement is not enabled for this program. Contact sales to enable it.",
);
}
// if workspace's payouts usage + the current invoice amount
// is greater than the workspace's payouts limit, throw an error
if (workspace.payoutsUsage + amount > workspace.payoutsLimit) {
throw new Error(
exceededLimitError({
plan: workspace.plan,
planPeriod: workspace.planPeriod,
limit: workspace.payoutsLimit,
type: "payouts",
}),
);
}
if (amount < INVOICE_MIN_PAYOUT_AMOUNT_CENTS) {
throw new Error(
"Your payout total is less than the minimum invoice amount of $10.",
);
}
```
Sources: [apps/web/lib/actions/partners/confirm-payouts.ts:74-106](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L74-L106)
> [!WARNING]
> When a `cutoffPeriod` is specified, the action counts eligible payouts using `prisma.payout.aggregate`. If the total count exceeds `CUTOFF_PERIOD_MAX_PAYOUTS`, confirmation is aborted to protect against memory limits during batch splitting.
Sources: [apps/web/lib/actions/partners/confirm-payouts.ts:109-123](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L109-L123)
### Payment Method and External Payout Validation
The action retrieves the payment method via Stripe and asserts that its customer ID matches `workspace.stripeId`. It checks that the payment type is included in `PAYMENT_METHOD_TYPES`. If `fastSettlement` is requested, `fastDirectDebitPayouts` must be enabled on the workspace and the payment method type must be `us_bank_account`.
| Validation Check | Trigger Condition | Error or Action |
| :--- | :--- | :--- |
| Stripe Customer Mismatch | `paymentMethod.customer !== workspace.stripeId` | Throws `"Invalid payout method."` |
| Unsupported Payment Type | `!PAYMENT_METHOD_TYPES.includes(paymentMethod.type)` | Throws an error listing supported types |
| Fast Settlement Rail | `fastSettlement && paymentMethod.type !== "us_bank_account"` | Throws `"Fast settlement is only supported for ACH payment."` |
| Direct Debit Mandate | `DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(paymentMethod.type)` | Detaches payment method via `stripe.paymentMethods.detach` if mandate is missing |
```typescript
const paymentMethod = await stripe.paymentMethods.retrieve(paymentMethodId);
if (paymentMethod.customer !== workspace.stripeId) {
throw new Error("Invalid payout method.");
}
if (!PAYMENT_METHOD_TYPES.includes(paymentMethod.type)) {
throw new Error(
`We only support ${PAYMENT_METHOD_TYPES.join(
", ",
)} for now. Please update your payout method to one of these.`,
);
}
if (fastSettlement && paymentMethod.type !== "us_bank_account") {
throw new Error("Fast settlement is only supported for ACH payment.");
}
// if it's a direct debit payment method, we need to check to make sure mandate is valid
if (DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(paymentMethod.type)) {
const mandate = await checkPaymentMethodMandate({
paymentMethodId,
});
if (!mandate) {
// if mandate is not valid, remove the payment method
await stripe.paymentMethods.detach(paymentMethodId);
throw new Error(
"No active mandate found for this bank account. Please set up a new bank account for payouts under your billing settings page.",
);
}
}
```
Sources: [apps/web/lib/actions/partners/confirm-payouts.ts:156-187](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L156-L187)
For non-internal program modes, the action retrieves eligible payouts and workspace webhooks subscribed to the `payout.confirmed` event. If the batch includes external payouts (`payout.mode === "external"`) and no active webhook is registered, confirmation is blocked with an `EXTERNAL_WEBHOOK_REQUIRED` error.
```typescript
if (program.payoutMode !== "internal") {
const [eligiblePayouts, payoutWebhooks] = await Promise.all([
getEligiblePayouts({
program,
cutoffPeriod,
selectedPayoutIds,
excludedPayoutIds,
page: 1,
pageSize: Infinity,
}),
getWebhooks({
workspaceId: workspace.id,
triggers: ["payout.confirmed"],
disabled: false,
installationId: null,
}),
]);
// Check if the invoice includes any external payouts
const hasExternalPayouts = eligiblePayouts.find(
(payout) => payout.mode === "external",
);
if (hasExternalPayouts && payoutWebhooks.length === 0) {
throw new Error(
`EXTERNAL_WEBHOOK_REQUIRED: This invoice includes at least one external payout, which requires an active webhook subscribed to the "payout.confirmed" event. Please set one up before proceeding.`,
);
}
}
```
Sources: [apps/web/lib/actions/partners/confirm-payouts.ts:125-154](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L125-L154)
### Invoice Generation and Record Creation
Within a Prisma interactive transaction (`prisma.$transaction`), the action computes the next invoice sequence number by counting existing workspace invoices, formatting a padded string (`padStart(4, "0")`), and combining it with the workspace `invoicePrefix`. It then creates the `Invoice` record with `inv_` prefixing.
```typescript
const invoice = await prisma.$transaction(async (tx) => {
// Generate the next invoice number by counting the number of invoices for the workspace
const totalInvoices = await tx.invoice.count({
where: {
workspaceId: workspace.id,
},
});
const paddedNumber = String(totalInvoices + 1).padStart(4, "0");
const invoiceNumber = `${workspace.invoicePrefix}-${paddedNumber}`;
// Create the invoice and return it
return await tx.invoice.create({
data: {
id: createId({ prefix: "inv_" }),
number: invoiceNumber,
programId,
workspaceId: workspace.id,
// these numbers will be updated later in the payouts/process cron job
// but we're adding them now for the program/payouts/success screen
amount,
fee,
total,
paymentMethod: fastSettlement
? "ach_fast"
: STRIPE_PAYMENT_METHOD_NORMALIZATION[paymentMethod.type],
```
Sources: [apps/web/lib/actions/partners/confirm-payouts.ts:189-214](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/confirm-payouts.ts#L189-L214)
## Disbursement Fanout on Settlement
### Settlement Timing and Delayed Scheduling
When Stripe dispatches a `charge.succeeded` webhook event for an invoice, the system processes payouts via a dedicated cron endpoint (`POST /api/cron/payouts/charge-succeeded`). The handler validates the payload schema containing the `invoiceId`, retrieves the associated invoice along with a count of payouts currently marked with the `processing` status, and exits early if no matching records exist.
```typescript
const payloadSchema = z.object({
invoiceId: z.string(),
});
// POST /api/cron/payouts/charge-succeeded
// This route is used to process the charge-succeeded event from Stripe.
// We're intentionally offloading this to a cron job so we can return a 200 to Stripe immediately.
export const POST = withCron(async ({ rawBody }) => {
try {
const { invoiceId } = payloadSchema.parse(JSON.parse(rawBody));
const invoice = await prisma.invoice.findUnique({
where: {
id: invoiceId,
},
include: {
_count: {
select: {
payouts: {
where: {
status: "processing",
},
},
},
},
},
});
if (!invoice) {
return logAndRespond(`Invoice ${invoiceId} not found.`);
}
if (invoice._count.payouts === 0) {
return logAndRespond(
`No payouts found with status 'processing' for invoice ${invoiceId}, skipping...`,
);
}
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:16-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L16-L52)
Prior to queuing individual disbursement rails, the handler executes a raw SQL update against the database to align each payout's disbursement method with its corresponding partner's `defaultPayoutMethod`, provided the payout status is `processing` and a default method is set on the partner profile.
```typescript
// Set the method for each payout in the invoice to the corresponding partner's default payout method
await prisma.$executeRaw`
UPDATE Payout p
INNER JOIN Partner pn ON p.partnerId = pn.id
SET p.method = pn.defaultPayoutMethod
WHERE p.invoiceId = ${invoice.id}
AND pn.defaultPayoutMethod IS NOT NULL
AND p.status = 'processing'
`;
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:54-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L54-L62)
If the invoice payment method is a card, the system evaluates whether the funds have settled by inspecting the underlying Stripe balance transactions linked to the charge ID in `stripeChargeMetadata`. If the balance transaction's `available_on` timestamp is in the future, funds are deemed unavailable, restricting immediate disbursement rails.
| Settlement State | Condition | Action Taken |
| :--- | :--- | :--- |
| **Available** | `available_on` $\le$ `now` | `fundsAvailable` is set to `true`; all payout rails proceed immediately. |
| **Pending / No Transaction** | `available_on` $>$ `now` or zero balance transactions | `fundsAvailable` is set to `false`; post-settlement payout methods are scheduled for delayed execution via QStash. |
```typescript
let fundsAvailable = true;
// if invoice payment method is card, we need to check if the funds have settled yet
if (invoice.paymentMethod === "card") {
const fundSettlementTiming = await getFundSettlementTiming(invoice);
if (!fundSettlementTiming.fundsAvailable) {
// set fundsAvailable to false so we don't queue any payouts that require funds to be available
fundsAvailable = false;
const postSettlementPayoutMethods = [
PartnerPayoutMethod.stablecoin,
PartnerPayoutMethod.paypal,
PartnerPayoutMethod.tremendous,
];
const postSettlementPayoutsCount = await prisma.payout.count({
where: {
invoiceId: invoice.id,
status: "processing",
method: {
in: postSettlementPayoutMethods,
},
},
});
if (postSettlementPayoutsCount > 0) {
await scheduleDelayedPayouts({
invoice,
executeAt: fundSettlementTiming.scheduledAt,
});
}
}
}
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:64-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L64-L96), [apps/web/app/ee/api/cron/payouts/charge-succeeded/utils.ts:68-117](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts#L68-L117)
> [!NOTE]
> Payout methods requiring direct balance movement (`PartnerPayoutMethod.stablecoin`, `PartnerPayoutMethod.paypal`, and `PartnerPayoutMethod.tremendous`) do not support Stripe `source_transaction` references. When funds are unconfirmed, these methods are deferred until 15 minutes past the `available_on` timestamp to prevent fronting funds on reversible card charges.
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:73-77](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L73-L77), [apps/web/app/ee/api/cron/payouts/charge-succeeded/utils.ts:64-67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts#L64-L67)
When delayed scheduling triggers, `scheduleDelayedPayouts` publishes a delayed message back to `/api/cron/payouts/charge-succeeded` via QStash with a 5-minute buffer on top of the calculated delay, applying flow control parallelism keyed to the invoice identifier.
```typescript
export async function scheduleDelayedPayouts({
invoice,
executeAt,
}: {
invoice: Pick;
executeAt: Date;
}) {
const scheduleTimeMs = executeAt.getTime();
const delaySeconds = Math.max(
0,
Math.floor((scheduleTimeMs - Date.now()) / 1000),
);
const qstashResponse = await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,
delay: delaySeconds + 5 * 60, // 5 minutes delay to give some buffer for the card charge to settle fully
deduplicationId: `retry-delayed-payouts-${invoice.id}`, // The deduplication window is 10 minutes
label: invoice.id,
flowControl: {
key: invoice.id,
parallelism: 1,
},
body: {
invoiceId: invoice.id,
},
});
if (qstashResponse.messageId) {
const scheduledAt = new Date(scheduleTimeMs);
console.log(
`Scheduled delayed payouts for invoice ${invoice.id} at ${scheduledAt.toISOString()}.`,
{
qstashResponse,
},
);
} else {
throw new Error(
`Failed to schedule delayed payouts for invoice ${invoice.id}`,
);
}
}
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/utils.ts:20-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts#L20-L62)
### Multi-Rail Queue Dispatch
Once settlement availability is established, the handler fans out disbursement requests across three provider queues using `Promise.allSettled`. Invoices with `payoutMode === "external"` bypass Stripe and Tremendous processing entirely.
```typescript
await Promise.allSettled([
// Queue Stripe payouts (need to pass along fundsAvailable to handle stablecoin payouts)
queueStripePayouts({
invoice,
fundsAvailable,
}),
// only send PayPal and Tremendous payouts if funds are available
...(fundsAvailable
? [
sendPaypalPayouts({
invoice,
}),
queueTremendousPayouts({
invoice,
}),
]
: []),
// Queue external payouts (doesn't rely on fundsAvailable)
queueExternalPayouts(invoice),
]);
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:98-120](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L98-L120)
- **Stripe Payout Queue (`queueStripePayouts`)**: Aggregates stablecoin payouts meeting `MIN_WITHDRAWAL_AMOUNT_CENTS`, adds fixed fees (`STABLECOIN_PAYOUT_FIXED_FEE_CENTS`), funds Dub's financial account if `fundsAvailable` is true, and chunks eligible partners in batches of 100 to enqueue jobs into the `send-stripe-payout` QStash queue with deduplication keys formatted as `${invoiceId}-${partnerId}`.
```typescript
export async function queueStripePayouts({
invoice,
fundsAvailable,
}: {
invoice: Pick<
Invoice,
"id" | "paymentMethod" | "stripeChargeMetadata" | "payoutMode"
>;
fundsAvailable: boolean;
}) {
if (invoice.payoutMode === "external") {
console.log(
`Invoice ${invoice.id} is paid externally, skipping Stripe payouts...`,
);
return;
}
const { id: invoiceId, paymentMethod, stripeChargeMetadata } = invoice;
if (fundsAvailable) {
// Fund the total Stablecoin payout amount for this invoice
const { _sum, _count } = await prisma.payout.aggregate({
_sum: {
amount: true,
},
_count: {
id: true,
},
where: {
invoiceId: invoice.id,
method: "stablecoin",
status: "processing",
// only transfer funds for stablecoin payouts >= minimum withdrawal amount
// for payouts below the minimum withdrawal amount, we will just mark them as processed
// and users can force withdraw them manually later (which triggers another fundFinancialAccount call)
amount: {
gte: MIN_WITHDRAWAL_AMOUNT_CENTS,
},
},
});
// We need to add the STABLECOIN_PAYOUT_FIXED_FEE_CENTS for each payout to the total funding amount
// to make sure that `createStablecoinPayout` later has enough funds to cover Stripe's fees
const stablecoinFundingAmount =
(_sum.amount ?? 0) + _count.id * STABLECOIN_PAYOUT_FIXED_FEE_CENTS;
// Send money to Financial Account to handle Stablecoin payouts
if (stablecoinFundingAmount > 0) {
try {
await fundFinancialAccount({
amount: stablecoinFundingAmount,
idempotencyKey: invoiceId,
});
} catch (error) {
await log({
message: `Failed to fund Dub's financial account for stablecoin payouts: ${error.message}`,
type: "errors",
});
throw error;
}
}
}
// Find the id of the charge that was used to fund the transfer
const parsedChargeMetadata =
stripeChargeMetadataSchema.safeParse(stripeChargeMetadata);
const chargeId = parsedChargeMetadata?.success
? parsedChargeMetadata?.data.id
: undefined;
// this should never happen since all completed invoices should have a charge id, but just in case
if (!chargeId) {
await log({
message:
"No charge id found in stripeChargeMetadata for invoice " +
invoiceId +
", continuing without source_transaction.",
type: "errors",
});
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts:16-154](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts#L16-L154)
- **Tremendous Payout Queue (`queueTremendousPayouts`)**: Filters internal processing payouts for partners with non-null `tremendousEmail` and `payoutsEnabledAt` whose amounts fall between `TREMENDOUS_MIN_PAYOUT_AMOUNT_CENTS` and `TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS`. It verifies that the program defines a `tremendousCampaignId` before chunking partners into batches of 100 and enqueueing jobs into the `send-tremendous-payout` QStash queue.
```typescript
export async function queueTremendousPayouts({
invoice,
}: {
invoice: Pick;
}) {
if (invoice.payoutMode === "external") {
console.log(
`Invoice ${invoice.id} is paid externally, skipping Tremendous payouts...`,
);
return;
}
// should never happen, but just in case
if (!invoice.programId) {
console.log(
`Invoice ${invoice.id} has no program ID, skipping Tremendous payouts...`,
);
return;
}
const partnersInCurrentInvoice = await prisma.payout.groupBy({
by: ["partnerId"],
where: {
invoiceId: invoice.id,
status: PayoutStatus.processing,
mode: PayoutMode.internal,
method: PartnerPayoutMethod.tremendous,
amount: {
gte: TREMENDOUS_MIN_PAYOUT_AMOUNT_CENTS,
lte: TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,
},
partner: {
tremendousEmail: {
not: null,
},
payoutsEnabledAt: {
not: null,
},
},
},
});
if (partnersInCurrentInvoice.length === 0) {
console.log("No partners for sending via Tremendous, skipping...");
return;
}
const program = await prisma.program.findUniqueOrThrow({
where: {
id: invoice.programId,
},
select: {
tremendousCampaignId: true,
},
});
// Log and skip if the program has no Tremendous campaign.
if (!program.tremendousCampaignId) {
logger.error("missing_campaign", {
service: "tremendous",
operation: "queue_tremendous_payouts",
correlation: {
invoiceId: invoice.id,
programId: invoice.programId,
},
});
await logger.flush();
return;
}
const chunkedPartners = chunk(partnersInCurrentInvoice, 100);
for (let i = 0; i < chunkedPartners.length; i++) {
const partnersInChunk = chunkedPartners[i];
await Promise.all(
partnersInChunk.map(({ partnerId }) =>
queue.enqueueJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/send-tremendous-payout`,
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts:20-113](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts#L20-L113)
- **PayPal and External Dispatch**: PayPal payouts are dispatched directly when funds are available, while external payouts are queued independently of the `fundsAvailable` status.
```typescript
// only send PayPal and Tremendous payouts if funds are available
...(fundsAvailable
? [
sendPaypalPayouts({
invoice,
}),
queueTremendousPayouts({
invoice,
}),
]
: []),
// Queue external payouts (doesn't rely on fundsAvailable)
queueExternalPayouts(invoice),
```
Sources: [apps/web/app/ee/api/cron/payouts/charge-succeeded/route.ts:105-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts#L105-L118)
## Stripe and Stablecoin Execution
### Stripe Connect Transfers
The execution layer processes internal queue jobs targeting Stripe Connect transfers and stablecoin payouts via the `/api/cron/payouts/send-stripe-payout` cron route. When a job arrives, the payload schema validates the presence of a `partnerId`, an optional `invoiceId`, and an optional `chargeId`. The router queries for a processing payout matching the partner, invoice, internal mode, and method types (`connect` or `stablecoin`), delegating execution to the corresponding handler function.
```typescript
const payloadSchema = z.object({
partnerId: z.string(),
invoiceId: z.string().optional(),
chargeId: z.string().optional(),
});
```
Sources: [apps/web/app/ee/api/cron/payouts/send-stripe-payout/route.ts:11-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts#L11-L15)
For `connect` payout methods, `createStripeTransfer` retrieves the partner's Stripe Connect identifier and verifies that payouts are enabled. It aggregates previously processed payouts with `stripeTransferId` set to `null` alongside active processing payouts for the current invoice.
```typescript
const partner = await prisma.partner.findUniqueOrThrow({
where: {
id: partnerId,
},
select: {
id: true,
email: true,
stripeConnectId: true,
payoutsEnabledAt: true,
},
});
// should never happen, but just in case
if (!partner.stripeConnectId || !partner.payoutsEnabledAt) {
console.warn(
`Partner ${partner.email} does not have an active payout account.`,
);
return;
}
const commonInclude: Prisma.PayoutInclude = {
program: {
select: {
id: true,
name: true,
logo: true,
workspaceId: true,
},
},
};
const [previouslyProcessedPayouts, currentInvoicePayouts] = await Promise.all(
[
prisma.payout.findMany({
where: {
partnerId: partner.id,
status: "processed",
stripeTransferId: null,
method: "connect",
},
orderBy: {
id: "asc",
},
include: commonInclude,
}),
invoiceId
? prisma.payout.findMany({
where: {
partnerId: partner.id,
invoiceId,
status: "processing",
method: "connect",
},
orderBy: {
id: "asc",
},
include: commonInclude,
})
: Promise.resolve([]),
],
);
```
Sources: [apps/web/lib/partners/create-stripe-transfer.ts:37-98](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts#L37-L98)
> [!CAUTION]
> If a partner's Stripe Express account returns `payouts_enabled` as false or has its `transfers` capability set to `inactive`, the system automatically nullifies `payoutsEnabledAt` and `defaultPayoutMethod` on the partner record, processes current invoice payouts, and halts transfer creation.
Sources: [apps/web/lib/partners/create-stripe-transfer.ts:164-191](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts#L164-L191)
Transfers are executed via `stripe.transfers.create` using a calculated idempotency key. When no prior processed payouts exist and a `chargeId` is present, the transfer includes a `source_transaction` reference to associate the funds directly with the original payment.
```typescript
const idempotencyKey = createPayoutsIdempotencyKey({
partnerId: partner.id,
invoiceId,
payoutIds: allPayouts.map((p) => p.id),
});
// Create a transfer for the partner combined payouts and update it as sent
const transfer = await stripe.transfers.create(
{
amount: finalTransferableAmount,
currency: "usd",
// here, `transfer_group` technically only used to associate the transfer with the invoice
// (even though the transfer could technically include payouts from multiple invoices)
transfer_group: finalPayoutInvoiceId!,
destination: partner.stripeConnectId,
description: `Dub Partners payout transfer (${allPayoutsProgramNames.join(", ")})`,
// Omit `source_transaction` if prior processed payouts exist to ensure this transfer
// never exceeds the original charge amount.
...(previouslyProcessedPayouts.length === 0 &&
chargeId && {
source_transaction: chargeId,
}),
},
{
idempotencyKey,
},
);
```
Sources: [apps/web/lib/partners/create-stripe-transfer.ts:196-222](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts#L196-L222)
### Stablecoin Outbound Payments
Stablecoin disbursements managed by `createStablecoinPayout` fetch partner accounts using `stripeRecipientId`. The handler validates account status by checking whether the recipient account is closed or lacks active `crypto_wallets` capabilities.
```typescript
const stripeRecipientAccount = await getStripeRecipientAccount(
partner.stripeRecipientId,
);
// Stripe recipient account is closed
if (stripeRecipientAccount.closed) {
await prisma.partner.update({
where: {
id: partner.id,
},
data: {
stripeRecipientId: null,
payoutsEnabledAt: null,
defaultPayoutMethod: null,
},
});
await markPayoutsAsProcessed(currentInvoicePayouts);
console.warn(
`Stripe recipient account for partner ${partner.email} is closed.`,
);
return;
}
// Stripe recipient account does not have crypto wallet capabilities
if (
stripeRecipientAccount.configuration?.recipient?.capabilities
?.crypto_wallets?.status !== "active"
) {
await prisma.partner.update({
where: {
id: partner.id,
},
data: {
payoutsEnabledAt: null,
},
});
await markPayoutsAsProcessed(currentInvoicePayouts);
const message = `Stripe recipient account for partner ${partner.email} does not have crypto wallet capabilities.`;
if (forceWithdrawal) {
throw new Error(message);
} else {
console.warn(message);
return;
}
}
```
Sources: [apps/web/lib/partners/create-stablecoin-payout.ts:180-229](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stablecoin-payout.ts#L180-L229)
## Related
- [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine)
- [Fraud Prevention](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/fraud-prevention)
---
## Technical docs: GET Get network partners count or list
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminnetworkpartners
## Parameters
## Responses
## Try It
---
## Technical docs: GET Get trusted partners
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadmintrustedpartners
## Responses
## Try It
---
## Technical docs: Fraud Prevention
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/fraud-prevention
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/lib/actions/partners/start-identity-verification.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts)
- [apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts)
- [apps/web/lib/middleware/link.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/fraud/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/fraud/page.tsx)
- [apps/web/ui/partners/identity-verification/identity-verification-banner.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/identity-verification/identity-verification-banner.tsx)
- [apps/web/ui/partners/fraud-risks/risk-disclaimer-banner.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/risk-disclaimer-banner.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/risk-events-table.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/risk-events-table.tsx)
- [apps/web/scripts/migrations/backfill-hold-processed-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/migrations/backfill-hold-processed-commissions.ts)
- [apps/web/app/ee/api/workflows/create-partner-commission/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts)
- [apps/web/ui/partners/identity-verification/identity-verification-card.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/identity-verification/identity-verification-card.tsx)
- [apps/web/scripts/migrations/backfill-hold-pending-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/migrations/backfill-hold-pending-commissions.ts)
- [apps/web/app/api/dub/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/fraud/review-fraud-alert-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/fraud/review-fraud-alert-sheet.tsx)
- [apps/web/lib/auth/track-dub-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/track-dub-lead.ts)
- [apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/page.tsx)
- [apps/web/lib/api/fraud/hold-pending-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-pending-commissions.ts)
- [apps/web/lib/api/fraud/hold-processed-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-processed-commissions.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/layout.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/layout.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/risk-rules-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/risk-rules-sheet.tsx)
- [apps/web/ui/partners/fraud-risks/risk-review-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/risk-review-sheet.tsx)
- [apps/web/app/ee/app.dub.co/embed/referrals/quickstart.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx)
- [apps/web/lib/api/fraud/detect-record-fraud-application.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-record-fraud-application.ts)
- [apps/web/app/ee/partners.dub.co/dashboard/profile/identity-verification-section.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/identity-verification-section.tsx)
- [apps/web/lib/swr/use-program-application-risks.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-program-application-risks.ts)
- [apps/web/lib/api/fraud/get-program-application-risks.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/get-program-application-risks.ts)
- [apps/web/ui/partners/fraud-risks/partner-risk-banner.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/partner-risk-banner.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/network/identity-verification.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/identity-verification.tsx)
## Overview
Fraud Prevention protects [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs) by combining automated edge bot filtering, heuristic application risk analysis, backend duplicate detection, and third-party identity verification with Veriff. It mitigates financial exposure through automated commission freezes, gives administrators centralized tooling to review risk alerts, and manages partner bans across workspaces.
Sources: [apps/web/lib/middleware/link.ts:32-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts#L32-L32)
Sources: [apps/web/lib/api/fraud/get-program-application-risks.ts:11-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/get-program-application-risks.ts#L11-L17)
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:17-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L17-L23)
Sources: [apps/web/app/ee/admin.dub.co/dashboard/partners/fraud/page.tsx:41-67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/fraud/page.tsx#L41-L67)
Sources: [apps/web/lib/api/fraud/hold-pending-commissions.ts:10-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-pending-commissions.ts#L10-L16)
## Edge Bot Detection and Clicks
### Bot Filtering and Identity Hashing
The edge redirection middleware inspects incoming requests before redirection or analytics recording occurs. To handle automated scrapers and bot traffic, links ending with `.php` extensions are systematically intercepted via `isUnsupportedKey` and redirected to the root domain with a `dub-no-track=1` query parameter and an `X-Robots-Tag: googlebot: noindex` header to prevent tracking pollution.
```typescript
// we don't support .php links (too much bot traffic)
// hence we redirect to the root domain and add `dub-no-track` header to avoid tracking bot traffic
if (isUnsupportedKey(key)) {
return NextResponse.redirect(new URL("/?dub-no-track=1", req.url), {
headers: {
...DUB_HEADERS,
"X-Robots-Tag": "googlebot: noindex",
},
status: 302,
});
}
```
Sources: [apps/web/lib/middleware/link.ts:77-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts#L77-L87)
For general traffic, unique visitor identification relies on `getIdentityHash` to compute request signatures. When [conversion tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking) or partner attribution is active, the middleware checks `recordClickCache` using this identity hash and domain-key pair to deduplicate or correlate incoming request sessions.
```typescript
// if we need to cache the clickId, check if clickId is cached in Redis
if (shouldCacheClickId) {
const identityHash = await getIdentityHash(req);
clickId =
(await recordClickCache
.get({ domain, key, identityHash })
.catch(() => undefined)) || undefined;
}
```
Sources: [apps/web/lib/middleware/link.ts:198-205](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts#L198-L205)
> [!NOTE]
> Unsupported `.php` links bypass standard database lookups entirely, immediately redirecting to the root domain with `dub-no-track=1` to prevent bot traffic from skewing click analytics.
Sources: [apps/web/lib/middleware/link.ts:77-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts#L77-L87)
> [!WARNING]
> During Redis failover states (`redisFailOver` active), click tracking jobs and identity hash lookups are skipped entirely to avoid edge execution timeouts, generating a local fallback `nanoid(16)` click identifier when necessary.
Sources: [apps/web/lib/middleware/link.ts:93-98](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts#L93-L98)
Sources: [apps/web/lib/middleware/link.ts:207-210](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts#L207-L210)
## Program Application Risk Evaluation
### Heuristic Checks and Application Risk Analysis
Partner applications are evaluated through heuristic rules to detect suspicious profile attributes during program enrollment. The risk evaluation engine analyzes partner attributes such as email format, domain consistency, and linked social profiles to calculate risk levels and identify potential fraud indicators.
```typescript
export async function getProgramApplicationRisks({
program,
partner,
}: {
program: Pick;
partner: Pick;
}) {
const fraudGroups = await prisma.fraudEventGroup.findMany({
where: {
programId: program.id,
partnerId: partner.id,
status: "pending",
type: {
in: ["partnerCrossProgramBan", "partnerDuplicateAccount"],
},
},
});
const hasCrossProgramBan = fraudGroups.some(
(group) => group.type === "partnerCrossProgramBan",
);
const hasDuplicateAccounts = fraudGroups.some(
(group) => group.type === "partnerDuplicateAccount",
);
const risksDetected: Partial> = {
partnerCrossProgramBan: hasCrossProgramBan,
partnerDuplicateAccount: hasDuplicateAccounts,
partnerEmailDomainMismatch: checkPartnerEmailDomainMismatch(partner),
partnerEmailMasked: checkPartnerEmailMasked(partner),
partnerNoSocialLinks: checkPartnerNoSocialLinks(partner),
partnerNoVerifiedSocialLinks: checkPartnerNoVerifiedSocialLinks(partner),
};
```
Sources: [apps/web/lib/api/fraud/get-program-application-risks.ts:11-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/get-program-application-risks.ts#L11-L44)
The risk assessment workflow checks pending fraud event groups for cross-program bans and duplicate accounts alongside four specific heuristic checks. The results populate a structured risks dictionary and determine the overall risk severity using highest-severity aggregation.
| Rule Type | Detection Function | Target Property | Purpose |
| :--- | :--- | :--- | :--- |
| `partnerCrossProgramBan` | Database query (`fraudEventGroup`) | `partner.id`, `program.id` | Checks for active cross-program ban events in pending status. |
| `partnerDuplicateAccount` | Database query (`fraudEventGroup`) | `partner.id`, `program.id` | Checks for active duplicate account events in pending status. |
| `partnerEmailDomainMismatch` | `checkPartnerEmailDomainMismatch` | `partner` | Evaluates discrepancies between email domains and profile data. |
| `partnerEmailMasked` | `checkPartnerEmailMasked` | `partner` | Identifies masked or disposable email address formats. |
| `partnerNoSocialLinks` | `checkPartnerNoSocialLinks` | `partner` | Detects applications lacking any connected social platforms. |
| `partnerNoVerifiedSocialLinks` | `checkPartnerNoVerifiedSocialLinks` | `partner` | Flags partner profiles with unverified social links. |
Sources: [apps/web/lib/api/fraud/get-program-application-risks.ts:18-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/get-program-application-risks.ts#L18-L44)
> [!NOTE]
> Application risk evaluation runs dynamically when fetching partner details through `getProgramApplicationRisks`, querying pending `fraudEventGroup` entries for `partnerCrossProgramBan` and `partnerDuplicateAccount` alongside runtime heuristic functions.
Sources: [apps/web/lib/api/fraud/get-program-application-risks.ts:18-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/get-program-application-risks.ts#L18-L44)
### UI Integration and Plan Capabilities
The frontend renders application risk summaries via `ProgramApplicationRiskSummary`, which retrieves risk status using SWR immutable hooks linked to workspace settings.
```typescript
export function useProgramApplicationRisks({
filters,
enabled = true,
}: {
filters: { partnerId: string | null | undefined };
enabled?: boolean;
}) {
const { id: workspaceId } = useWorkspace();
const { partnerId } = filters;
const { data, isLoading, error } = useSWRImmutable(
enabled && partnerId && workspaceId
? `/api/partners/${partnerId}/application-risks?workspaceId=${workspaceId}`
: null,
fetcher,
);
const { risksDetected, riskSeverity } = data || {};
const triggeredFraudRules = useMemo(() => {
if (!risksDetected) return [];
return FRAUD_RULES.filter((rule) => {
return risksDetected[rule.type] === true;
});
}, [risksDetected]);
return {
risks: risksDetected,
triggeredFraudRules,
severity: riskSeverity,
isLoading,
error,
};
```
Sources: [apps/web/lib/swr/use-program-application-risks.ts:13-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/swr/use-program-application-risks.ts#L13-L44)
When plan capabilities permit fraud event management (`canManageFraudEvents`), the component displays triggered fraud rules with colored severity indicators. If the workspace is on a lower tier, it renders an upsell component featuring blurred risk items and an upgrade prompt for the Advanced plan.
```tsx
const { canManageFraudEvents } = getPlanCapabilities(plan);
if (isLoading || triggeredFraudRules.length === 0) {
return null;
}
if (!canManageFraudEvents) {
return ;
}
return (
<>
Risk analysis
setShowModal(true)}
className="h-6 w-fit px-1.5 py-2"
/>
{triggeredFraudRules.map((rule) => {
if (!rule.severity) return null;
return (
{rule.name}
);
})}
>
);
}
```
Sources: [apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx:39-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx#L39-L91)
> [!WARNING]
> Workspaces lacking fraud management privileges do not receive raw risk data; `ProgramApplicationRiskSummaryUpsell` displays placeholder risk entries with a backdrop blur and an upgrade banner.
Sources: [apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx:39-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx#L39-L47)
Sources: [apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx:112-192](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/program-application-risk-summary.tsx#L112-L192)
## Duplicate Identity and Payout Detection
### Identity Verification and Session Aggregation
The backend identity fraud workflow evaluates incoming Veriff verification decisions to uncover shared partner identities. When a verification session completes, the system filters risk labels against the approved Veriff risk categories and extracts all associated session identifiers linked to those labels.
```typescript
let veriffSessionIds = riskLabels
.filter(({ label }) => veriffRiskLabels.includes(label as VeriffRiskLabel))
.map(({ sessionIds }) => sessionIds)
.flat();
// Add the current veriff session id to the list
veriffSessionIds.push(veriffSessionId);
// Remove duplicates
veriffSessionIds = [...new Set(veriffSessionIds)];
if (veriffSessionIds.length === 0) {
console.log(
"[detectDuplicateIdentityFraud] No veriff session ids provided.",
);
return;
}
```
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:30-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L30-L46)
The function queries `prisma.programEnrollment` to find all program enrollments where the associated partner matches any collected Veriff session IDs. Enrollments where the `partnerDuplicateAccount` fraud rule is disabled via the program's fraud rules configuration are filtered out.
```typescript
let programEnrollments = await prisma.programEnrollment.findMany({
where: {
partner: {
veriffSessionId: {
in: veriffSessionIds,
},
},
},
select: {
programId: true,
partnerId: true,
status: true,
riskMonitoringDisabledAt: true,
program: {
select: {
fraudRules: true,
},
},
},
});
if (programEnrollments.length === 0) {
console.log("[detectDuplicateIdentityFraud] No program enrollments found.");
return;
}
// Filter out program enrollments where the partnerDuplicateAccount rule is disabled
programEnrollments = programEnrollments.filter((enrollment) =>
isFraudRuleEnabled({
fraudRules: enrollment.program.fraudRules,
ruleType: FraudRuleType.partnerDuplicateAccount,
}),
);
```
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:48-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L48-L80)
> [!NOTE]
> During duplicate identity detection, the current `veriffSessionId` is explicitly appended to the extracted session list and deduplicated via a `Set` before querying the database.
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:35-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L35-L39)
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:48-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L48-L55)
### Payout Method and Crypto Wallet Matching
Duplicate payout method detection correlates partners who register identical payout destinations or cryptocurrency wallet addresses. The detection accepts an options object containing either a `payoutMethodHash` or a `cryptoWalletAddress`.
```typescript
type DetectDuplicatePayoutMethodFraudOptions =
| { payoutMethodHash: string; cryptoWalletAddress?: never }
| { cryptoWalletAddress: string; payoutMethodHash?: never };
// Check for duplicate payout methods: if multiple partners share the same payout method hash,
// create fraud events for all their active program enrollments to flag potential fraud
export async function detectDuplicatePayoutMethodFraud({
payoutMethodHash,
cryptoWalletAddress,
}: DetectDuplicatePayoutMethodFraudOptions) {
if (!payoutMethodHash && !cryptoWalletAddress) {
return;
}
```
Sources: [apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts:10-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts#L10-L22)
The system queries program enrollments whose partner records match the provided hash or wallet address using an `OR` condition, then verifies that the `partnerDuplicateAccount` rule remains enabled for each program.
```typescript
let programEnrollments = await prisma.programEnrollment.findMany({
where: {
partner: {
OR: [
...(payoutMethodHash ? [{ payoutMethodHash }] : []),
...(cryptoWalletAddress ? [{ cryptoWalletAddress }] : []),
],
},
},
select: {
programId: true,
partnerId: true,
status: true,
riskMonitoringDisabledAt: true,
program: {
select: {
fraudRules: true,
},
},
},
});
if (programEnrollments.length === 0) {
return;
}
// Filter out program enrollments where the partnerDuplicateAccount rule is disabled
programEnrollments = programEnrollments.filter((enrollment) =>
isFraudRuleEnabled({
fraudRules: enrollment.program.fraudRules,
ruleType: FraudRuleType.partnerDuplicateAccount,
}),
);
```
Sources: [apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts:24-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts#L24-L56)
> [!IMPORTANT]
> Both duplicate identity and payout detection workflows group matching partners by program ID and discard any programs with fewer than two participating partners before generating fraud events.
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:82-107](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L82-L107)
Sources: [apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts:58-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts#L58-L82)
### Fraud Event Creation and Commission Freezes
Once multiple partners are identified within a program, the workflows iterate through each active, risk-monitored partner to construct duplicate account fraud event inputs. Inactive enrollment statuses and partners with disabled risk monitoring are skipped.
```typescript
for (const [programId, partners] of partnersByProgram.entries()) {
for (const sourcePartner of partners) {
// Skip if the partner is inactive or risk detection is disabled
if (
INACTIVE_ENROLLMENT_STATUSES.includes(sourcePartner.status) ||
sourcePartner.riskMonitoringDisabledAt
) {
continue;
}
for (const enrolledPartner of partners) {
fraudEvents.push({
programId,
partnerId: sourcePartner.partnerId,
type: FraudRuleType.partnerDuplicateAccount,
metadata: {
duplicatePartnerId: enrolledPartner.partnerId,
riskLabels,
},
});
}
}
}
```
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:111-133](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L111-L133)
The resulting fraud events are persisted via `createFraudEvents`, returning affected groups that trigger batch commission freezes for both pending and processed earnings.
```typescript
const { affectedGroups } = await createFraudEvents(fraudEvents);
const results = await Promise.allSettled([
holdPendingCommissions(affectedGroups),
holdProcessedCommissions(affectedGroups),
]);
results
.filter((r): r is PromiseRejectedResult => r.status === "rejected")
.forEach((r) => console.error("Failed to hold commissions:", r.reason));
```
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:135-143](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L135-L143)
| Detection Workflow | Input Parameters | Target Entity Property | Associated Fraud Rule |
| :--- | :--- | :--- | :--- |
| `detectDuplicateIdentityFraud` | `veriffSessionId`, `riskLabels` | `partner.veriffSessionId` | `FraudRuleType.partnerDuplicateAccount` |
| `detectDuplicatePayoutMethodFraud` | `payoutMethodHash`, `cryptoWalletAddress` | `partner.payoutMethodHash`, `partner.cryptoWalletAddress` | `FraudRuleType.partnerDuplicateAccount` |
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:17-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L17-L23)
Sources: [apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts:125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-identity-fraud.ts#L125)
Sources: [apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts:16-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts#L16-L19)
Sources: [apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts:100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts#L100)
## Veriff Identity Verification Workflow
### Session Creation and Action Validation
The identity verification workflow begins when a partner initiates verification through the `startIdentityVerificationAction` server action. The action verifies that the user possesses the `partner_profile.update` permission before evaluating the partner's current `identityVerificationStatus`.
```typescript
export const startIdentityVerificationAction = authPartnerActionClient.action(
async ({ ctx }) => {
const { partner, partnerUser } = ctx;
throwIfNoPermission({
role: partnerUser.role,
permission: "partner_profile.update",
});
if (partner.identityVerificationStatus) {
switch (partner.identityVerificationStatus) {
case "approved":
throw new Error(
"Your identity has already been verified. No further action is required.",
);
case "submitted":
case "review":
throw new Error(
"A verification attempt is already in progress. Please wait for it to complete or resubmit.",
);
}
}
```
Sources: [apps/web/lib/actions/partners/start-identity-verification.ts:16-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts#L16-L37)
If the status is `approved`, the system rejects the request with an error indicating no further action is required. If the status is `submitted` or `review`, the system blocks duplicate attempts while an active review is in progress. Additionally, the system checks `veriffMetadata.attemptCount` against `MAX_PARTNER_IDENTITY_VERIFICATION_ATTEMPTS`.
```typescript
const veriffMetadata = parseVeriffMetadata(partner.veriffMetadata);
if (
veriffMetadata.attemptCount >= MAX_PARTNER_IDENTITY_VERIFICATION_ATTEMPTS
) {
throw new Error(
"You've reached the maximum number of identity verification attempts. Please contact support: https://dub.co/support",
);
}
```
Sources: [apps/web/lib/actions/partners/start-identity-verification.ts:39-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts#L39-L47)
> [!WARNING]
> If an unexpired session already exists (`sessionExpiresAt > new Date()`), the action returns the existing `sessionUrl` instead of generating a duplicate Veriff session.
Sources: [apps/web/lib/actions/partners/start-identity-verification.ts:51-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts#L51-L60)
### Partner Dashboard and Admin UI Integration
When a new session is generated, rate limiting is enforced via `RATELIMIT_POLICIES.identityVerificationStart` keyed on the partner ID. The backend invokes `createVeriffSession`, updates the partner record with the new `veriffSessionId` and merged Veriff metadata featuring a 7-day expiration via `addDays(new Date(), 7)`, and returns the session URL.
```typescript
await assertRateLimit({
policy: RATELIMIT_POLICIES.identityVerificationStart,
identifier: partner.id,
});
// Create a new session
const { verification } = await createVeriffSession({
partner,
});
await prisma.partner.update({
where: {
id: partner.id,
},
data: {
veriffSessionId: verification.id,
veriffMetadata: mergeVeriffMetadata(partner.veriffMetadata, {
sessionUrl: verification.url,
sessionExpiresAt: addDays(new Date(), 7),
}),
},
});
return {
sessionUrl: verification.url,
};
```
Sources: [apps/web/lib/actions/partners/start-identity-verification.ts:62-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts#L62-L87)
In the partner profile UI, `IdentityVerificationSection` renders status badges and manages verification actions. Upon successful action execution, the client dynamically imports `createVeriffFrame` from `@veriff/incontext-sdk` to render the verification modal in-context, triggering profile revalidation when the `MESSAGES.FINISHED` event occurs.
```tsx
const { executeAsync, isPending } = useAction(
startIdentityVerificationAction,
{
onError: ({ error }) => {
toast.error(
parseActionError(error, "Failed to start identity verification."),
);
},
onSuccess: async ({ data }) => {
const { createVeriffFrame, MESSAGES } = await import(
"@veriff/incontext-sdk"
);
createVeriffFrame({
url: data.sessionUrl,
onEvent: (msg) => {
if (msg === MESSAGES.FINISHED) {
toast.success(
"Verification submitted. We'll update your status shortly.",
);
mutate();
}
},
});
mutate();
},
},
);
```
Sources: [apps/web/app/ee/partners.dub.co/dashboard/profile/identity-verification-section.tsx:30-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/identity-verification-section.tsx#L30-L58)
Administrators can also manage verifications directly from the network management dashboard using `NetworkIdentityVerification`, which supports generating Veriff session URLs or manually verifying partner identity.
```tsx
const handleGenerateSession = async () => {
const requestPartnerId = partner.id;
setIsGeneratingSession(true);
try {
const response = await fetch(
`/api/admin/partners/${requestPartnerId}/generate-veriff-session`,
{
method: "POST",
},
);
if (!response.ok) {
throw new Error(
(await response.text()) || "Failed to generate Veriff session.",
);
}
const { sessionUrl: url } = (await response.json()) as {
sessionUrl: string;
};
if (partnerIdRef.current !== requestPartnerId) {
return;
}
setSessionUrl(url);
toast.success("Veriff session generated.");
} catch (error) {
if (partnerIdRef.current !== requestPartnerId) {
return;
}
toast.error(
error instanceof Error
? error.message
: "Failed to generate Veriff session.",
);
} finally {
if (partnerIdRef.current === requestPartnerId) {
setIsGeneratingSession(false);
}
}
};
const handleVerifyIdentity = async () => {
const requestPartnerId = partner.id;
setIsVerifyingIdentity(true);
try {
const response = await fetch(
`/api/admin/partners/${requestPartnerId}/verify-identity`,
{
method: "POST",
},
);
if (!response.ok) {
throw new Error(
(await response.text()) || "Failed to verify partner identity.",
);
}
if (partnerIdRef.current !== requestPartnerId) {
return;
}
toast.success("Partner identity verified.");
} catch (error) {
if (partnerIdRef.current !== requestPartnerId) {
return;
}
toast.error(
error instanceof Error
? error.message
: "Failed to verify partner identity.",
);
} finally {
if (partnerIdRef.current === requestPartnerId) {
setIsVerifyingIdentity(false);
}
}
};
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/partners/network/identity-verification.tsx:27-110](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/identity-verification.tsx#L27-L110)
| Component / Action | Target Entity / Endpoint | Primary Status States / Actions | Permission Required |
| :--- | :--- | :--- | :--- |
| `startIdentityVerificationAction` | Server Action | `approved`, `submitted`, `review`, `started`, `declined` | `partner_profile.update` |
| `IdentityVerificationSection` | `/profile#identity-verification` | `approved`, `submitted`, `review`, `started`, `declined`, `resubmissionRequested`, `expired`, `abandoned` | `partner_profile.update` (enforced via `hasPermission`) |
| `NetworkIdentityVerification` | `/api/admin/partners/{id}/generate-veriff-session` | `Generate Veriff Session`, `Verify identity` | Admin Role |
Sources: [apps/web/lib/actions/partners/start-identity-verification.ts:20-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts#L20-L23)
Sources: [apps/web/lib/actions/partners/start-identity-verification.ts:72-83](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/partners/start-identity-verification.ts#L72-L83)
Sources: [apps/web/app/ee/partners.dub.co/dashboard/profile/identity-verification-section.tsx:30-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/identity-verification-section.tsx#L30-L57)
Sources: [apps/web/app/ee/admin.dub.co/dashboard/partners/network/identity-verification.tsx:32-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/identity-verification.tsx#L32-L82)
## Commission Holding and Settlement Freezes
### Pending and Processed Commission Batch Holds
When fraud rules or risk triggers are activated, the system executes bulk-hold mechanisms for both pending and processed commissions. For pending commissions, `holdPendingCommissions` targets partner-program enrollments flagged by partner-level fraud criteria, such as duplicate identities, duplicate payout methods, or network-level bans. The engine evaluates eligibility using a standard filter across enterprise and advanced workspace plans.
```typescript
const holdEligibleWhere: Prisma.CommissionWhereInput = {
status: CommissionStatus.pending,
earnings: {
gt: 0,
},
program: {
workspace: {
plan: {
in: ["enterprise", "advanced"],
},
},
},
};
```
Sources: [apps/web/lib/api/fraud/hold-pending-commissions.ts:26-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-pending-commissions.ts#L26-L38)
For processed commissions that are already associated with a pending payout, `holdProcessedCommissions` applies a parallel batch hold mechanism. In addition to updating the commission status to hold, this operation resets the `payoutId` field to null and tracks affected payout IDs for subsequent amount recalculation via `retallyPayoutsAmount`.
```typescript
const holdEligibleWhere: Prisma.CommissionWhereInput = {
status: CommissionStatus.processed,
payout: {
status: PayoutStatus.pending,
},
earnings: {
gt: 0,
},
program: {
workspace: {
plan: {
in: ["enterprise", "advanced"],
},
},
},
};
```
Sources: [apps/web/lib/api/fraud/hold-processed-commissions.ts:32-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-processed-commissions.ts#L32-L47)
> [!WARNING]
> Because commission statuses can change between the initial query and the execution of `updateMany` (for example, if a payout is modified concurrently), `updateMany` re-checks eligibility, and the system verifies updated row counts against database state before logging activity or syncing totals.
Sources: [apps/web/lib/api/fraud/hold-pending-commissions.ts:92-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-pending-commissions.ts#L92-L96)
Sources: [apps/web/lib/api/fraud/hold-processed-commissions.ts:110-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-processed-commissions.ts#L110-L114)
### Migration Backfills and Settlement Synchronization
Historical risk groups are remediated via dedicated migration scripts (`backfill-hold-pending-commissions.ts` and `backfill-hold-processed-commissions.ts`). These routines iterate through pending fraud event groups in batches of 50, dividing rules into partner-level and customer-level categories to construct targeted Prisma queries.
```typescript
const BATCH_SIZE = 50;
type PartnerLevelFraudRule = (typeof PARTNER_LEVEL_FRAUD_RULES)[number];
type CustomerLevelFraudRule = (typeof CUSTOMER_LEVEL_FRAUD_RULES)[number];
const holdEligibleWhere: Prisma.CommissionWhereInput = {
status: CommissionStatus.pending,
earnings: {
gt: 0,
},
program: {
workspace: {
plan: {
in: ["enterprise", "advanced"],
},
},
},
};
```
Sources: [apps/web/scripts/migrations/backfill-hold-pending-commissions.ts:13-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/migrations/backfill-hold-pending-commissions.ts#L13-L30)
| Migration Script | Target Status | Payout Association | Additional Post-Processing |
| :--- | :--- | :--- | :--- |
| `backfill-hold-pending-commissions.ts` | `CommissionStatus.pending` | Unrestricted by payout status | `trackCommissionStatusUpdate`, `syncTotalCommissions` |
| `backfill-hold-processed-commissions.ts` | `CommissionStatus.processed` | `PayoutStatus.pending` (sets `payoutId: null`) | `retallyPayoutsAmount`, activity logging, total sync |
Sources: [apps/web/scripts/migrations/backfill-hold-pending-commissions.ts:18-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/migrations/backfill-hold-pending-commissions.ts#L18-L30)
Sources: [apps/web/scripts/migrations/backfill-hold-processed-commissions.ts:24-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/migrations/backfill-hold-processed-commissions.ts#L24-L39)
Sources: [apps/web/scripts/migrations/backfill-hold-processed-commissions.ts:240](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/migrations/backfill-hold-processed-commissions.ts#L240)
When commissions are transitioned to hold status, the system groups them by program identifier to record entries via `trackCommissionStatusUpdate`, and recalculates partner totals using `syncTotalCommissions` across all affected program-partner pairs.
```typescript
// Activity logs are scoped to a workspace + program, so batch by program.
const commissionsByProgram = groupBy(heldCommissions, (c) => c.programId);
for (const commissions of Object.values(commissionsByProgram)) {
const { id: programId, workspaceId } = commissions[0].program;
await trackCommissionStatusUpdate({
workspaceId,
programId,
commissions,
newStatus: CommissionStatus.hold,
});
}
const affectedPairs = [
...new Map(
heldCommissions.map((c) => [
`${c.programId}:${c.partnerId}`,
{ programId: c.programId, partnerId: c.partnerId },
]),
).values(),
];
await Promise.all(
affectedPairs.map(({ programId, partnerId }) =>
syncTotalCommissions({
programId,
partnerId,
}),
),
);
```
Sources: [apps/web/lib/api/fraud/hold-pending-commissions.ts:116-146](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-pending-commissions.ts#L116-L146)
Sources: [apps/web/lib/api/fraud/hold-processed-commissions.ts:134-165](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/fraud/hold-processed-commissions.ts#L134-L165)
## Program Risk Management Interface
### Risk Center Layout and Feature Gating
The Risk Center page is available in enterprise and advanced workspaces under `/[slug]/program/risks`, delivering workspace-level visibility into partner risk events and automated monitoring rules. Access to these risk management features is governed by plan capabilities; workspaces lacking the required tier are intercepted by `FraudRiskLayout`, which renders `RiskCenterUpsell` instead of loading the dashboard components.
```tsx
export default function FraudRiskLayout({ children }: { children: ReactNode }) {
const { plan, loading } = useWorkspace();
if (loading) {
return ;
}
const { canManageFraudEvents } = getPlanCapabilities(plan);
if (!canManageFraudEvents) {
return ;
}
return children;
}
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/layout.tsx:9-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/layout.tsx#L9-L22)
The Risk Center view wraps its data layer inside `RiskEventsTable`, providing automatic background filtering, sorting via query parameters (`sortBy` and `sortOrder`), and expiration disclaimers. Unresolved risk events automatically expire after 30 days unless categorized as confirmed network-level bans.
```tsx
export function RiskDisclaimerBanner({ className }: { className?: string }) {
return (
We recommend reviewing the risk events thoroughly before taking action.
Unresolved events expire after 30 days, except confirmed network-level
bans.{" "}
Learn more
);
}
```
Sources: [apps/web/ui/partners/fraud-risks/risk-disclaimer-banner.tsx:3-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/risk-disclaimer-banner.tsx#L3-L17)
> [!WARNING]
> While standard risk events carry a 30-day expiration window, confirmed network-level bans bypass automatic expiration and remain enforced across the entire partner network.
Sources: [apps/web/ui/partners/fraud-risks/risk-disclaimer-banner.tsx:3-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/partners/fraud-risks/risk-disclaimer-banner.tsx#L3-L16)
### Risk Rules Configuration Sheet
Workspace administrators configure monitoring criteria using `RiskRulesSheet`, which interfaces with `/api/fraud/rules`. The form state distinguishes between complex configurable fraud rules with dedicated subcomponents and toggle-only rules that use standard switches.
```tsx
// Rules that have dedicated settings components with complex config UI
const RULES_WITH_CUSTOM_UI = new Set([
"paidTrafficDetected",
"referralSourceBanned",
]);
// Toggle-only rules rendered via the generic RiskRuleToggleSettings component
const TOGGLE_ONLY_RULES = CONFIGURABLE_FRAUD_RULES.filter(
(rule): rule is FraudRuleInfo & { type: keyof UpdateFraudRuleSettings } =>
!RULES_WITH_CUSTOM_UI.has(rule.type),
);
interface RiskRulesSheetProps {
setIsOpen: Dispatch>;
}
function RiskRulesSheetContent({ setIsOpen }: RiskRulesSheetProps) {
const { id: workspaceId } = useWorkspace();
const { isSubmitting, makeRequest } = useApiMutation();
const { data: fraudRules, isLoading } = useSWR(
workspaceId ? `/api/fraud/rules?workspaceId=${workspaceId}` : null,
fetcher,
);
const { setShowDisableModal, DisableRiskRulesModal } =
useDisableRiskRulesModal({ setIsOpen });
const form = useForm({
defaultValues: {
referralSourceBanned: {
enabled: false,
config: { domains: [] },
},
paidTrafficDetected: {
enabled: false,
config: { platforms: [], google: { whitelistedCampaignIds: [] } },
},
...Object.fromEntries(
TOGGLE_ONLY_RULES.map((rule) => [rule.type, { enabled: true }]),
),
},
});
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/risk-rules-sheet.tsx:32-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/risk-rules-sheet.tsx#L32-L73)
| Rule Type | Configuration Component | Default State | Config Structure |
| :--- | :--- | :--- | :--- |
| `referralSourceBanned` | `RiskReferralSourceSettings` | Disabled (`false`) | `{ domains: string[] }` |
| `paidTrafficDetected` | `RiskPaidTrafficSettings` | Disabled (`false`) | `{ platforms: PaidTrafficPlatform[], google: { whitelistedCampaignIds: string[] } }` |
| Toggle-only rules | `RiskRuleToggleSettings` | Enabled (`true`) | `{ enabled: boolean }` |
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/risk-rules-sheet.tsx:32-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/risk-rules-sheet.tsx#L32-L73)
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/risk-rules-sheet.tsx:185-195](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/risk-rules-sheet.tsx#L185-L195)
When a user attempts to disable active rules, `getRulesBeingDisabled` evaluates the configuration delta against previous settings. If any active rule is deactivated, the form halts direct submission and opens the disable confirmation modal before dispatching a PATCH request to the API.
```tsx
// Handle form submission
const onSubmit = async (body: UpdateFraudRuleSettings) => {
if (isLoading) {
return;
}
// First submit if no previous data exists
if (!fraudRules) {
await submitForm(body);
return;
}
// Detect rule disable transitions
const rulesBeingDisabled = getRulesBeingDisabled({
previousFraudRules: fraudRules,
nextFraudRules: body,
});
// If any rules are being disabled, show confirmation modal
if (rulesBeingDisabled.length > 0) {
setShowDisableModal(true);
return;
}
// Otherwise, submit directly
await submitForm(body);
};
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/program/risks/risk-rules-sheet.tsx:132-157](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/risks/risk-rules-sheet.tsx#L132-L157)
## Related
- [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine)
- [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement)
---
## Technical docs: Stripe App
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/stripe-app
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/stripe-app/stripe-app.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json)
- [packages/stripe-app/src/views/AppSettings.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/integrations/integrationSlug/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/integrations/%5BintegrationSlug%5D/page-client.tsx)
- [apps/web/ui/guides/install-stripe-integration-button.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/install-stripe-integration-button.tsx)
- [apps/web/app/ee/api/stripe/integration/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts)
- [apps/web/lib/discounts/discount-provider-stripe.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-stripe.ts)
- [packages/stripe-app/src/utils/constants.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/constants.ts)
- [apps/web/lib/integrations/stripe/update-stripe-settings.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/update-stripe-settings.ts)
- [apps/web/scripts/dev/data.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/data.json)
- [apps/web/app/api/callback/plain/partner/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/plain/partner/route.ts)
- [apps/web/lib/integrations/stripe/ui/settings.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/ui/settings.tsx)
- [apps/web/lib/discounts/discount-provider-shopify.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-shopify.ts)
- [apps/web/app/ee/api/shopify/integration/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/integration/callback/route.ts)
- [packages/hubspot-app/src/app/app-hsmeta.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/hubspot-app/src/app/app-hsmeta.json)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/tracking/installation-section.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/tracking/installation-section.tsx)
- [apps/web/scripts/stripe/backfill-discount-code-sales.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/backfill-discount-code-sales.ts)
- [apps/web/app/ee/api/stripe/integration/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/route.ts)
- [apps/web/app/ee/api/customers/search-stripe/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/customers/search-stripe/route.ts)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/program/partners/partnerId/links/discount-codes.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/program/partners/%5BpartnerId%5D/links/discount-codes.tsx)
- [apps/web/ui/modals/add-customer-modal.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/modals/add-customer-modal.tsx)
- [packages/stripe-app/package.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/package.json)
- [apps/web/app/ee/api/stripe/integration/webhook/promotion-code-updated.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts)
- [apps/web/scripts/stripe/connect-client.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/connect-client.ts)
- [packages/stripe-app/src/utils/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/dub.ts)
- [apps/web/lib/stripe/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/index.ts)
- [packages/stripe-app/src/utils/oauth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts)
- [packages/stripe-app/src/hooks/use-workspace.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/hooks/use-workspace.ts)
- [packages/hubspot-app/src/app/webhooks/webhooks-hsmeta.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/hubspot-app/src/app/webhooks/webhooks-hsmeta.json)
- [apps/web/lib/stripe/coupon-discount-converter.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts)
## Overview
The Stripe app integration bridges Dub with Stripe accounts, enabling automated [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking), bidirectional coupon synchronization, and merchant workspace management. By packaging a Stripe UI extension manifest with OAuth capabilities, it allows merchants to link their Dub workspaces directly from the Stripe dashboard, configure tracking preferences, and synchronize promotional discounts. The system securely handles webhook event pipelines for checkout sessions, subscriptions, and invoices, while offering customer lookup tools and historical sales backfill utilities to ensure accurate partner commission attribution.
Sources: [apps/web/scripts/dev/data.json:276-297](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/data.json#L276-L297), [packages/stripe-app/stripe-app.json:1-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L1-L91), [packages/stripe-app/src/views/AppSettings.tsx:24-198](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L24-L198), [apps/web/app/ee/api/stripe/integration/webhook/route.ts:22-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L22-L33), [apps/web/lib/discounts/discount-provider-stripe.ts:113-150](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-stripe.ts#L113-L150), [apps/web/lib/integrations/stripe/ui/settings.tsx:22-206](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/ui/settings.tsx#L22-L206), [apps/web/app/ee/api/customers/search-stripe/route.ts:11-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/customers/search-stripe/route.ts#L11-L91), [apps/web/scripts/stripe/backfill-discount-code-sales.ts:40-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/backfill-discount-code-sales.ts#L40-L111)
## Stripe App Manifest and Extensions
The Dub Stripe app configuration is defined in `packages/stripe-app/stripe-app.json`, identifying the package with ID `dub.co`, version `0.0.25`, and a public distribution type.
Sources: [packages/stripe-app/stripe-app.json:1-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L1-L21), [packages/stripe-app/stripe-app.json:88-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L88-L91)
The app declares a single settings view viewport mapped to the `AppSettings` component.
Sources: [packages/stripe-app/stripe-app.json:7-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L7-L13)
The Content Security Policy within the manifest restricts network connections to Dub's OAuth endpoints and Stripe integration API routes.
Sources: [packages/stripe-app/stripe-app.json:14-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L14-L21)
> [!IMPORTANT]
> The `connect-src` policy strictly limits outbound requests to `https://api.dub.co/oauth/` and `https://api.dub.co/stripe/integration`. Any unlisted endpoint calls made from the UI extension will be blocked by Stripe's runtime security container.
> Sources: [packages/stripe-app/stripe-app.json:14-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L14-L20)
The Stripe extension package uses React 19, the Stripe UI Extension SDK, and the Stripe Node library. Node version `>=14` is required under engine specifications.
Sources: [packages/stripe-app/package.json:7-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/package.json#L7-L15)
Core connection constants establish the client identifier and host URLs for communicating with the Dub platform from within the extension package.
Sources: [packages/stripe-app/src/utils/constants.ts:1-5](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/constants.ts#L1-L5)
The extension requests specific permission scopes to inspect customer records, subscriptions, invoices, charges, checkout sessions, and webhooks, alongside write capabilities for secrets, coupons, and promotion codes.
Sources: [packages/stripe-app/stripe-app.json:23-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L23-L80)
| Permission Scope | Purpose Description |
| :--- | :--- |
| `customer_read` | Allows Dub to read customer information. |
| `subscription_read` | Allows Dub to read subscription information. |
| `invoice_read` | Allows Dub to read invoice information. |
| `charge_read` | Allows Dub to read charges to detect refunded payments. |
| `checkout_session_read` | Allows Dub to read checkout session information. |
| `user_email_read` | Access current user's email address to identify within Dub. |
| `connected_account_read` | Allows reading basic data from connected accounts, such as account name and id. |
| `webhook_read` | Allows Dub to read webhook information. |
| `event_read` | Allows Dub to read event information. |
| `secret_write` | Allows storing Dub access tokens in Stripe for an account. |
| `coupon_write` | Allows Dub to create coupons for an account. |
| `coupon_read` | Allows Dub to read coupons for an account. |
| `promotion_code_write` | Allows Dub to create promotion codes for an account. |
| `promotion_code_read` | Allows Dub to read promotion codes for an account. |
Sources: [packages/stripe-app/stripe-app.json:23-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/stripe-app.json#L23-L80)
## Stripe Dashboard OAuth Handshake
```mermaid
sequenceDiagram
participant App as AppSettings View
participant Stripe as Stripe OAuth SDK
participant Dub as Dub API / Authorize
App->>Stripe: createOAuthState()
Stripe-->>App: Return state & challenge (S256)
App->>Dub: Redirect to GET /oauth/authorize (client_id, redirect_uri, code_challenge)
Dub-->>App: Redirect back with auth code & verifier (oauthContext)
App->>Dub: POST /oauth/token (authorization_code, code_verifier)
Dub-->>App: Return Token object (access_token, refresh_token)
App->>Dub: GET /oauth/userinfo (Bearer token)
Dub-->>App: Return Workspace object
App->>Dub: PATCH /stripe/integration (stripeAccountId, stripeMode)
```
Sources: [packages/stripe-app/src/views/AppSettings.tsx:30-139](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L30-L139), [packages/stripe-app/src/utils/oauth.ts:11-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L11-L88), [packages/stripe-app/src/utils/dub.ts:5-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/dub.ts#L5-L23)
The OAuth authorization handshake begins within the `AppSettings` component when no connected workspace exists in Stripe secrets and no active authorization code is present in the extension context.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:24-141](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L24-L141)
The component invokes `createOAuthState` from `@stripe/ui-extension-sdk/oauth` to generate a cryptographic state string and a PKCE code challenge.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:135-139](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L135-L139), [packages/stripe-app/src/views/AppSettings.tsx:30-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L30-L31)
When the merchant clicks the connect action in the `SignInView`, the app builds an authorization URL via `getOAuthUrl`.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:170-183](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L170-L183), [packages/stripe-app/src/utils/oauth.ts:11-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L11-L30)
The generated URL points to `${DUB_HOST}/oauth/authorize` and includes query parameters for `client_id`, `redirect_uri`, `response_type` set to `"code"`, `code_challenge`, `code_challenge_method` set to `"S256"`, and the generated `state`.
Sources: [packages/stripe-app/src/utils/oauth.ts:20-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L20-L29)
The redirect URI is dynamically calculated based on the Stripe mode using `getRedirectUrl`, pointing to `https://dashboard.stripe.com/apps-oauth/dub.co` for live mode or `https://dashboard.stripe.com/test/apps-oauth/dub.co` for test/sandbox modes.
Sources: [packages/stripe-app/src/utils/oauth.ts:6-8](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L6-L8), [packages/stripe-app/src/utils/oauth.ts:22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L22)
> [!WARNING]
> If `code` or `verifier` parameters are missing from `oauthContext` upon return from the authorization server, the `connectWorkspace` routine aborts execution immediately without persisting credentials or throwing an unhandled exception.
> Sources: [packages/stripe-app/src/views/AppSettings.tsx:78-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L78-L80)
Once the authorization server redirects back to the Stripe app with the authorization code and PKCE verifier (`oauthContext?.code` and `oauthContext?.verifier`), the `useEffect` hook detects the parameters and executes `connectWorkspace`.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:36-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L36-L37), [packages/stripe-app/src/views/AppSettings.tsx:127-131](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L127-L131), [packages/stripe-app/src/views/AppSettings.tsx:75-119](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L75-L119)
| Step Function | API Endpoint / Action | Description |
| :--- | :--- | :--- |
| `getToken` | `POST /oauth/token` | Exchanges the authorization code and PKCE `code_verifier` for access and refresh tokens using `application/x-www-form-urlencoded`. |
| `setSecret` (`dub_token`) | Stripe Secrets API | Stores the serialized token JSON payload securely within Stripe extension secrets. |
| `getUserInfo` | `GET /oauth/userinfo` | Fetches the user profile and associated workspace metadata from Dub using the `Bearer` access token. |
| `updateWorkspace` | `PATCH /stripe/integration` | Links the Dub workspace to the merchant's Stripe account by sending `stripeAccountId` and `stripeMode`. |
| `setSecret` (`dub_workspace`) | Stripe Secrets API | Stores the retrieved workspace metadata object securely as `dub_workspace`. |
Sources: [packages/stripe-app/src/views/AppSettings.tsx:82-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L82-L114), [packages/stripe-app/src/utils/dub.ts:14-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/dub.ts#L14-L23), [packages/stripe-app/src/utils/oauth.ts:43-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L43-L88)
> [!TIP]
> The `stripeMode` sent to `updateWorkspace` evaluates `userContext.account.isSandbox`. If the Stripe account is in sandbox mode, it resolves to `"sandbox"`; otherwise, it falls back to `environment.mode`.
> Sources: [packages/stripe-app/src/views/AppSettings.tsx:61-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L61-L63), [packages/stripe-app/src/views/AppSettings.tsx:106-108](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L106-L108)
To ensure continuous background operation without re-prompting merchants, `getValidToken` inspects stored tokens via `getSecret` for the `dub_token` key.
Sources: [packages/stripe-app/src/utils/oauth.ts:91-95](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L91-L95)
It validates the active token by calling `getUserInfo`. If the request fails due to expiration or revocation, it invokes `refreshToken` against `${DUB_API_HOST}/oauth/token` using the stored `refresh_token` and `grant_type: "refresh_token"`.
Sources: [packages/stripe-app/src/utils/oauth.ts:101-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L101-L105), [packages/stripe-app/src/utils/oauth.ts:123-137](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L123-L137)
If refreshing succeeds, the new token payload is persisted back to Stripe secrets under `dub_token` and returned to the caller. If refresh fails, `getValidToken` logs an error and returns `null`.
Sources: [packages/stripe-app/src/utils/oauth.ts:111-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L111-L118), [packages/stripe-app/src/utils/oauth.ts:106-109](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L106-L109)
When a merchant elects to disconnect their workspace from the `AppSettings` banner view, `disconnectWorkspace` triggers.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:40-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L40-L41), [packages/stripe-app/src/views/AppSettings.tsx:154-167](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L154-L167)
It retrieves a valid token, deletes both `dub_workspace` and `dub_token` secrets from Stripe in parallel using `Promise.all`, and issues an asynchronous `updateWorkspace` patch request with `accountId: null` to disassociate the Stripe account on the Dub backend.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:43-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L43-L65)
Finally, it invokes `mutate()` to refresh workspace hook state.
Sources: [packages/stripe-app/src/views/AppSettings.tsx:67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L67), [packages/stripe-app/src/views/AppSettings.tsx:161](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx#L161)
## Integration Settings and Workspace Management
The Dub dashboard exposes configuration interfaces and server actions for managing Stripe integration settings per workspace.
Sources: [apps/web/lib/integrations/stripe/update-stripe-settings.ts:21-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/update-stripe-settings.ts#L21-L60), [apps/web/lib/integrations/stripe/ui/settings.tsx:22-206](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/ui/settings.tsx#L22-L206)
The client interface is rendered via `IntegrationPageClient`, which resolves the correct settings component (`StripeIntegrationSettings`) using the `STRIPE_INTEGRATION_ID` constant.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/integrations/integrationSlug/page-client.tsx:72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/integrations/%5BintegrationSlug%5D/page-client.tsx#L72), [apps/web/app/app.dub.co/dashboard/slug/ee/settings/integrations/integrationSlug/page-client.tsx:121](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/integrations/%5BintegrationSlug%5D/page-client.tsx#L121)
When an integration is successfully connected, a dynamic connection banner displays the current operational mode: `live` (emerald background), `test` (blue background), or `sandbox` (orange background).
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/integrations/integrationSlug/page-client.tsx:123-158](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/integrations/%5BintegrationSlug%5D/page-client.tsx#L123-L158)
| Mode Variant | Background Class | Title Text | Icon Component |
| :--- | :--- | :--- | :--- |
| `live` | `bg-emerald-50` | Live Mode | `CheckCircleFill` |
| `test` | `bg-[#F0F7FF]` | Test Mode | `Flask` |
| `sandbox` | `bg-orange-50` | Sandbox Mode | `Flask` |
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/integrations/integrationSlug/page-client.tsx:133-154](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/integrations/%5BintegrationSlug%5D/page-client.tsx#L133-L154)
Workspaces requiring the integration can initialize installation via `InstallStripeIntegrationButton`.
Sources: [apps/web/ui/guides/install-stripe-integration-button.tsx:13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/install-stripe-integration-button.tsx#L13)
This component monitors active integrations using `useIntegrations` with a tailored polling interval (`5000`ms normally, falling back to `1000`ms when clicked).
Sources: [apps/web/ui/guides/install-stripe-integration-button.tsx:19-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/install-stripe-integration-button.tsx#L19-L24)
If the Stripe integration is not detected, it renders a required setup callout and a primary link pointing to `/[workspaceSlug]/settings/integrations/stripe`.
Sources: [apps/web/ui/guides/install-stripe-integration-button.tsx:47-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/install-stripe-integration-button.tsx#L47-L69)
> [!NOTE]
> The installation check hook continuously revalidates on focus unless `isEnabled` resolves to true. When clicked, it accelerates polling to every 1,000 milliseconds to promptly capture installation status updates.
> Sources: [apps/web/ui/guides/install-stripe-integration-button.tsx:19-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/install-stripe-integration-button.tsx#L19-L24)
Workspace settings updates are defined in `apps/web/lib/integrations/stripe/update-stripe-settings.ts`, wrapped with `authActionClient`.
Sources: [apps/web/lib/integrations/stripe/update-stripe-settings.ts:21-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/update-stripe-settings.ts#L21-L23)
The action validates inputs against a schema requiring `workspaceId`, a `freeTrials` configuration object containing boolean toggles for `enabled` and `trackQuantity`, and an optional `discountCodeRestrictions` object containing `firstTimeTransaction`.
Sources: [apps/web/lib/integrations/stripe/update-stripe-settings.ts:11-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/update-stripe-settings.ts#L11-L25)
It verifies that the user possesses `integrations.write` permissions via `throwIfNoPermission`, locates the installed integration record in Prisma, merges the settings payload, and calls `revalidatePath`.
Sources: [apps/web/lib/integrations/stripe/update-stripe-settings.ts:27-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/stripe/update-stripe-settings.ts#L27-L60)
Additionally, the backend exposes a `PATCH /api/stripe/integration` route restricted to business, advanced, and enterprise plans with owner or member roles.
Sources: [apps/web/app/ee/api/stripe/integration/route.ts:18-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/route.ts#L18-L19), [apps/web/app/ee/api/stripe/integration/route.ts:110-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/route.ts#L110-L112)
This endpoint parses request bodies for `stripeAccountId` and `stripeMode`, validates the token's `installationId`, updates the project's `stripeConnectId`, and uses Vercel's `waitUntil` helper to either delete the installation if `stripeAccountId` is `null` or update the installation settings with the new `stripeMode`.
Sources: [apps/web/app/ee/api/stripe/integration/route.ts:20-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/route.ts#L20-L89)
> [!WARNING]
> If a `P2002` unique constraint violation occurs during the project update (indicating the Stripe Connect account is already registered elsewhere), the API route throws a Dub API conflict error.
> Sources: [apps/web/app/(ee)/api/stripe/integration/route.ts:95-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/route.ts#L95-L101)
## Discount and Coupon Synchronization
Dub maps partner discount attributes between Dub and Stripe through dedicated converter utilities.
Sources: [apps/web/lib/stripe/coupon-discount-converter.ts:17-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts#L17-L47), [apps/web/lib/stripe/coupon-discount-converter.ts:52-83](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts#L52-L83)
The conversion handles percentage versus flat monetary amounts, currency constraints, and duration mappings.
Sources: [apps/web/lib/stripe/coupon-discount-converter.ts:20-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts#L20-L44), [apps/web/lib/stripe/coupon-discount-converter.ts:56-74](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts#L56-L74)
| Dub Max Duration | Stripe Coupon Duration | Duration In Months |
| :--- | :--- | :--- |
| `null` | `forever` | *undefined* |
| `0` | `once` | *undefined* |
| Positive integer ($N$) | `repeating` | $N$ |
Sources: [apps/web/lib/stripe/coupon-discount-converter.ts:24-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts#L24-L31)
> [!CAUTION]
> Amount-based flat coupons (`amount_off`) require `currency: "usd"` in Stripe. If a coupon specifies both `percent_off` and `amount_off`, or omits both entirely, validation fails.
> Sources: [apps/web/lib/stripe/coupon-discount-converter.ts:93-102](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/stripe/coupon-discount-converter.ts#L93-L102)
When creating discount codes for partner links via `createDiscountCode`, Dub connects to the Stripe API using the workspace's active mode and `stripeConnectId`.
Sources: [apps/web/lib/discounts/discount-provider-stripe.ts:152-167](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-stripe.ts#L152-L167)
It enforces first-time transaction restrictions configured in the workspace settings.
Sources: [apps/web/lib/discounts/discount-provider-stripe.ts:188-191](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-stripe.ts#L188-L191)
> [!TIP]
> If a generated discount code already exists in Stripe and `shouldRetry` is enabled, Dub automatically appends a 2-character nanoid suffix (`${currentCode}${nanoid(2)}`) and retries up to `MAX_ATTEMPTS` (3 times) before throwing a creation failure error.
> Sources: [apps/web/lib/discounts/discount-provider-stripe.ts:17-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-stripe.ts#L17-L21), [apps/web/lib/discounts/discount-provider-stripe.ts:199-218](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/discounts/discount-provider-stripe.ts#L199-L218)
Stripe promotion code updates are intercepted via the `promotion_code.updated` webhook handler.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/promotion-code-updated.ts:6-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts#L6-L14)
If a promotion code becomes inactive (`promotionCode.active` is false), the system looks up the corresponding record in the workspace's default program and removes it.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/promotion-code-updated.ts:22-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts#L22-L48)
## Merchant Webhook Processing Pipeline
The Stripe integration webhook endpoint (`POST /api/stripe/integration/webhook`) accepts incoming event notifications, verifies cryptographic signatures, and matches requests against the appropriate environment secret.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:36-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L36-L41), [apps/web/app/ee/api/stripe/integration/webhook/route.ts:64-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L64-L70)
Depending on the request path suffix, the webhook router selects either `STRIPE_APP_WEBHOOK_SECRET_TEST` (`/test`), `STRIPE_APP_WEBHOOK_SECRET_SANDBOX` (`/sandbox`), or the production `STRIPE_APP_WEBHOOK_SECRET` (`live`).
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:46-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L46-L55)
> [!CAUTION]
> If a test webhook event is received on the live webhook receiver endpoint (`!event.livemode && mode === "live"`), the event is explicitly dropped to prevent cross-mode pollution.
> Sources: [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:91-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L91-L97)
Dub tracks a specific subset of Stripe lifecycle events through `relevantEvents`, resolving the associated workspace via the event's `stripeConnectId` (`event.account`).
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:22-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L22-L33), [apps/web/app/ee/api/stripe/integration/webhook/route.ts:107-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L107-L118)
Events failing to match workspace records or unsupported types are skipped and acknowledged.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:79-85](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L79-L85), [apps/web/app/ee/api/stripe/integration/webhook/route.ts:120-125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L120-L125)
| Event Type | Handler / Action |
| :--- | :--- |
| `account.application.deauthorized` | `accountApplicationDeauthorized` |
| `charge.refunded` | `chargeRefunded` |
| `checkout.session.completed` | `checkoutSessionCompleted` |
| `coupon.deleted` | `couponDeleted` |
| `customer.created` | `syncCustomer` |
| `customer.updated` | `syncCustomer` |
| `customer.subscription.created` | `customerSubscriptionCreated` |
| `customer.subscription.deleted` | `customerSubscriptionDeleted` |
| `invoice.paid` | `invoicePaid` |
| `promotion_code.updated` | `promotionCodeUpdated` |
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:22-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L22-L33), [apps/web/app/ee/api/stripe/integration/webhook/route.ts:133-189](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L133-L189)
> [!TIP]
> If event execution throws a Stripe rate limit error (`isStripeRateLimitError`), the webhook handler catches it and returns HTTP status `429` with a warning log level so Stripe automatically retries the delivery instead of treating it as an internal server error (`500`).
> Sources: [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:191-204](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L191-L204)
## Customer Lookup and Historical Backfills
Workspace owners can query connected Stripe accounts by email directly from the Dub dashboard using the customer search endpoint (`GET /api/customers/search-stripe`).
Sources: [apps/web/app/ee/api/customers/search-stripe/route.ts:11-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/customers/search-stripe/route.ts#L11-L16)
The endpoint first validates that the workspace has an active Stripe connection ID and an installed Stripe integration containing valid settings.
Sources: [apps/web/app/ee/api/customers/search-stripe/route.ts:18-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/customers/search-stripe/route.ts#L18-L47)
Once the integration settings are verified, the server queries the connected Stripe account using the configured Stripe mode and maps matching customer records against the local database to ascertain whether customers already exist within Dub.
Sources: [apps/web/app/ee/api/customers/search-stripe/route.ts:49-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/customers/search-stripe/route.ts#L49-L88)
> [!WARNING]
> If the Stripe integration is not installed or the workspace lacks a connected Stripe account, the search endpoint throws a `bad_request` API error halting the customer search operation.
> Sources: [apps/web/app/(ee)/api/customers/search-stripe/route.ts:18-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/customers/search-stripe/route.ts#L18-L43)
The add customer modal interface provides a streamlined email lookup tool allowing merchants to search for customers inside their connected Stripe accounts.
Sources: [apps/web/ui/modals/add-customer-modal.tsx:251-291](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/modals/add-customer-modal.tsx#L251-L291)
When a valid email address is entered, the interface calls the search handler, displaying matching records alongside their Stripe identifier, subscription counts, and whether they are already registered on Dub.
Sources: [apps/web/ui/modals/add-customer-modal.tsx:229-234](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/modals/add-customer-modal.tsx#L229-L234), [apps/web/ui/modals/add-customer-modal.tsx:298-369](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/modals/add-customer-modal.tsx#L298-L369)
To recover partner sales and commissions skipped by webhooks prior to patch `#4609`—where matching checks failed when an external ID resolved to no Dub customer—administrators execute the historical backfill script (`apps/web/scripts/stripe/backfill-discount-code-sales.ts`).
Sources: [apps/web/scripts/stripe/backfill-discount-code-sales.ts:12-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/backfill-discount-code-sales.ts#L12-L22), [apps/web/scripts/stripe/backfill-discount-code-sales.ts:40-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/backfill-discount-code-sales.ts#L40-L59)
The script iterates through paid invoices created on or after `START_DATE`, verifying promotion codes against valid partner discount records, and verifies subscription creation dates before creating manual commissions.
Sources: [apps/web/scripts/stripe/backfill-discount-code-sales.ts:130-156](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/backfill-discount-code-sales.ts#L130-L156), [apps/web/scripts/stripe/backfill-discount-code-sales.ts:193-207](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/stripe/backfill-discount-code-sales.ts#L193-L207)
## Related
- [Workspace Subscriptions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/workspace-subscriptions)
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
---
## Technical docs: POST Mark partner as trusted
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/createadmintrustedpartner
## Request Body
Partner identification payload
## Responses
## Try It
---
## Technical docs: DELETE Remove partner trusted status
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/deleteadmintrustedpartner
## Request Body
Partner ID payload
## Responses
## Try It
---
## Technical docs: HubSpot & Intercom
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/hubspot-intercom
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/api/intercom/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/route.ts)
- [apps/web/app/ee/api/intercom/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/callback/route.ts)
- [apps/web/lib/integrations/hubspot/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts)
- [apps/web/app/ee/api/intercom/webhook/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/route.ts)
- [apps/web/app/ee/api/hubspot/webhook/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts)
- [apps/web/app/ee/api/hubspot/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/callback/route.ts)
- [apps/web/lib/integrations/intercom/forward-message.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/forward-message.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts)
- [apps/web/app/ee/api/cron/import/partnerstack/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/partnerstack/route.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/utils/sync-customer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts)
- [apps/web/app/api/ai/support-chat/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/ai/support-chat/route.ts)
- [apps/web/app/ee/api/intercom/webhook/health-check/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/health-check/route.ts)
- [apps/web/app/ee/api/cron/import/tolt/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/tolt/route.ts)
- [apps/web/app/ee/api/hubspot/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts)
- [apps/web/app/ee/api/cron/import/firstpromoter/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts)
- [apps/web/app/ee/api/cron/import/lemonsqueezy/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts)
- [apps/web/lib/integrations/intercom/client.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/client.ts)
- [apps/web/app/ee/api/intercom/webhook/process/conversation-admin-replied.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts)
- [apps/web/app/ee/api/intercom/webhook/uninstall/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/uninstall/route.ts)
- [apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts)
- [apps/web/lib/integrations/hubspot/track-sale.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-sale.ts)
- [apps/web/lib/integrations/hubspot/constants.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/constants.ts)
- [apps/web/lib/integrations/hubspot/update-hubspot-settings.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/update-hubspot-settings.ts)
- [apps/web/lib/integrations/intercom/schema.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/schema.ts)
- [apps/web/lib/integrations/hubspot/oauth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/oauth.ts)
- [apps/web/lib/integrations/hubspot/ui/settings.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/ui/settings.tsx)
- [apps/web/app/ee/api/intercom/webhook/verify-webhook-signature.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts)
- [apps/web/lib/integrations/hubspot/schema.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/schema.ts)
- [apps/web/lib/integrations/hubspot/api.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/api.ts)
- [apps/web/scripts/dev/seed-integration.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/seed-integration.ts)
## Overview
Dub features integrations with HubSpot and Intercom to synchronize CRM data, attribute conversions, and route partner communications directly within workspaces. The HubSpot integration handles OAuth authentication, automatic property provisioning, and webhook event processing via QStash to track leads and closed-won sales from contact and deal objects. Concurrently, the Intercom integration manages app installation workflows, HMAC signature verification, health checks, and bi-directional message routing between partners and workspace admins with attachment synchronization.
Sources: [apps/web/app/ee/api/hubspot/callback/route.ts:15-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/callback/route.ts#L15-L112), [apps/web/app/ee/api/hubspot/webhook/route.ts:12-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts#L12-L69), [apps/web/app/ee/api/intercom/callback/route.ts:16-125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/callback/route.ts#L16-L125), [apps/web/app/ee/api/intercom/webhook/route.ts:12-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/route.ts#L12-L41), [apps/web/app/ee/api/intercom/webhook/process/conversation-admin-replied.ts:33-133](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts#L33-L133), [apps/web/lib/integrations/hubspot/api.ts:111-134](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/api.ts#L111-L134)
## HubSpot OAuth and Schema Configuration
### OAuth Flow and Installation
The HubSpot OAuth implementation uses `HubSpotOAuthProvider` configured with specific authentication parameters, token endpoints, and requested permission scopes. During the OAuth callback at `/api/hubspot/callback`, authorization codes are exchanged for access and refresh tokens, workspace membership is verified, and only workspace owners are permitted to install the integration.
```typescript
export const hubSpotOAuthProvider = new HubSpotOAuthProvider({
name: "HubSpot",
clientId: process.env.HUBSPOT_CLIENT_ID!,
clientSecret: process.env.HUBSPOT_CLIENT_SECRET!,
authUrl: "https://app.hubspot.com/oauth/authorize",
tokenUrl: "https://api.hubapi.com/oauth/v1/token",
redirectUri: `${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`,
redisStatePrefix: "hubspot:oauth:state",
scopes: [
"oauth",
"crm.objects.contacts.read",
"crm.objects.contacts.write",
"crm.objects.deals.read",
"crm.schemas.contacts.write",
].join(" "),
tokenSchema: hubSpotAuthTokenSchema,
bodyFormat: "form",
authorizationMethod: "body",
});
```
Sources: [apps/web/lib/integrations/hubspot/oauth.ts:100-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/oauth.ts#L100-L118)
> [!WARNING]
> Only users with the `owner` role within a workspace are authorized to complete the HubSpot installation flow and store encrypted tokens.
Sources: [apps/web/app/ee/api/hubspot/callback/route.ts:70-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/callback/route.ts#L70-L76)
### Token Refresh Lifecycle
Token validation checks whether the current token has expired, incorporating a one-minute buffer (`60 * 1000` ms) before expiration to preemptively refresh credentials. When a token is invalid or expired, `refreshTokenForInstallation` requests a new token set from HubSpot, encrypts both access and refresh tokens before updating the database record.
```typescript
isTokenValid(token: HubSpotAuthToken) {
if (!token.created_at) {
return false;
}
const buffer = 60 * 1000; // refresh 1 min early
const expiresAt = token.created_at + token.expires_in * 1000;
return Date.now() < expiresAt - buffer;
}
```
Sources: [apps/web/lib/integrations/hubspot/oauth.ts:88-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/oauth.ts#L88-L97)
Uninstalling the HubSpot integration invokes an external deletion request against the HubSpot app installs API using a valid bearer token.
Sources: [apps/web/lib/integrations/hubspot/oauth.ts:54-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/oauth.ts#L54-L86)
### Custom Property Provisioning
Upon successful integration installation, Dub automatically provisions custom contact properties in HubSpot via a batch creation request to store attribution identifiers (`dub_id`, `dub_link`, and `dub_partner_email`).
| Property Label | Property Name | Type | Field Type | Group Name | Form Field |
| :--- | :--- | :--- | :--- | :--- | :--- |
| Dub Click ID | `dub_id` | string | text | contactinformation | `true` |
| Dub Link | `dub_link` | string | text | contactinformation | *undefined* |
| Dub Partner Email | `dub_partner_email` | string | text | contactinformation | *undefined* |
Sources: [apps/web/app/ee/api/hubspot/callback/route.ts:101-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/callback/route.ts#L101-L112), [apps/web/lib/integrations/hubspot/constants.ts:17-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/constants.ts#L17-L40)
## HubSpot Webhook Ingestion and Dispatch
### Signature Validation and Payload Fan-Out
HubSpot webhooks arrive at `/api/hubspot/webhook` carrying an `X-HubSpot-Signature` header. The route extracts the raw request body and verifies authenticity by hashing the concatenated string of `HUBSPOT_CLIENT_SECRET` and the raw body using SHA-256 (`crypto.createHash("sha256")`), comparing the resulting hex digest against the incoming signature header through constant-time comparison (`timingSafeCompare`). If the signature is absent, the environment secret is missing, or the comparison fails, a `DubApiError` (`bad_request`, `internal_server_error`, or `unauthorized`) is thrown and handled by `handleAndReturnErrorResponse`.
```typescript
export const POST = withAxiom(async (req) => {
try {
const rawBody = await req.text();
const signature = req.headers.get("X-HubSpot-Signature");
// Verify webhook signature
if (!signature) {
throw new DubApiError({
code: "bad_request",
message: "Missing X-HubSpot-Signature header.",
});
}
if (!HUBSPOT_CLIENT_SECRET) {
throw new DubApiError({
code: "internal_server_error",
message: "Missing HUBSPOT_CLIENT_SECRET environment variable.",
});
}
// Create expected hash: client_secret + request_body
const sourceString = HUBSPOT_CLIENT_SECRET + rawBody;
const expectedHash = crypto
.createHash("sha256")
.update(sourceString)
.digest("hex");
// Compare with provided signature using constant-time comparison
if (!timingSafeCompare(signature, expectedHash)) {
throw new DubApiError({
code: "unauthorized",
message: "Invalid webhook signature.",
});
}
```
Sources: [apps/web/app/ee/api/hubspot/webhook/route.ts:12-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts#L12-L46)
Once verified, the payload is parsed as an array (or normalized to a single-element array if received as an object). Because HubSpot can transmit multiple events in a single HTTP request, the endpoint fans out the events to QStash by invoking `enqueueBatchJobs`. Each enqueued job targets `/api/hubspot/webhook/process` via a POST request with the queue name `"process-hubspot-webhook"`, using `event.eventId` as the deduplication ID.
```typescript
const events = JSON.parse(rawBody) as any[];
const finalEvents = Array.isArray(events) ? events : [events];
// HubSpot can send multiple events in a single request, so we fan them out
// to QStash and process each event independently in /api/hubspot/webhook/process.
// This keeps the webhook handler fast and ensures a slow/failing event doesn't
// block or fail the rest of the batch.
const qstashResponse = await enqueueBatchJobs(
finalEvents.map((event) => ({
queueName: "process-hubspot-webhook",
url: `${APP_DOMAIN_WITH_NGROK}/api/hubspot/webhook/process`,
deduplicationId: event.eventId,
method: "POST",
body: event,
})),
);
console.log(
`[hubspot/webhook] Enqueued ${finalEvents.length} webhook events to be processed.`,
qstashResponse,
);
return logAndRespond("Webhook received.");
```
Sources: [apps/web/app/ee/api/hubspot/webhook/route.ts:47-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts#L47-L69)
> [!WARNING]
> Fanning out webhook batches individually to QStash ensures that a slow or failing event in a batch does not block or fail the remaining events.
Sources: [apps/web/app/ee/api/hubspot/webhook/route.ts:50-53](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts#L50-L53)
### Event Processing and Action Routing
The `/api/hubspot/webhook/process` route receives each individual event from QStash, verifies the incoming QStash signature using `verifyQstashSignature`, and parses the body via `hubSpotWebhookSchema` to extract `objectTypeId`, `portalId`, and `subscriptionType`. It queries Prisma for an installed installation where the credential path `$.hub_id` matches the `portalId` and the integration slug is `"hubspot"`, loading the associated workspace project (`id`, `stripeConnectId`, `webhookEnabled`).
```typescript
export const POST = withAxiom(async (req) => {
const startTime = Date.now();
let body: any;
let workspace:
| Pick
| undefined;
try {
const rawBody = await req.text();
await verifyQstashSignature({
req,
rawBody,
});
body = JSON.parse(rawBody);
const { objectTypeId, portalId, subscriptionType } =
hubSpotWebhookSchema.parse(body);
// Find the installation
const installation = await prisma.installedIntegration.findFirst({
where: {
integration: {
slug: "hubspot",
},
credentials: {
path: "$.hub_id",
equals: portalId,
},
},
include: {
project: {
select: {
id: true,
stripeConnectId: true,
webhookEnabled: true,
},
},
},
});
if (!installation) {
return logAndRespond(
`[HubSpot] Installation is not found for portalId ${portalId}.`,
);
}
workspace = installation.project;
```
Sources: [apps/web/app/ee/api/hubspot/webhook/process/route.ts:18-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts#L18-L68)
After refreshing the OAuth token via `hubSpotOAuthProvider.refreshTokenForInstallation(installation)` and parsing integration settings through `hubSpotSettingsSchema`, `getHubSpotEventAction` evaluates the event against the workspace configuration to determine whether to track a lead, track a sale, or skip the event.
```typescript
export function getHubSpotEventAction({
event,
settings,
}: {
event: Pick<
z.infer,
"objectTypeId" | "subscriptionType" | "propertyName" | "propertyValue"
>;
settings: z.infer;
}): "trackLead" | "trackSale" | "skip" {
```
Sources: [apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts:5-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts#L5-L14)
The evaluation rules depend on the CRM object type ID (`0-1` for contacts and `0-3` for deals) and the subscription type (`object.creation` or `object.propertyChange`):
| Object Type ID | Subscription Type | Property Name | Condition | Action Result |
| :--- | :--- | :--- | :--- | :--- |
| `0-1` (Contact) | `object.creation` | *any* | Contact created | `trackLead` |
| `0-1` (Contact) | `object.propertyChange` | *any* | `leadTriggerEvent === "lifecycleStageReached"` | `trackLead` |
| `0-3` (Deal) | `object.creation` | *any* | `leadTriggerEvent === "dealCreated"` | `trackLead` |
| `0-3` (Deal) | `object.propertyChange` | `dealstage` | `leadTriggerEvent === "dealStageReached"` and `newDealStage === leadDealStageId` | `trackLead` |
| `0-3` (Deal) | `object.propertyChange` | `dealstage` | `newDealStage === closedWonDealStageId` | `trackSale` |
| *other* | *any* | *any* | Does not match configured trigger criteria | `skip` |
Sources: [apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts:22-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts#L22-L69)
## HubSpot Contact and Deal Tracking
### Deferred Lead Tracking and Lifecycle Triggers
When a new HubSpot contact is created (`objectTypeId === "0-1"` and `subscriptionType === "object.creation"`), the tracking pipeline fetches the contact record via `hubSpotApi.getContact(objectId)` and verifies that the `dub_id` custom property is present on the contact properties. If present, it executes a deferred lead event by invoking `trackLead` with `mode: "deferred"`, `source: "hubspot"`, and `commissionSource: CommissionSource.hubspot`, pulling first and last name properties to assemble the customer name.
```typescript
// A new contact is created (deferred lead tracking)
if (objectTypeId === "0-1" && subscriptionType === "object.creation") {
const contactInfo = await hubSpotApi.getContact(objectId);
if (!contactInfo) {
return `No contact info found for contact ${objectId}.`;
}
const { properties } = contactInfo;
if (!properties.dub_id) {
return `No dub_id found for contact ${objectId}.`;
}
const customerName =
[properties.firstname, properties.lastname].filter(Boolean).join(" ") ||
null;
const trackLeadResult = await trackLead({
clickId: properties.dub_id,
eventName: "Sign up",
customerEmail: properties.email,
customerExternalId: properties.email,
customerName,
mode: "deferred",
workspace,
source: "hubspot",
commissionSource: CommissionSource.hubspot,
});
if (trackLeadResult) {
await updateHubSpotContact({
contact: contactInfo,
trackLeadResult,
hubSpotApi,
});
}
return `Deferred lead tracked for contact ${objectId}.`;
}
```
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:33-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L33-L72)
When a contact's lifecycle stage reaches the configured target (`leadTriggerEvent === "lifecycleStageReached"`), the handler verifies that the contact's `lifecyclestage` property matches `settings.leadLifecycleStageId` case-insensitively. It queries Prisma for an existing customer matching either the HubSpot contact ID or email address, and tracks an asynchronous lead event via `trackLead` using `mode: "async"`.
```typescript
// Case 2: When the contact's lifecycle stage is changed to a qualified lead
if (
objectTypeId === "0-1" &&
subscriptionType === "object.propertyChange" &&
settings.leadTriggerEvent === "lifecycleStageReached"
) {
if (!settings.leadLifecycleStageId) {
return `leadLifecycleStageId is not set.`;
}
const contactInfo = await hubSpotApi.getContact(objectId);
if (!contactInfo) {
return `No contact info found for contact ${objectId}.`;
}
const { properties } = contactInfo;
if (
properties.lifecyclestage?.toLowerCase() !==
settings.leadLifecycleStageId?.toLowerCase()
) {
return `Unknown contact lifecyclestage ${properties.lifecyclestage}. Expected ${settings.leadLifecycleStageId}.`;
}
if (!properties.dub_id) {
return `No dub_id found for contact ${objectId}.`;
}
const customer = await prisma.customer.findFirst({
where: {
projectId: workspace.id,
OR: [{ externalId: contactInfo.id }, { externalId: properties.email }],
},
});
const trackLeadResult = await trackLead({
clickId: properties.dub_id,
eventName: `Contact ${properties.lifecyclestage}`,
customerExternalId: customer?.externalId || properties.email,
customerName: `${properties.firstname} ${properties.lastname}`,
customerEmail: properties.email,
mode: "async",
workspace,
source: "hubspot",
commissionSource: CommissionSource.hubspot,
});
if (trackLeadResult) {
await updateHubSpotContact({
contact: contactInfo,
trackLeadResult,
hubSpotApi,
});
}
return `Lead tracked for contact ${objectId}.`;
}
```
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:117-174](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L117-L174)
> [!WARNING]
> Deferred lead tracking strictly requires the contact to possess a valid `dub_id` property populated; if `dub_id` is absent, the event aborts without tracking a lead.
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:43-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L43-L45)
### Deal-Driven Lead and Sale Attribution
Deals (`objectTypeId === "0-3"`) drive both lead creation and revenue attribution depending on workspace settings and property change events. When `leadTriggerEvent` is configured to `"dealCreated"` upon deal creation, or `"dealStageReached"` when the `dealstage` property matches `settings.leadDealStageId`, `trackFinalLead` retrieves the deal object along with its associated contacts via `hubSpotApi.getDeal(dealId)`.
```typescript
// Track the final lead event
// Case 1: A deal is created for the contact
if (
objectTypeId === "0-3" &&
subscriptionType === "object.creation" &&
settings.leadTriggerEvent === "dealCreated"
) {
return trackFinalLead({
dealId: objectId,
workspace,
hubSpotApi,
});
}
// Track the final lead event
// Case 3: A deal reaches the configured lead deal stage
if (
objectTypeId === "0-3" &&
subscriptionType === "object.propertyChange" &&
settings.leadTriggerEvent === "dealStageReached"
) {
if (!settings.leadDealStageId) {
return `leadDealStageId is not set.`;
}
if (propertyName !== "dealstage") {
return `Unknown propertyName ${propertyName}. Expected dealstage.`;
}
if (
propertyValue?.toLowerCase() !== settings.leadDealStageId.toLowerCase()
) {
return `Unknown propertyValue ${propertyValue}. Expected ${settings.leadDealStageId}.`;
}
return trackFinalLead({
dealId: objectId,
workspace,
hubSpotApi,
});
}
```
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:74-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L74-L114)
```typescript
// Track the final lead for the first contact associated with a deal
const trackFinalLead = async ({
dealId,
workspace,
hubSpotApi,
}: {
dealId: number;
workspace: Pick;
hubSpotApi: HubSpotApi;
}) => {
const deal = await hubSpotApi.getDeal(dealId);
if (!deal) {
return `No deal found for deal ${dealId}.`;
}
const { properties, associations } = deal;
// Find the contact associated with the deal
const contact = associations?.contacts?.results?.[0];
if (!contact) {
return `No contact found for deal ${dealId}.`;
}
// HubSpot doesn't return the contact properties in the deal associations,
// so we need to get it separately
const contactInfo = await hubSpotApi.getContact(contact.id);
if (!contactInfo) {
return `No contact info found for contact ${contact.id}.`;
}
const customer = await prisma.customer.findFirst({
where: {
projectId: workspace.id,
OR: [
{ email: contactInfo.properties.email },
{ externalId: contactInfo.id },
{ externalId: contactInfo.properties.email },
],
},
});
if (!customer) {
return `No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`;
}
const trackLeadResult = await trackLead({
clickId: "",
eventName: `Deal ${properties.dealstage}`,
customerExternalId: customer.externalId!,
```
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:179-230](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L179-L230)
For revenue tracking, `trackHubSpotSaleEvent` listens for `object.propertyChange` events on the `dealstage` property where the new value matches `settings.closedWonDealStageId`. After retrieving the deal and its associated primary contact via `hubSpotApi.getDeal` and `hubSpotApi.getContact`, it validates that the deal amount property is set. It then queries Prisma for the corresponding customer record using either email or contact ID identifiers, and invokes `trackSale` with an amount scaled to cents (multiplied by 100), custom payment processor settings, and metadata containing both `hubspotDealId` and `hubspotContactId`.
```typescript
export const trackHubSpotSaleEvent = async ({
payload,
workspace,
authToken,
settings,
}: {
payload: Record;
workspace: Pick;
authToken: HubSpotAuthToken;
settings: z.infer;
}) => {
const { objectId, subscriptionType, propertyName, propertyValue } =
hubSpotSaleEventSchema.parse(payload);
if (subscriptionType !== "object.propertyChange") {
return `Unknown subscriptionType ${subscriptionType}.`;
}
if (propertyName !== "dealstage") {
return `Unknown propertyName ${propertyName}. Expected dealstage.`;
}
if (
propertyValue.toLowerCase() !== settings.closedWonDealStageId?.toLowerCase()
) {
return `Unknown propertyValue ${propertyValue}. Expected ${settings.closedWonDealStageId}.`;
}
const hubSpotApi = new HubSpotApi({
token: authToken.access_token,
});
const deal = await hubSpotApi.getDeal(objectId);
if (!deal) {
return `No deal found for deal ${objectId}`;
}
const { id: dealId, properties, associations } = deal;
if (!properties.amount) {
return `Amount is not set for deal ${dealId}`;
}
// Find the contact associated with the deal
const contact = associations?.contacts?.results?.[0];
if (!contact) {
return `No contact associated with deal ${dealId}`;
}
// HubSpot doesn't return the contact properties in the deal associations,
// so we need to get it separately
const contactInfo = await hubSpotApi.getContact(contact.id);
if (!contactInfo) {
return `No contact info found for contact ${contact.id}`;
}
const customer = await prisma.customer.findFirst({
where: {
projectId: workspace.id,
OR: [
{ email: contactInfo.properties.email },
{ externalId: contactInfo.id },
{ externalId: contactInfo.properties.email },
],
},
});
if (!customer) {
return `No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`;
}
await trackSale({
customerExternalId: customer.externalId!,
amount: Number(properties.amount) * 100,
eventName: `${properties.dealname} ${properties.dealstage}`,
paymentProcessor: "custom",
invoiceId: dealId,
```
Sources: [apps/web/lib/integrations/hubspot/track-sale.ts:10-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-sale.ts#L10-L100)
> [!NOTE]
> Deal-based lead and sale tracking inspects the first associated contact on the deal (`associations.contacts.results[0]`) and performs a secondary API fetch (`hubSpotApi.getContact`) because deal associations do not include contact property payloads.
Sources: [apps/web/lib/integrations/hubspot/track-lead.ts:197-206](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts#L197-L206), [apps/web/lib/integrations/hubspot/track-sale.ts:54-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-sale.ts#L54-L63)
## Intercom OAuth and Webhook Ingestion
### OAuth Installation Flow
The Intercom OAuth authorization flow is initiated via `GET /api/intercom/callback`. The endpoint first verifies the active user session and validates that the authenticated user holds an `owner` role within the target workspace. It also enforces plan capabilities by checking that `getPlanCapabilities(workspace.plan).canInstallAdvancedIntegrations` evaluates to true. After exchanging the authorization code for an access token via `intercomOAuthProvider.exchangeCodeForToken`, the handler queries the Intercom API for admin credentials to obtain the unique `appId` (`admin.app?.id_code`). The credentials are encrypted and stored via `installIntegration`, and the user is redirected to `/${workspace.slug}/settings/integrations/intercom`.
```typescript
try {
const session = await getSession();
if (!session?.user.id) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized. Please login to continue.",
});
}
const { token, contextId: workspaceId } =
await intercomOAuthProvider.exchangeCodeForToken(req);
workspace = await prisma.project.findUniqueOrThrow({
where: {
id: workspaceId,
},
select: {
id: true,
slug: true,
plan: true,
users: {
where: {
userId: session.user.id,
},
select: {
role: true,
defaultFolderId: true,
},
},
},
});
if (workspace.users.length === 0) {
throw new DubApiError({
code: "bad_request",
message: "You are not a member of this workspace.",
});
}
if (workspace.users[0].role !== "owner") {
throw new DubApiError({
code: "bad_request",
message: "Only workspace owners can install integrations.",
});
}
if (!getPlanCapabilities(workspace.plan).canInstallAdvancedIntegrations) {
throw new DubApiError({
code: "forbidden",
message:
"Intercom integration is only available on Advanced and Enterprise plans.",
});
}
const integration = await prisma.integration.findUniqueOrThrow({
where: {
id: INTERCOM_INTEGRATION_ID,
},
select: {
id: true,
},
});
const intercom = new Intercom({
token: token.access_token,
});
const admin = await intercom.getAdmin();
if (!admin.app?.id_code) {
throw new DubApiError({
code: "internal_server_error",
message: "Failed to retrieve Intercom workspace ID.",
});
}
const credentials = intercomCredentialsSchema.parse({
accessToken: encrypt(token.access_token),
appId: admin.app?.id_code,
```
Sources: [apps/web/app/ee/api/intercom/callback/route.ts:33-125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/callback/route.ts#L33-L125)
> [!CAUTION]
> Only workspace members with an `owner` role can successfully install the Intercom integration; non-owner member requests throw a `bad_request` error and abort installation.
Sources: [apps/web/app/ee/api/intercom/callback/route.ts:73-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/callback/route.ts#L73-L78)
### Webhook Verification and Event Dispatch
Intercom webhook events arriving at `POST /api/intercom/webhook` are processed by verifying the request signature, parsing the payload against `intercomWebhookSchema`, and evaluating the event topic. The webhook handler restricts processing to `relevantTopics`, which is defined as a set containing `conversation.admin.replied` and `ping`.
```typescript
const relevantTopics = new Set(["conversation.admin.replied", "ping"]);
```
Sources: [apps/web/app/ee/api/intercom/webhook/route.ts:9-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/route.ts#L9-L21)
When a `ping` topic is received, the endpoint acknowledges the event without further action. For conversation reply events, the payload is enqueued into QStash using a batch job configuration pointing to `/api/intercom/webhook/process` with the queue name `process-intercom-webhook`.
Sources: [apps/web/app/ee/api/intercom/webhook/route.ts:23-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/route.ts#L23-L41)
### Webhook Signature Verification
Intercom webhook requests authenticate payloads using cryptographic HMAC signatures transmitted via specific HTTP headers. The `verifyIntercomWebhookSignature` function inspects incoming headers to determine the expected signature scheme based on whether an `X-Hub-Signature` or `X-Body-Signature` header is present.
Sources: [apps/web/app/ee/api/intercom/webhook/verify-webhook-signature.ts:7-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts#L7-L27)
| Header | Hash Algorithm | Target Payload | Purpose |
| :--- | :--- | :--- | :--- |
| `X-Hub-Signature` | `sha1` (prefixed with `sha1=`) | Raw request body | Standard webhook event verification |
| `X-Body-Signature` | `sha256` (hex digest) | Raw request body | Uninstall and health-check verification |
Sources: [apps/web/app/ee/api/intercom/webhook/verify-webhook-signature.ts:32-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts#L32-L48)
The computed signature is compared against the provided header value using `timingSafeCompare` to prevent timing attacks. If the `INTERCOM_CLIENT_SECRET` environment variable is unset, or if neither signature header is supplied, the utility throws an API error.
Sources: [apps/web/app/ee/api/intercom/webhook/verify-webhook-signature.ts:14-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts#L14-L60)
### Health Check and Uninstall Workflows
Intercom monitors app health and lifecycle events through dedicated webhook endpoints. The health check endpoint (`POST /api/intercom/webhook/health-check`) parses the workspace identifier using `intercomHealthCheckWebhookSchema` and queries Prisma for an installed integration where `credentials.appId` matches the Intercom workspace ID. If no valid installation or credential schema match is found, it returns an `UNHEALTHY` status response with configuration call-to-action details; otherwise, it reports `OK`.
Sources: [apps/web/app/ee/api/intercom/webhook/health-check/route.ts:13-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/health-check/route.ts#L13-L62)
The uninstall endpoint (`POST /api/intercom/webhook/uninstall`) parses `app_id` via `intercomUninstallWebhookSchema`, locates the corresponding database record using the same JSON path query on credentials (`$.appId`), and deletes the `InstalledIntegration` entry to revoke access when an app is uninstalled or disconnected in Intercom.
Sources: [apps/web/app/ee/api/intercom/webhook/uninstall/route.ts:10-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/uninstall/route.ts#L10-L45)
## Intercom Bi-Directional Message Routing
### Forwarding Partner and Admin Messages
Dub bridges communication between partner portals and Intercom conversations by routing messages bi-directionally. When a partner sends a message, `forwardPartnerMessageToIntercom` looks up or creates a contact via `intercom.getOrCreateContact(partner)` and queries Redis for an existing thread key structured as `intercom:thread:${credentials.appId}:${program.id}:${partner.id}`. If no conversation ID is cached, a new conversation is initialized using `intercom.createConversationAsContact`.
Sources: [apps/web/lib/integrations/intercom/forward-message.ts:43-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/forward-message.ts#L43-L64)
```mermaid
sequenceDiagram
participant Partner as Partner Portal
participant Dub as Dub API
participant Redis as Upstash Redis
participant Intercom as Intercom API
Partner->>Dub: Send message with attachments
Dub->>Intercom: Get or create contact by email
Dub->>Redis: Check thread key intercom:thread:{appId}:{programId}:{partnerId}
alt Conversation ID Exists
Dub->>Intercom: Reply to existing conversation ID
else No Conversation Exists
Dub->>Intercom: Create new conversation
Intercom-->>Dub: Return conversation_id
Dub->>Redis: Store conversation_id in Redis
end
```
Sources: [apps/web/lib/integrations/intercom/forward-message.ts:47-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/forward-message.ts#L47-L79)
> [!WARNING]
> Intercom's API honors only one of `attachment_urls` or `attachment_files` per reply; supplying both causes Intercom to keep the URLs and silently drop inline files. To prevent data loss on mixed-content messages, Dub evaluates attachments before dispatch.
Sources: [apps/web/lib/integrations/intercom/forward-message.ts:181-187](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/forward-message.ts#L181-L187)
The `buildIntercomAttachments` helper inspects message attachments stored in private R2 storage and applies distinct encoding strategies depending on whether all attached files are images.
| Attachment Condition | Transfer Method | Payload Parameter | Purpose |
| :--- | :--- | :--- | :--- |
| All attachments are images (`image/*`) | Signed download URLs (30-minute expiry) | `attachment_urls` | Lightweight delivery accepted by creation endpoints |
| Mixed content (e.g., image + PDF) | Inline base64-encoded buffers | `attachment_files` | Ensures non-image files are delivered without dropping data |
Sources: [apps/web/lib/integrations/intercom/forward-message.ts:188-222](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/intercom/forward-message.ts#L188-L222)
### Ingesting Admin Replies and Attachment Sync
When an admin replies inside Intercom, a webhook event with topic `conversation.admin.replied` is dispatched to `POST /api/intercom/webhook/process`. The processor verifies the QStash signature, validates the body against `intercomWebhookSchema`, and queries the database for an `InstalledIntegration` matching the Intercom `app_id`.
Sources: [apps/web/app/ee/api/intercom/webhook/process/route.ts:21-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/route.ts#L21-L42)
Sources: [apps/web/app/ee/api/intercom/webhook/process/route.ts:87-93](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/route.ts#L87-L93)
The `handleConversationAdminReplied` function identifies target partners by inspecting `data.item.contacts.contacts` and fetching their corresponding email addresses from Intercom. Conversation parts created via the Intercom API (identified by a non-null `app_package_code`) are skipped to prevent echoing messages back.
Sources: [apps/web/app/ee/api/intercom/webhook/process/conversation-admin-replied.ts:44-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts#L44-L70)
> [!NOTE]
> Workspace user attribution resolves in a strict three-tier fallback sequence: matching `author.email` to project users, falling back to the user ID who installed the integration (`installation.userId`), and finally defaulting to the first project owner.
Sources: [apps/web/app/ee/api/intercom/webhook/process/conversation-admin-replied.ts:193-207](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts#L193-L207)
Incoming Intercom attachments are validated against `UPLOAD_POLICIES.programMessageAttachments` content types and size limits, downloaded with a 30-second timeout, and uploaded to the private R2 bucket under `messages/{programId}/{nanoid}/{filename}`. If an attachment fails storage, its external URL is appended to the message text as a fallback. Finally, partner notifications are scheduled via QStash with a 3-minute delay.
Sources: [apps/web/app/ee/api/intercom/webhook/process/conversation-admin-replied.ts:92-157](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts#L92-L157)
## Related
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
---
## Technical docs: Ad Conversion Sync
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/ad-conversion-sync
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/lib/integrations/google-ads/upload-conversion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts)
- [apps/web/app/ee/api/singular/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts)
- [apps/web/app/ee/api/appsflyer/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts)
- [apps/web/app/ee/api/track/application/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/application/route.ts)
- [apps/web/app/ee/api/google-ads/upload-conversion/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/upload-conversion/route.ts)
- [apps/web/lib/integrations/google-ads/api.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/api.ts)
- [apps/web/app/ee/api/google-ads/conversion-actions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/conversion-actions/route.ts)
- [apps/web/app/ee/api/track/lead/client/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/lead/client/route.ts)
- [apps/web/app/ee/api/google-ads/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/callback/route.ts)
- [apps/web/lib/auth/track-dub-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/track-dub-lead.ts)
- [apps/web/app/ee/api/cron/framer/backfill-leads-batch/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/framer/backfill-leads-batch/route.ts)
- [apps/web/app/ee/api/shopify/pixel/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts)
- [apps/web/app/ee/api/track/sale/client/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/client/route.ts)
- [apps/web/app/ee/api/track/lead/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/lead/route.ts)
- [apps/web/app/api/dub/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts)
- [apps/web/scripts/dev/simulate-shopify-conversion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/simulate-shopify-conversion.ts)
- [apps/web/app/ee/api/track/sale/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/track/sale/route.ts)
- [apps/web/scripts/programs/3-import-customer-leads.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/programs/3-import-customer-leads.ts)
- [apps/web/lib/api/conversions/track-sale.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts)
- [apps/web/scripts/dev/data.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/data.json)
- [apps/web/lib/api/conversions/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts)
- [apps/web/scripts/create-integration.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/create-integration.ts)
- [apps/web/lib/api/commissions/create-manual-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/commissions/create-manual-commissions.ts)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/lib/postback/postback-adapters.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts)
- [apps/web/lib/postback/record-postback-event.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/record-postback-event.ts)
- [apps/web/ui/guides/integrations.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/integrations.ts)
- [apps/web/lib/api/customers/reattribute-customer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/customers/reattribute-customer.ts)
- [apps/web/lib/integrations/hubspot/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/hubspot/track-lead.ts)
- [apps/web/lib/integrations/singular/track-lead.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/singular/track-lead.ts)
## Overview
Ad Conversion Sync synchronizes offline conversion events, mobile app attribution postbacks, and e-commerce checkouts back to advertising networks like Google Ads [apps/web/lib/integrations/google-ads/upload-conversion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts), AppsFlyer [apps/web/app/ee/api/appsflyer/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts), and Singular [apps/web/app/ee/api/singular/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts). It solves attribution fragmentation by bridging server-side conversion funnels, web pixel tracking [apps/web/app/ee/api/shopify/pixel/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts), and external marketing platforms into unified referral and partner commissions. Key design decisions include QStash-driven asynchronous queueing [apps/web/lib/integrations/google-ads/upload-conversion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts), strict IP range validation for webhooks [[apps/web/app/ee/api/appsflyer/webhook/route.ts], [apps/web/app/ee/api/singular/webhook/route.ts]], and custom postback adapters with cryptographic signing [apps/web/lib/postback/postback-adapters.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts). This subsystem interacts directly with Dub's core conversion and customer management modules to record and verify downstream event loops [[apps/web/lib/api/conversions/track-lead.ts], [apps/web/lib/api/conversions/track-sale.ts]].
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:1-177](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L1-L177), [apps/web/app/ee/api/shopify/pixel/route.ts:1-83](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L1-L83), [apps/web/app/ee/api/singular/webhook/route.ts:1-113](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L1-L113), [apps/web/lib/api/conversions/track-lead.ts:1-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-lead.ts#L1-L63), [apps/web/lib/api/conversions/track-sale.ts:1-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/conversions/track-sale.ts#L1-L62), [apps/web/lib/integrations/google-ads/upload-conversion.ts:1-98](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts#L1-L98), [apps/web/lib/postback/postback-adapters.ts:1-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L1-L69)
## Google Ads OAuth and Configuration
### Authorization and Account Discovery
The Google Ads integration follows an OAuth 2.0 authorization code flow initiated by workspace owners on Advanced and Enterprise plans. When a user authorizes the application, the callback route exchanges the authorization code for access and refresh tokens, encrypts the credentials using workspace secrets, and persists them via the integration installation module.
During the OAuth callback execution, the system instantiates the Google Ads API client using the newly acquired access token and invokes `listAccessibleCustomers` to retrieve all accessible customer accounts and manager hierarchies. If exactly one customer account is available, the integration auto-selects its descriptive name, account ID, and infers the correct login customer ID.
```typescript
const googleAdsApi = new GoogleAdsApi({
accessToken: token.access_token,
});
const customers = await googleAdsApi.listAccessibleCustomers();
let customerName: string | null = null;
let customerId: string | null = null;
let loginCustomerId: string | null = null;
// Just one customer, so we can use the first one
if (customers.length === 1) {
customerName = customers[0].descriptiveName;
customerId = customers[0].id;
loginCustomerId = inferLoginCustomerId({
customers,
selectedCustomerId: customerId,
});
}
```
Sources: [apps/web/app/ee/api/google-ads/callback/route.ts:92-110](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/callback/route.ts#L92-L110)
> [!NOTE]
> Only workspace members with the `owner` role can install or modify the Google Ads integration, and the workspace must possess an active Advanced or Enterprise plan capability.
Sources: [apps/web/app/ee/api/google-ads/callback/route.ts:63-83](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/callback/route.ts#L63-L83)
### Login Customer ID Inference
Manager accounts (MCC) and client accounts require precise handling of the `login-customer-id` header to avoid `USER_PERMISSION_DENIED` (403) errors. The system infers and tests multiple candidate identifiers when resolving accounts or listing conversion actions.
```typescript
export const inferLoginCustomerId = ({
customers,
selectedCustomerId,
}: {
customers: {
id: string;
manager: boolean;
loginCustomerId?: string | null;
}[];
selectedCustomerId: string;
}) => {
const normalizedSelectedId = selectedCustomerId.replace(/-/g, "");
const selectedCustomer = customers.find(
(customer) => customer.id.replace(/-/g, "") === normalizedSelectedId,
);
if (!selectedCustomer) {
return null;
}
if (selectedCustomer.loginCustomerId) {
return selectedCustomer.loginCustomerId.replace(/-/g, "");
}
if (selectedCustomer.manager) {
return normalizedSelectedId;
}
return null;
};
```
Sources: [apps/web/lib/integrations/google-ads/api.ts:509-538](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/api.ts#L509-L538)
> [!WARNING]
> Sub-managers discovered via account hierarchy traversal that have independent customer login identifiers are excluded from automatic manager candidate lists to prevent invalid permission headers.
Sources: [apps/web/lib/integrations/google-ads/api.ts:563-570](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/api.ts#L563-L570)
### Conversion Action Selection
Workspaces query available conversion actions through an API endpoint that verifies workspace-level installation, retrieves fresh OAuth tokens, and iterates through login customer ID candidates. It performs a streaming search query filtering specifically for enabled upload click conversion actions.
```typescript
for (const loginCustomerId of candidates) {
try {
const googleAdsApi = new GoogleAdsApi({
accessToken: token.access_token,
loginCustomerId,
customerId,
});
const conversionActions =
await googleAdsApi.listUploadClickConversionActions(customerId);
return NextResponse.json({
conversionActions,
loginCustomerId,
});
} catch (error) {
lastError = error;
const message = error instanceof Error ? error.message : String(error);
if (!message.includes("USER_PERMISSION_DENIED")) {
throw error;
}
}
}
```
Sources: [apps/web/app/ee/api/google-ads/conversion-actions/route.ts:65-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/conversion-actions/route.ts#L65-L90)
The conversion action query retrieves specific resource fields from the Google Ads API schema:
| Field Path | Filter / Condition | Purpose |
| :--- | :--- | :--- |
| `conversion_action.id` | Selected | Identifies the unique numeric conversion action identifier |
| `conversion_action.name` | Selected | Provides the human-readable label shown in settings |
| `conversion_action.resource_name` | Selected | Provides the full API resource path (`customers/{cid}/conversionActions/{id}`) |
| `conversion_action.type` | Equals `UPLOAD_CLICKS` | Restricts results to offline click upload actions |
| `conversion_action.status` | Equals `ENABLED` | Filters out paused or removed conversion actions |
Sources: [apps/web/lib/integrations/google-ads/api.ts:415-421](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/api.ts#L415-L421)
## Google Ads Conversion Upload Pipeline
### Click ID Extraction and Queueing
When a lead or sale event is tracked via [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking), the conversion pipeline extracts promotional click identifiers from the visitor's landing URL to establish attribution. The `extractGoogleAdsClickId` function parses URL query parameters using `getSearchParams` and checks for three supported click identifier variants: `gclid` (Google Click ID), `gbraid` (App-to-web click ID), and `wbraid` (Web-to-app click ID). If none of these parameters are present, conversion queueing is immediately aborted.
```typescript
const extractGoogleAdsClickId = (url: string): GoogleAdsClickId | null => {
try {
const queryParams = getSearchParams(url);
if (queryParams.gclid) {
return {
gclid: queryParams.gclid,
};
}
if (queryParams.gbraid) {
return {
gbraid: queryParams.gbraid,
};
}
if (queryParams.wbraid) {
return {
wbraid: queryParams.wbraid,
};
}
return null;
} catch {
return null;
}
};
```
Sources: [apps/web/lib/integrations/google-ads/upload-conversion.ts:21-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts#L21-L47)
Before publishing the payload to QStash, `queueGoogleAdsConversionUpload` verifies whether the target workspace has installed the Google Ads integration. It also handles currency normalization: because the Google Ads Data Manager API expects major currency units, conversion values are divided by 100 for any currency that is not a zero-decimal currency (such as JPY). The payload is subsequently published asynchronously to the ingestion endpoint with up to 3 retries and a unique deduplication identifier constructed from the workspace ID and event ID.
```typescript
export const queueGoogleAdsConversionUpload = async (
payload: z.infer,
) => {
if (!extractGoogleAdsClickId(payload.click.url)) {
return;
}
if (!(await googleAdsInstalledWorkspaces.has(payload.workspaceId))) {
return;
}
// Data Manager expects major currency units, so we need to divide by 100
// if the currency is NOT a zero decimal currency (e.g. JPY doesn't have cents)
if (
payload.conversionValue &&
payload.currencyCode &&
!isZeroDecimalCurrency(payload.currencyCode)
) {
payload.conversionValue = payload.conversionValue / 100;
}
try {
const response = await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/google-ads/upload-conversion`,
body: payload,
retries: 3,
deduplicationId: `google-ads-${payload.workspaceId}-${payload.eventId}`,
});
if (!response.messageId) {
throw new Error("Failed to queue Google Ads conversion upload");
}
return response;
} catch (error) {
logger.error("google-ads.queue_conversion_failed", {
service: "google-ads",
error: toErrorFields(error),
correlation: {
workspaceId: payload.workspaceId,
eventId: payload.eventId,
eventType: payload.eventType,
clickId: payload.click.id,
},
});
await logger.flush();
throw error;
}
};
```
Sources: [apps/web/lib/integrations/google-ads/upload-conversion.ts:49-98](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts#L49-L98)
> [!NOTE]
> QStash message deduplication relies on the deterministic deduplication ID format `google-ads-{workspaceId}-{eventId}`, preventing duplicate ingestion of the same offline conversion event if retried.
Sources: [apps/web/lib/integrations/google-ads/upload-conversion.ts:75-75](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts#L75-L75)
### API Upload Execution and Mapping
The scheduled cron route handles incoming POST requests at `/api/google-ads/upload-conversion` using the `withCron` wrapper. It parses the incoming body against `googleAdsConversionUploadSchema` and delegates execution to `uploadGoogleAdsConversion`.
Sources: [apps/web/app/ee/api/google-ads/upload-conversion/route.ts:9-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/google-ads/upload-conversion/route.ts#L9-L20)
The upload handler queries the `InstalledIntegration` table for the specified workspace using the `GOOGLE_ADS_INTEGRATION_ID` constant. It parses workspace settings and resolves the appropriate conversion mapping by matching the incoming event type (`lead` or `sale`) and event name against configured mappings. If the customer ID or conversion mapping is missing, or if the click URL lacks a valid click ID, the upload operation returns a skipped status.
```typescript
export const uploadGoogleAdsConversion = async (
payload: z.infer,
): Promise => {
const {
workspaceId,
eventType,
click,
conversionDateTime,
eventId,
eventName,
conversionValue,
currencyCode,
conversionCount,
} = googleAdsConversionUploadSchema.parse(payload);
try {
const installedIntegration = await prisma.installedIntegration.findFirst({
where: {
integrationId: GOOGLE_ADS_INTEGRATION_ID,
projectId: workspaceId,
},
select: {
id: true,
settings: true,
credentials: true,
},
});
if (!installedIntegration) {
return {
message: `Google Ads integration not installed for workspace ${workspaceId}. Skipping...`,
status: "skipped",
};
}
const settings = googleAdsSettingsSchema.parse(
installedIntegration.settings ?? {},
);
const mappings =
eventType === "lead" ? settings.leadMappings : settings.saleMappings;
const mapping = resolveGoogleAdsConversionMapping({
mappings,
eventName,
});
if (!settings.customerId) {
return {
message: `Missing customerId. Skipping...`,
status: "skipped",
};
}
if (!mapping) {
return {
message: mappings.length
? `No ${eventType} conversion mapping matched event name "${eventName ?? ""}". Skipping...`
: `Missing ${eventType} conversion mapping. Skipping...`,
status: "skipped",
};
}
const conversionAction = mapping.conversionAction;
const googleClickId = extractGoogleAdsClickId(click.url);
if (!googleClickId) {
return {
message: `No gclid/gbraid/wbraid found on click ${click.id}. Skipping...`,
status: "skipped",
};
}
```
Sources: [apps/web/lib/integrations/google-ads/upload-conversion.ts:105-176](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts#L105-L176)
Once validated, the pipeline retrieves a fresh OAuth access token via `googleAdsOAuthProvider.getAccessToken` and instantiates the `GoogleAdsApi` client. It invokes `uploadClickConversion` against the Google Ads Data Manager API endpoint (`events:ingest`), wrapping the call in an exponential backoff retry loop with a maximum of 3 retries and delays scaled by `1000 * Math.pow(2, attempt)`.
```typescript
const token =
await googleAdsOAuthProvider.getAccessToken(installedIntegration);
let loginCustomerId: string | null = null;
if (
settings.loginCustomerId &&
settings.loginCustomerId !== settings.customerId
) {
loginCustomerId = settings.loginCustomerId;
}
const googleAdsApi = new GoogleAdsApi({
accessToken: token.access_token,
loginCustomerId,
customerId: settings.customerId,
});
const maxRetries = 3;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const response = await googleAdsApi.uploadClickConversion({
customerId: settings.customerId,
conversionAction,
googleClickId,
conversionDateTime,
conversionValue,
currencyCode,
conversionCount,
eventId,
});
return {
message: `Uploaded ${eventType} conversion for workspace ${workspaceId} (requestId: ${response.requestId})`,
status: "uploaded",
};
} catch (error) {
if (attempt < maxRetries) {
await sleep(1000 * Math.pow(2, attempt));
continue;
}
throw error;
}
}
```
Sources: [apps/web/lib/integrations/google-ads/upload-conversion.ts:178-223](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/upload-conversion.ts#L178-L223)
> [!WARNING]
> New integrations must utilize the Data Manager API (`events:ingest`) rather than the legacy `ConversionUploadService.UploadClickConversions` service when submitting offline click conversions.
Sources: [apps/web/lib/integrations/google-ads/api.ts:441-443](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/google-ads/api.ts#L441-L443)
## Shopify Pixel Order Attribution Sync
### Pixel Webhook Ingestion and Validation
The Shopify Pixel event endpoint processes incoming telemetry via `POST /api/shopify/pixel`. Request bodies are validated using a Zod schema requiring `clickId`, `checkoutToken`, and `shopDomain`. CORS headers from `COMMON_CORS_HEADERS` are attached to all responses, including preflight `OPTIONS` requests returning status `204`.
```typescript
import { COMMON_CORS_HEADERS } from "@/lib/api/cors";
import { parseRequestBody } from "@/lib/api/utils";
import {
shopifyCheckoutCache,
tryDispatchShopifyOrderJob,
} from "@/lib/integrations/shopify/checkout-cache";
import { getClickEvent } from "@/lib/tinybird";
import { ratelimit } from "@/lib/upstash";
import { LOCALHOST_IP } from "@dub/utils";
import { ipAddress, waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
const inputSchema = z.object({
clickId: z.string().nullish(),
checkoutToken: z.string().nullish(),
shopDomain: z.string().nullish(),
});
// POST /api/shopify/pixel – Handle the Shopify Pixel events
export const POST = async (req: Request) => {
const response = NextResponse.json("OK", {
headers: COMMON_CORS_HEADERS,
});
```
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:1-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L1-L25)
Incoming payloads are parsed, logged, and filtered for required identification tokens. If either `checkoutToken` or `clickId` is absent, the endpoint logs an error and skips processing while returning an "OK" response.
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:26-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L26-L46)
> [!WARNING]
> Requests lacking either a `checkoutToken` or a `clickId` are dropped immediately without initiating cache updates or dispatching order background jobs.
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:37-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L37-L45)
### Rate Limiting and Click Event Retrieval
Prior to executing attribution logic, requests undergo rate limiting keyed by client IP. When executing on Vercel (`process.env.VERCEL === "1"`), the IP is resolved using `ipAddress(req)`; otherwise, `LOCALHOST_IP` is used. The limiter evaluates against the key prefix `shopify-track-pixel:{ip}`.
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:47-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L47-L55)
Once rate limiting passes, the route queries Tinybird via `getClickEvent` using the provided `clickId`. If no matching click event exists in analytics storage, the request is aborted.
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:56-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L56-L62)
### Checkout Cache Lookups and Job Dispatch
Validated pixel events are committed asynchronously using `waitUntil`. The checkout token is mapped to its associated `clickId` inside `shopifyCheckoutCache`, after which `tryDispatchShopifyOrderJob` triggers downstream e-commerce order attribution processing.
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:63-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L63-L76)
| Field Name | Type | Nullable | Purpose |
| :--- | :--- | :--- | :--- |
| `clickId` | string | Yes | Associates the visitor click identifier with the e-commerce session |
| `checkoutToken` | string | Yes | Unique token identifying the Shopify checkout instance |
| `shopDomain` | string | Yes | Target Shopify merchant storefront domain |
Sources: [apps/web/app/ee/api/shopify/pixel/route.ts:14-18](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/pixel/route.ts#L14-L18)
## Mobile Attribution with AppsFlyer
### Webhook Verification and IP Range Enforcement
The AppsFlyer postback webhook endpoint listens for incoming events at `GET /api/appsflyer/webhook`. Unless executing in a local development environment (`isLocalDev`), incoming requests have their client IP verified against allowed `APPSFLYER_IP_RANGES` using `isIpInRange`. If an address falls outside the designated ranges, a `DubApiError` with code `forbidden` is thrown.
```typescript
if (!isLocalDev) {
const ip = await getIP();
const isAllowed = APPSFLYER_IP_RANGES.some((range) =>
isIpInRange(ip, range),
);
if (!isAllowed) {
throw new DubApiError({
code: "forbidden",
message: `IP address ${ip} is not allowed.`,
});
}
}
```
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:37-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L37-L49)
> [!WARNING]
> Requests originating from unverified IP addresses outside `APPSFLYER_IP_RANGES` are rejected with a `403 Forbidden` response code in production environments.
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:43-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L43-L48)
Query parameters are parsed using `querySchema` to extract `appId`, `partnerEventId`, and `eventValue`. The `partnerEventId` must explicitly match either `"lead"` or `"sale"` values, otherwise processing is skipped and an acknowledgment response is returned.
```typescript
const querySchema = z.object({
appId: z.string(),
partnerEventId: z.string().nullish(),
eventValue: z.string().nullish(),
});
…
queryParams = getSearchParams(req.url);
const { appId, partnerEventId } = querySchema.parse(queryParams);
if (!partnerEventId || !["lead", "sale"].includes(partnerEventId)) {
return logAndRespond(
`"${partnerEventId}" is not a valid partner event ID (accepted values: "lead", "sale"). Skipping...`,
);
}
```
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:20-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L20-L24), [apps/web/app/ee/api/appsflyer/webhook/route.ts:51-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L51-L59)
### Workspace Installation Lookup
Once the query parameters are validated, the route queries Prisma's `installedIntegration` model to find an active configuration matching the `APPSFLYER_INTEGRATION_ID` constant and the specified `appId` stored within integration settings JSON paths.
```typescript
// Find the installation
const installation = await prisma.installedIntegration.findFirst({
where: {
integrationId: APPSFLYER_INTEGRATION_ID,
settings: {
path: "$.appIds",
array_contains: appId,
},
},
select: {
project: {
select: {
id: true,
stripeConnectId: true,
webhookEnabled: true,
},
},
},
});
```
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:61-80](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L61-L80)
If no matching installation is found for the given app ID, a `bad_request` error is raised requiring configuration verification.
```typescript
if (!installation) {
throw new DubApiError({
code: "bad_request",
message: `AppsFlyer integration is not configured for the appId: "${appId}". Did you add the app ID to the AppsFlyer integration settings?`,
});
}
```
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:81-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L81-L86)
### Conversion Currency Transformation and Event Recording
When `partnerEventId` is `"lead"`, parameters are parsed via `trackLeadRequestSchema` and dispatched to `trackLead` with `commissionSource` set to `CommissionSource.appsflyer`.
```typescript
if (partnerEventId === "lead") {
const {
clickId,
eventName,
customerExternalId,
customerName,
customerEmail,
customerAvatar,
} = trackLeadRequestSchema.parse(queryParams);
const leadResponse = await trackLead({
clickId,
eventName,
customerExternalId,
customerName,
customerEmail,
customerAvatar,
eventQuantity: undefined,
mode: undefined,
metadata: null,
workspace,
commissionSource: CommissionSource.appsflyer,
});
response = JSON.stringify(leadResponse);
}
```
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:91-116](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L91-L116)
When `partnerEventId` is `"sale"`, raw financial amounts undergo currency transformation via `appsflyerAmountToDubCents` before being validated through `trackSaleRequestSchema`. The resulting conversion record is handled by `trackSale` using a `paymentProcessor` of `"custom"` and `CommissionSource.appsflyer`.
```typescript
// Track sale event
else if (partnerEventId === "sale") {
const amountInCents = appsflyerAmountToDubCents(queryParams.amount);
const { eventName, customerExternalId, amount, currency, invoiceId } =
trackSaleRequestSchema.parse({
...queryParams,
...(amountInCents !== undefined && { amount: amountInCents }),
});
const saleResponse = await trackSale({
customerExternalId,
amount,
currency,
eventName,
paymentProcessor: "custom",
invoiceId,
leadEventName: undefined,
metadata: null,
workspace,
commissionSource: CommissionSource.appsflyer,
});
response = JSON.stringify(saleResponse);
}
```
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:118-141](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L118-L141)
| Query Parameter / Field | Type | Nullable | Purpose |
| :--- | :--- | :--- | :--- |
| `appId` | string | No | Mobile application identifier configured in AppsFlyer settings |
| `partnerEventId` | string | Yes | Identifies the conversion category (`lead` or `sale`) |
| `eventValue` | string | Yes | Additional metadata payload associated with the postback event |
Sources: [apps/web/app/ee/api/appsflyer/webhook/route.ts:20-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L20-L24)
## Singular Mobile Attribution Ingestion
### Event Mapping and Workspace Resolution
Incoming mobile postbacks from Singular are received at the endpoint `GET /api/singular/webhook`. When requests arrive, the client IP address is checked against `SINGULAR_IP_RANGES` using `isIpInRange` unless the environment flag `isLocalDev` is active. If the incoming IP does not match any authorized range, a `DubApiError` with code `forbidden` is thrown.
```typescript
import { isLocalDev } from "@/lib/api/environment";
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getIP } from "@/lib/api/utils/get-ip";
import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { withAxiom } from "@/lib/axiom/server";
import { SINGULAR_IP_RANGES } from "@/lib/integrations/singular/singular-ip-ranges";
import { trackSingularLeadEvent } from "@/lib/integrations/singular/track-lead";
import { trackSingularSaleEvent } from "@/lib/integrations/singular/track-sale";
import { isIpInRange } from "@/lib/middleware/utils/is-ip-in-range";
import { prisma } from "@/lib/prisma";
import { getSearchParams } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
…
// GET /api/singular/webhook – listen to Postback events from Singular
export const GET = withAxiom(async (req) => {
try {
if (!isLocalDev) {
const ip = await getIP();
const isAllowed = SINGULAR_IP_RANGES.some((range) =>
isIpInRange(ip, range),
);
if (!isAllowed) {
throw new DubApiError({
code: "forbidden",
message: `IP address ${ip} is not allowed.`,
});
}
}
```
Sources: [apps/web/app/ee/api/singular/webhook/route.ts:1-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L1-L13), [apps/web/app/ee/api/singular/webhook/route.ts:37-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L37-L52)
> [!WARNING]
> Production webhook calls originating outside `SINGULAR_IP_RANGES` are immediately rejected with a `403 Forbidden` error status via `handleAndReturnErrorResponse`.
Sources: [apps/web/app/ee/api/singular/webhook/route.ts:40-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L40-L51), [apps/web/app/ee/api/singular/webhook/route.ts:110-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L110-L112)
Query parameters are inspected to extract `dub_workspace_id`, which is validated and normalized using `normalizeWorkspaceId`. The incoming `event_name` parameter is checked against a supported event dictionary to map Singular postback actions into Dub conversion types. Unsupported events are logged to the console and acknowledged with an `"OK"` response without throwing an error.
```typescript
const singularToDubEvent = {
activated: "lead",
sng_complete_registration: "lead",
sng_subscribe: "sale",
sng_ecommerce_purchase: "sale",
__iap__: "sale", // In-app purchase
"Copy GAID": "lead", // Singular Device Assist
"copy IDFA": "lead", // Singular Device Assist
};
const supportedEvents = Object.keys(singularToDubEvent);
const querySchema = z.object({
dub_workspace_id: z
.string()
.min(1, "dub_workspace_id is required")
.describe(
"The Singular advertiser's workspace ID on Dub (see https://d.to/id).",
)
.transform((v) => normalizeWorkspaceId(v)),
});
…
const queryParams = getSearchParams(req.url);
const { dub_workspace_id: workspaceId } = querySchema.parse(queryParams);
const { event_name: eventName } = queryParams;
if (!eventName) {
throw new DubApiError({
code: "bad_request",
message: "event_name is required.",
});
}
if (!supportedEvents.includes(eventName)) {
console.error(
`Event ${eventName} is not supported by Singular <> Dub integration.`,
);
return NextResponse.json("OK");
}
```
Sources: [apps/web/app/ee/api/singular/webhook/route.ts:15-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L15-L35), [apps/web/app/ee/api/singular/webhook/route.ts:54-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L54-L73)
| Singular Event Name | Mapped Dub Event Type | Description |
| :--- | :--- | :--- |
| `activated` | `lead` | User activation event |
| `sng_complete_registration` | `lead` | Standard registration completion |
| `sng_subscribe` | `sale` | Subscription event |
| `sng_ecommerce_purchase` | `sale` | E-commerce purchase transaction |
| `__iap__` | `sale` | In-app purchase event |
| `Copy GAID` | `lead` | Singular Device Assist GAID copy |
| `copy IDFA` | `lead` | Singular Device Assist IDFA copy |
Sources: [apps/web/app/ee/api/singular/webhook/route.ts:15-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L15-L23)
Prisma queries the `project` model using the resolved workspace ID to retrieve workspace attributes including `stripeConnectId` and `webhookEnabled`. If the workspace cannot be found, a `not_found` error is raised.
```typescript
const workspace = await prisma.project.findUnique({
where: {
id: workspaceId,
},
select: {
id: true,
stripeConnectId: true,
webhookEnabled: true,
},
});
if (!workspace) {
throw new DubApiError({
code: "not_found",
message: `Workspace ${workspaceId} not found.`,
});
}
```
Sources: [apps/web/app/ee/api/singular/webhook/route.ts:75-91](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L75-L91)
### Lead Event Bridging
Once the workspace is authenticated, lead events are processed by deleting the `dub_workspace_id` parameter and dispatching the payload to `trackSingularLeadEvent`. The helper parses `dub_id` as the click ID and extracts nested parameters from `event_attributes` containing customer details, before invoking `trackLead` with a `commissionSource` of `CommissionSource.singular`.
```typescript
const dubEvent = singularToDubEvent[eventName];
delete queryParams.dub_workspace_id;
if (dubEvent === "lead") {
await trackSingularLeadEvent({
queryParams,
workspace,
});
} else if (dubEvent === "sale") {
await trackSingularSaleEvent({
queryParams,
workspace,
});
}
```
Sources: [apps/web/app/ee/api/singular/webhook/route.ts:93-108](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts#L93-L108)
```typescript
export const trackSingularLeadEvent = async ({
queryParams,
workspace,
}: {
queryParams: Record;
workspace: Pick;
}) => {
const {
dub_id: clickId,
event_name: eventName,
event_attributes: {
customer_external_id: customerExternalId,
customer_name: customerName,
customer_email: customerEmail,
customer_avatar: customerAvatar,
event_quantity: eventQuantity,
mode,
},
} = singularLeadEventSchema.parse(queryParams);
return await trackLead({
clickId,
eventName,
customerEmail,
customerAvatar,
customerExternalId,
customerName,
eventQuantity,
mode,
metadata: null,
workspace,
commissionSource: CommissionSource.singular,
});
};
```
Sources: [apps/web/lib/integrations/singular/track-lead.ts:31-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/singular/track-lead.ts#L31-L64)
## Partner Postback and Conversion Relaying
Downstream postback dispatching is handled by concrete subclasses extending `PostbackAdapter`, which manage custom event transformer registration upon initialization and execute asynchronous delivery via QStash. The abstract base class instantiates a `PostbackEventTransformers` registry and exposes an `execute` method that transforms raw event payloads before signing and publishing them to configured endpoints.
```typescript
export interface PostbackPayload {
eventId: string;
event: PostbackTrigger;
createdAt: string;
data: unknown;
}
export abstract class PostbackAdapter {
protected eventTransformers = new PostbackEventTransformers();
constructor(protected postback: Postback) {
this.registerEventTransformers();
}
protected abstract registerEventTransformers(): void;
```
Sources: [apps/web/lib/postback/postback-adapters.ts:8-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L8-L23)
```typescript
async execute(payload: PostbackPayload) {
const transformedPayload = this.eventTransformers.transform(payload);
if (!transformedPayload) {
return;
}
const searchParams = {
postbackId: this.postback.id,
eventId: payload.eventId,
event: payload.event,
};
const callbackUrl = buildCallbackUrl(
`${APP_DOMAIN_WITH_NGROK}/api/postbacks/callback`,
searchParams,
);
```
Sources: [apps/web/lib/postback/postback-adapters.ts:24-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L24-L41)
When dispatching postback requests, `execute` generates an HMAC webhook signature using the postback secret and attaches it to the request header `Dub-Signature`. It also sets `Upstash-Hide-Headers` to `"true"` before publishing the payload via `qstash.publishJSON`.
```typescript
const signature = await createWebhookSignature(
this.postback.secret,
transformedPayload,
);
const response = await qstash.publishJSON({
callback: callbackUrl.href,
failureCallback: callbackUrl.href,
url: this.postback.url,
body: transformedPayload,
headers: {
"Dub-Signature": signature,
"Upstash-Hide-Headers": "true",
},
});
if (!response.messageId) {
console.error("Failed to publish postback event to QStash", response);
}
if (process.env.NODE_ENV === "development") {
console.debug("Published postback event to QStash", {
...response,
payload: transformedPayload,
});
}
}
```
Sources: [apps/web/lib/postback/postback-adapters.ts:42-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L42-L68)
> [!WARNING]
> If `qstash.publishJSON` returns a response object lacking a `messageId`, an error is logged to `console.error`, though execution continues without throwing.
Sources: [apps/web/lib/postback/postback-adapters.ts:58-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L58-L60)
Postback event telemetry and audit logging are recorded using Tinybird through the `recordPostbackEvent` ingestion helper, which targets the `dub_postback_events` data source using the `postbackEventInputSchemaTB` schema while omitting the `timestamp` field.
```typescript
import { postbackEventInputSchemaTB } from "@/lib/postback/schemas";
import { tb } from "../tinybird/client";
export const recordPostbackEvent = tb.buildIngestEndpoint({
datasource: "dub_postback_events",
event: postbackEventInputSchemaTB.omit({ timestamp: true }),
});
```
Sources: [apps/web/lib/postback/record-postback-event.ts:1-7](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/record-postback-event.ts#L1-L7)
## Related
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
---
## Technical docs: GET Get pending PayPal payouts
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminpendingpaypalpayouts
## Parameters
## Responses
## Try It
---
## Technical docs: GET Get admin payouts and timeseries
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminpayouts
## Parameters
## Responses
## Try It
---
## Technical docs: Data Importers
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/data-importers
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/scripts/dev/data.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/data.json)
- [apps/web/app/ee/api/cron/import/bitly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/import/rebrandly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/rebrandly/route.ts)
- [apps/web/lib/rewardful/importer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/importer.ts)
- [apps/web/app/ee/api/cron/import/rebrandly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rebrandly/route.ts)
- [apps/web/lib/rewardful/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-commissions.ts)
- [apps/web/app/ee/api/cron/import/rewardful/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rewardful/route.ts)
- [apps/web/app/ee/api/cron/import/tolt/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/tolt/route.ts)
- [apps/web/app/ee/api/cron/import/firstpromoter/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/import/short/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/short/route.ts)
- [apps/web/app/ee/api/cron/import/short/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/short/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/import/bitly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/bitly/route.ts)
- [apps/web/lib/tapfiliate/importer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tapfiliate/importer.ts)
- [apps/web/lib/tolt/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-commissions.ts)
- [apps/web/lib/middleware/link.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts)
- [apps/web/app/api/callback/bitly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/bitly/route.ts)
- [apps/web/app/ee/api/cron/import/lemonsqueezy/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts)
- [apps/web/lib/rewardful/import-campaigns.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-campaigns.ts)
- [apps/web/ui/guides/integrations.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/guides/integrations.ts)
- [apps/web/lib/rewardful/import-partners.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-partners.ts)
- [apps/web/lib/firstpromoter/import-commissions.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/lib/firstpromoter/import-partners.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-partners.ts)
- [apps/web/lib/partnerstack/importer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partnerstack/importer.ts)
- [packages/utils/src/constants/dub-domains.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/utils/src/constants/dub-domains.ts)
- [apps/web/lib/middleware/utils/crawl-bitly.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts)
- [apps/web/lib/rewardful/import-customers.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts)
- [apps/web/lib/tolt/import-customers.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts)
- [apps/web/scripts/customers/beehiiv/fix-case-a-complex.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/beehiiv/fix-case-a-complex.ts)
- [apps/web/scripts/customers/beehiiv/fix-case-a-simple.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/customers/beehiiv/fix-case-a-simple.ts)
## Overview
Data Importers facilitate the migration of historical link, partner, customer, and commission data from external URL shorteners and affiliate management platforms into Dub. By providing automated ingestion pathways, the system bridges legacy external infrastructures with Dub's workspace environment and [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs).
Sources: [apps/web/app/api/workspaces/idOrSlug/import/bitly/route.ts:60-140](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/bitly/route.ts#L60-L140), [apps/web/app/ee/api/cron/import/rewardful/route.ts:13-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rewardful/route.ts#L13-L37)
## Workspace link import endpoints
### Provider Route Architecture
Dub provides authenticated workspace-scoped HTTP routes to connect, inspect, and initiate link migrations from external URL shorteners including Bitly, Rebrandly, and Short.io. Each provider integration exposes standard HTTP verbs (`GET`, `PUT`, `POST`) guarded by workspace authorization checks and specific permission requirements such as `links.write` and `folders.links.write`.
Sources: [apps/web/app/api/workspaces/idOrSlug/import/bitly/route.ts:13-143](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/bitly/route.ts#L13-L143), [apps/web/app/api/workspaces/idOrSlug/import/rebrandly/route.ts:13-165](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/rebrandly/route.ts#L13-L165), [apps/web/app/api/workspaces/idOrSlug/import/short/route.ts:13-147](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/short/route.ts#L13-L147)
The migration endpoints perform token validation against secure Redis storage, query external provider APIs to fetch domains, groups, and link counts, and provision missing custom domains into both Prisma and Vercel prior to dispatching background ingestion jobs via QStash.
| Provider | Access Token Redis Key | Base API Endpoint | Required Permission |
| :--- | :--- | :--- | :--- |
| Bitly | `import:bitly:{workspaceId}` | `https://api-ssl.bitly.com/v4` | `links.write` |
| Rebrandly | `import:rebrandly:{workspaceId}` | `https://api.rebrandly.com/v1` | `links.write` |
| Short.io | `import:short:{workspaceId}` | `https://api.short.io` | `links.write` |
Sources: [apps/web/app/api/workspaces/idOrSlug/import/bitly/route.ts:15-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/bitly/route.ts#L15-L22), [apps/web/app/api/workspaces/idOrSlug/import/rebrandly/route.ts:15-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/rebrandly/route.ts#L15-L23), [apps/web/app/api/workspaces/idOrSlug/import/short/route.ts:15-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/short/route.ts#L15-L23)
> [!NOTE]
> During domain selection in `POST` handlers, if a selected import domain does not yet exist in the workspace, the route automatically registers it with Prisma (`primary: false`), provisions it on Vercel via `addDomainToVercel`, and generates a root placeholder link (`_root`) before publishing background cron tasks.
Sources: [apps/web/app/api/workspaces/idOrSlug/import/bitly/route.ts:72-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/bitly/route.ts#L72-L101), [apps/web/app/api/workspaces/idOrSlug/import/rebrandly/route.ts:116-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/rebrandly/route.ts#L116-L142), [apps/web/app/api/workspaces/idOrSlug/import/short/route.ts:99-125](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/short/route.ts#L99-L125)
## On-demand Bitly edge crawling
### Edge Crawl Execution Flow
When an incoming request cannot be resolved through standard database lookups during edge redirect dispatch, the `crawlBitly` utility intercepts requests to evaluate whether the requested key matches Bitly shortlink structures. Keys containing unsupported characters specified by Bitly's character regex are immediately rejected from being crawled.
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:20-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L20-L27)
```typescript
const invalidBitlyKeyRegex = /[`~,.<>;':"/\\[\]^{}()=+!*@&$£?%#|]/;
```
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:25-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L25-L25)
For valid keys, the function queries the Bitly API endpoint using the configured `BUFFER_BITLY_API_KEY`. If the remote bitlink exists and returns a validated long URL via `getUrlFromStringIfValid`, the system provisions the link directly into the database as an on-demand creation assigned to dedicated buffer workspace identifiers.
| Constant Name | Value / Identifier | Description |
| :--- | :--- | :--- |
| `BUFFER_WORKSPACE_ID` | `cm05wnnpo000711ztj05wwdbu` | Workspace assignment for on-demand crawled links |
| `BUFFER_USER_ID` | `cm05wnd49000411ztg2xbup0i` | User ID associated with crawled link creation |
| `BUFFER_FOLDER_ID` | `fold_1JNQBVZV8P0NA0YGB11W2HHSQ` | Folder categorization ID for buffer imports |
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:15-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L15-L17), [apps/web/lib/middleware/utils/crawl-bitly.ts:35-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L35-L50)
> [!WARNING]
> If the Bitly API encounters a rate limit or returns a non-ok response during `fetchBitlyLink`, the handler logs the rate limit hit and returns a `404` status for the target domain and key combination rather than failing the edge request outright.
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:100-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L100-L105)
### Background Persistence and Fallback Routing
Once a bitlink record is retrieved from the Bitly API and sanitized, `ev.waitUntil` schedules background persistence tasks using Prisma to create the link entry, record analytics via Tinybird through `recordLink`, and publish workspace usage events to Upstash Redis streams via `publishWorkspaceLinksUsageEvent`.
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:36-61](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L36-L61)
```typescript
.then((data) =>
Promise.allSettled([
recordLink(data),
publishWorkspaceLinksUsageEvent({
workspaceId: BUFFER_WORKSPACE_ID,
linksCount: 1,
timestamp: new Date().toISOString(),
}),
]),
),
```
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:51-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L51-L60)
If the remote lookup fails or yields no valid link, the middleware issues a fallback redirect to `https://buffer.com` with a `302` status code and attaches static Vercel CDN cache headers with an `s-maxage` of `86400` seconds alongside cache tags generated via `linkCache._createStaticPagesCacheKeys`.
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:70-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L70-L81)
```typescript
return NextResponse.redirect("https://buffer.com", {
headers: {
...DUB_HEADERS,
"Vercel-CDN-Cache-Control": "public, s-maxage=86400",
"Vercel-Cache-Tag": linkCache._createStaticPagesCacheKeys({
domain,
key,
}),
},
status: 302,
});
```
Sources: [apps/web/lib/middleware/utils/crawl-bitly.ts:71-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/utils/crawl-bitly.ts#L71-L81)
## Asynchronous link import workers
### QStash Signature Verification and Cron Routing
Background synchronization for external provider migrations relies on POST endpoints configured with `force-dynamic` rendering. Every incoming request body is intercepted, read as text, and validated against QStash cryptographic signatures via `verifyQstashSignature` before JSON parsing occurs.
Sources: [apps/web/app/ee/api/cron/import/bitly/route.ts:12-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts#L12-L19), [apps/web/app/ee/api/cron/import/rebrandly/route.ts:9-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rebrandly/route.ts#L9-L16), [apps/web/app/ee/api/cron/import/short/route.ts:9-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/short/route.ts#L9-L16)
```typescript
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
const body = JSON.parse(rawBody);
```
Sources: [apps/web/app/ee/api/cron/import/bitly/route.ts:14-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts#L14-L19)
Depending on the provider target, requests parse specific parameters from the payload to drive batch processing and handle authentication credentials stored inside Redis keys.
| Provider Route | Payload Parameters Extracted | Redis Key Lookup Pattern |
| :--- | :--- | :--- |
| Bitly | `workspaceId`, `bitlyGroup`, `importTags`, `rateLimited` | `import:bitly:{workspaceId}` |
| Rebrandly | `workspaceId`, `importTags`, `createdAfter` | `import:rebrandly:{workspaceId}` |
| Short.io | `workspaceId`, `userId`, `domainId`, `domain`, `folderId`, `importTags`, `pageToken`, `count` | `import:short:{workspaceId}` |
Sources: [apps/web/app/ee/api/cron/import/bitly/route.ts:19-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts#L19-L23), [apps/web/app/ee/api/cron/import/rebrandly/route.ts:16-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rebrandly/route.ts#L16-L22), [apps/web/app/ee/api/cron/import/short/route.ts:16-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/short/route.ts#L16-L26)
> [!CAUTION]
> If a Rebrandly API key cannot be retrieved from Redis during background processing, the handler immediately throws a `DubApiError` with a `bad_request` code rather than attempting unauthenticated remote fetches.
Sources: [apps/web/app/ee/api/cron/import/rebrandly/route.ts:20-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rebrandly/route.ts#L20-L29)
### Tag Synchronization and Rate Limiting Flow
When import routines execute with `importTags` enabled, workers check Redis for previously cached flags (`import:bitly:${workspaceId}:tags` or `import:rebrandly:${workspaceId}:tags`). If absent, tag definitions are fetched from the upstream provider API, inserted into Prisma via `createId` with generated badge colors, and mapped to database identifiers.
Sources: [apps/web/app/ee/api/cron/import/bitly/route.ts:35-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts#L35-L82), [apps/web/app/ee/api/cron/import/rebrandly/route.ts:31-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rebrandly/route.ts#L31-L62)
```typescript
await prisma.tag.createMany({
data: tags.map((tag) => ({
id: createId({ prefix: "tag_" }),
name: tag,
color: randomBadgeColor(),
projectId: workspaceId,
})),
skipDuplicates: true,
});
await redis.set(`import:bitly:${workspaceId}:tags`, "true");
}
```
Sources: [apps/web/app/ee/api/cron/import/bitly/route.ts:54-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts#L54-L64)
Bitly background workers also evaluate provider-specific rate limits when the `rateLimited` flag evaluates to true, returning a JSON response indicating `rate_limited` status when thresholds are exceeded.
Sources: [apps/web/app/ee/api/cron/import/bitly/route.ts:25-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/bitly/route.ts#L25-L33)
> [!NOTE]
> OAuth callback handoff sequences for Bitly store access tokens directly in Redis under `import:bitly:${workspaceId}` before redirecting users back to their workspace dashboard with query parameters configured for initialization.
Sources: [apps/web/app/api/callback/bitly/route.ts:46-53](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/bitly/route.ts#L46-L53)
## Affiliate partner ingestion workflow
### Execution Walkthrough and Sequence
Affiliate partner migration pipelines ingest programs, campaigns, and active partners from platforms like Rewardful and FirstPromoter via QStash-verified background cron routes. The execution router evaluates the incoming `POST` action payload to dispatch processing across specific handlers for campaigns, partners, affiliate coupons, customers, and commissions.
Sources: [apps/web/app/ee/api/cron/import/rewardful/route.ts:13-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rewardful/route.ts#L13-L36)
1. `POST` — The QStash cron endpoint verifies message signatures and parses payload actions, routing execution to `importPartners` for active affiliate ingestion via `apps/web/app/(ee)/api/cron/import/rewardful/route.ts`.
Sources: [apps/web/app/ee/api/cron/import/rewardful/route.ts:13-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rewardful/route.ts#L13-L26)
2. `importPartners` — Fetches workspace credentials from Redis, instantiates provider clients, pages through remote affiliate records, filters active partners with existing leads or matching campaign IDs, and delegates creation to `createPartnerAndLinks` via `apps/web/lib/rewardful/import-partners.ts`.
Sources: [apps/web/lib/rewardful/import-partners.ts:14-110](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-partners.ts#L14-L110), [apps/web/lib/firstpromoter/import-partners.ts:19-102](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-partners.ts#L19-L102)
3. `createPartnerAndLinks` — Upserts partner database records by email, establishes approved program enrollments with group attributes, invokes application approval handlers, and bulk-creates referral links via `apps/web/lib/rewardful/import-partners.ts`.
Sources: [apps/web/lib/rewardful/import-partners.ts:165-256](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-partners.ts#L165-L256), [apps/web/lib/firstpromoter/import-partners.ts:116-254](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-partners.ts#L116-L254)
```mermaid
sequenceDiagram
participant Route as POST (route.ts)
participant Import as importPartners
participant Create as createPartnerAndLinks
Route->>Import: Dispatches import-partners action payload
Import->>Create: Iterates active affiliates and calls helper
Create->>Create: Upserts partner, enrollment, and bulk creates links
```
Sources: [apps/web/app/ee/api/cron/import/rewardful/route.ts:13-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rewardful/route.ts#L13-L26), [apps/web/lib/rewardful/import-partners.ts:14-256](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-partners.ts#L14-L256)
### Platform Integration Parameters and Limits
| Importer Platform | Maximum Batch Limit | Credential Cache Duration | Default Target Entity |
| :--- | :--- | :--- | :--- |
| Rewardful | 10 batches (`REWARDFUL_MAX_BATCHES`) | 24 hours (86400 seconds) | `partner` |
| FirstPromoter | 5 batches (`MAX_BATCHES`) | 24 hours | `partner` |
Sources: [apps/web/lib/rewardful/importer.ts:8-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/importer.ts#L8-L13), [apps/web/lib/rewardful/import-partners.ts:45-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-partners.ts#L45-L52), [apps/web/lib/firstpromoter/importer.ts:8-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/importer.ts#L8-L10), [apps/web/lib/firstpromoter/import-partners.ts:52-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-partners.ts#L52-L56)
> [!WARNING]
> When FirstPromoter link creation fails during partner imports, the database enrollment remains committed; error catch blocks ensure the enrollment identifier is still pushed to page-level partner search synchronization queues.
Sources: [apps/web/lib/firstpromoter/import-partners.ts:240-252](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-partners.ts#L240-L252)
## Customer referral ingestion pipeline
### Ingestion Flow and Synthetic Click Generation
Customer migrations from Rewardful and Tolt parse paginated referral payloads, verify existing database records by Stripe customer identifier or external ID, and manufacture synthetic click events for historical attribution. Because historical imports lack live HTTP requests, the pipeline constructs a dummy `Request` object with predefined headers (`user-agent`, `x-forwarded-for`, and Vercel geo headers) to simulate visitor traffic against the target link URL.
Sources: [apps/web/lib/rewardful/import-customers.ts:31-75](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L31-L75), [apps/web/lib/rewardful/import-customers.ts:210-236](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L210-L236), [apps/web/lib/tolt/import-customers.ts:33-121](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L33-L121), [apps/web/lib/tolt/import-customers.ts:205-231](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L205-L231)
```mermaid
sequenceDiagram
participant API as Rewardful / Tolt API
participant Importer as importCustomers
participant Click as recordClick & recordLead
participant DB as Prisma DB
API->>Importer: Returns customer/referral page
Importer->>DB: Checks existing stripeCustomerId / externalId
Importer->>Click: Generates dummy Request and records click
Click->>DB: Creates Customer and increments link leads count
```
Sources: [apps/web/lib/rewardful/import-customers.ts:36-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L36-L90), [apps/web/lib/rewardful/import-customers.ts:210-296](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L210-L296), [apps/web/lib/tolt/import-customers.ts:34-136](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L34-L136), [apps/web/lib/tolt/import-customers.ts:205-292](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L205-L292)
### Platform-Specific Ingestion Rules
| Importer Platform | Batch Limit Constant | Link & Token Resolution | Customer Deduplication Keys |
| :--- | :--- | :--- | :--- |
| Rewardful | `REWARDFUL_REFERRALS_MAX_BATCHES` | `referral.link?.token` or `referral.coupon?.token` with `-coupon` suffix | `stripeCustomerId`, workspace `externalId` |
| Tolt | `MAX_BATCHES` | Partner email mapped to program enrollment links (`links[0]`) | Workspace `externalId` (`customer_id || email || id`) |
Sources: [apps/web/lib/rewardful/import-customers.ts:35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L35), [apps/web/lib/rewardful/import-customers.ts:153-169](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L153-L169), [apps/web/lib/rewardful/import-customers.ts:194-208](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L194-L208), [apps/web/lib/tolt/import-customers.ts:33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L33), [apps/web/lib/tolt/import-customers.ts:83-94](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L83-L94), [apps/web/lib/tolt/import-customers.ts:111-120](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L111-L120), [apps/web/lib/tolt/import-customers.ts:195-201](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L195-L201)
> [!CAUTION]
> Rewardful customer records missing a valid Stripe customer ID starting with `cus_` trigger a `STRIPE_CUSTOMER_NOT_FOUND` import error log and halt processing for that specific referral.
Sources: [apps/web/lib/rewardful/import-customers.ts:181-192](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L181-L192)
> [!IMPORTANT]
> When processing Rewardful referrals, chunks of 10 items are handled concurrently via `Promise.allSettled`, while Tolt batches include a 2-second `sleep(2000)` delay between pages to respect upstream rate limits.
Sources: [apps/web/lib/rewardful/import-customers.ts:77-90](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-customers.ts#L77-L90), [apps/web/lib/tolt/import-customers.ts:122-138](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-customers.ts#L122-L138)
## Commission sync and attribution updates
Historical commissions are backfilled via asynchronous workers triggered through QStash endpoints in cron routes such as `apps/web/app/(ee)/api/cron/import/firstpromoter/route.ts`, `apps/web/app/(ee)/api/cron/import/rewardful/route.ts`, and `apps/web/app/(ee)/api/cron/import/tolt/route.ts`. During commission processing, sale amounts expressed in foreign currencies are converted to USD utilizing real-time exchange rates fetched from Upstash Redis hashes (`fxRates:usd`).
```typescript
let saleAmount = Number(commission.original_sale_amount ?? 0);
const saleCurrency = commission.original_sale_currency ?? "usd";
if (saleAmount > 0 && saleCurrency.toUpperCase() !== "USD" && fxRates) {
const { amount: convertedAmount } = convertCurrencyWithFxRates({
currency: saleCurrency,
amount: saleAmount,
fxRates,
});
saleAmount = convertedAmount;
}
```
Sources: [apps/web/lib/firstpromoter/import-commissions.ts:231-242](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts#L231-L242), [apps/web/lib/rewardful/import-commissions.ts:48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-commissions.ts#L48), [apps/web/lib/tolt/import-commissions.ts:52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-commissions.ts#L52)
> [!CAUTION]
> Commissions with units other than cash or those flagged as self-referrals are rejected and logged via Tinybird import error tracking with specific error codes like `SELF_REFERRAL` or `NOT_SUPPORTED_UNIT`.
Sources: [apps/web/lib/firstpromoter/import-commissions.ts:181-199](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts#L181-L199)
Status mappings vary across upstream affiliate providers to unify commission states within Dub databases:
| Provider | Upstream Status Value | Mapped Dub Status |
| :--- | :--- | :--- |
| Rewardful | `pending`, `due` | `pending` |
| Rewardful | `paid` | `paid` |
| Rewardful | `voided` | `canceled` |
| Tolt | `pending`, `approved` | `pending` |
| Tolt | `paid` | `paid` |
| Tolt | `rejected` | `canceled` |
| Tolt | `refunded` | `refunded` |
| FirstPromoter | `pending`, `approved` | `pending` |
| FirstPromoter | `denied` | `canceled` |
Sources: [apps/web/lib/rewardful/import-commissions.ts:28-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/rewardful/import-commissions.ts#L28-L33), [apps/web/lib/tolt/import-commissions.ts:28-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/tolt/import-commissions.ts#L28-L34), [apps/web/lib/firstpromoter/import-commissions.ts:28-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts#L28-L33)
> [!TIP]
> Downstream analytics records are updated concurrently with Prisma database mutations by calling `recordSaleWithTimestamp`, passing parsed click event schemas, customer identifiers, and payment processor details set to `stripe`.
Sources: [apps/web/lib/firstpromoter/import-commissions.ts:320-365](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/firstpromoter/import-commissions.ts#L320-L365)
## Related
- [Link Dispatch](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/link-attribution/link-dispatch)
- [Commission Engine](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/commission-engine)
---
## Technical docs: GET Get stablecoin payouts
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getstablecoinpayouts
## Parameters
## Responses
## Try It
---
## Technical docs: OAuth Apps
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/oauth-apps
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/api/oauth/apps/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/route.ts)
- [apps/web/app/api/oauth/authorize/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/authorize/route.ts)
- [packages/cli/src/utils/oauth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/oauth.ts)
- [apps/web/app/app.dub.co/auth/oauth/authorize/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx)
- [apps/web/app/api/tokens/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/tokens/route.ts)
- [apps/web/lib/api/oauth/constants.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts)
- [apps/web/app/api/oauth/userinfo/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/userinfo/route.ts)
- [apps/web/app/api/oauth/apps/appId/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/%5BappId%5D/route.ts)
- [packages/stripe-app/src/utils/oauth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts)
- [apps/web/app/api/oauth/token/exchange-code-for-token.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts)
- [packages/cli/src/api/callback.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts)
- [apps/web/app/ee/api/hubspot/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/callback/route.ts)
- [apps/web/app/api/slack/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/slack/callback/route.ts)
- [apps/web/app/api/oauth/token/refresh-access-token.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/refresh-access-token.ts)
- [packages/cli/src/commands/login.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts)
- [apps/web/lib/integrations/oauth-provider.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/oauth-provider.ts)
- [apps/web/app/api/callback/bitly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/bitly/route.ts)
- [apps/web/app/app.dub.co/auth/oauth/authorize/authorize-form.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx)
- [apps/web/lib/integrations/bitly/oauth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/bitly/oauth.ts)
- [apps/web/app/api/oauth/token/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/route.ts)
- [apps/web/app/app.dub.co/auth/oauth/authorize/scopes-requested.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/page.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/appId/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/%5BappId%5D/page-client.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/new/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/new/page-client.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/layout.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/layout.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/page-client.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/new/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/new/page.tsx)
- [apps/web/lib/actions/generate-client-secret.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/generate-client-secret.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/appId/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/%5BappId%5D/page.tsx)
- [apps/web/prisma/schema/oauth.prisma](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/oauth.prisma)
## Overview
Dub features a complete OAuth 2.0 authorization server implementation that enables third-party developers and internal clients, such as the Dub CLI, to securely integrate with Dub workspaces. Developers can register and manage OAuth applications directly within workspace developer settings, configuring redirect URIs, scopes, and PKCE requirements. The platform provides an interactive consent and authorization workflow where users select a target workspace, review requested permission scopes against their role privileges, and approve or decline access. Authorized requests issue short-lived authorization codes that are exchanged via secure token endpoints for access and refresh tokens, supporting both confidential client secrets and public PKCE verification.
Sources: [apps/web/prisma/schema/oauth.prisma:1-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/oauth.prisma#L1-L49), [apps/web/app/api/oauth/apps/route.ts:15-160](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/route.ts#L15-L160), [apps/web/app/api/oauth/authorize/route.ts:17-132](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/authorize/route.ts#L17-L132), [apps/web/app/app.dub.co/auth/oauth/authorize/page.tsx:23-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx#L23-L114), [apps/web/app/api/oauth/token/exchange-code-for-token.ts:15-230](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L15-L230), [packages/cli/src/commands/login.ts:9-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts#L9-L37)
## OAuth Application Storage and Schema
### Database Persistence Architecture
The OAuth persistence layer is managed via Prisma queries targeting `prisma.oAuthApp` (representing registered application credentials linked to an integration), `prisma.oAuthCode` (tracking short-lived authorization codes issued during consent prompts), and `prisma.oAuthRefreshToken` (managing token longevity by linking installations to restricted access tokens). The `oAuthApp` database table stores credentials including `clientId`, `hashedClientSecret`, `partialClientSecret`, `redirectUris` stored as JSON, and a `pkce` boolean flag for PKCE enforcement.
Sources: [apps/web/prisma/schema/oauth.prisma:1-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/oauth.prisma#L1-L12), [apps/web/app/api/oauth/apps/route.ts:17-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/route.ts#L17-L30)
Authorization codes issued during user consent prompts are inserted into `prisma.oAuthCode`, recording `clientId`, authorizing `userId`, workspace `projectId`, the unique `code` string, granted `scopes`, `redirectUri`, `expiresAt` timestamps, and optional PKCE parameters `codeChallenge` and `codeChallengeMethod`.
Sources: [apps/web/prisma/schema/oauth.prisma:14-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/oauth.prisma#L14-L34), [apps/web/app/api/oauth/authorize/route.ts:102-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/authorize/route.ts#L102-L114)
Long-lived sessions use `prisma.oAuthRefreshToken` to persist credentials, linking an installation record (`installationId`) to an issued access token (`accessTokenId`) via `hashedRefreshToken` and tracking an `expiresAt` date. Access tokens themselves are stored as `prisma.restrictedToken` records, establishing the foundation for API authentication across Dub's endpoints (documented in [REST API](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api), which handles general token querying and API key authentication).
Sources: [apps/web/prisma/schema/oauth.prisma:36-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/prisma/schema/oauth.prisma#L36-L49), [apps/web/app/api/oauth/token/exchange-code-for-token.ts:180-199](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L180-L199), [apps/web/app/api/tokens/route.ts:26-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/tokens/route.ts#L26-L65)
### Configuration Constants and Lifetimes
OAuth parameters and cryptographic lengths are governed by strict configuration constants defined in `OAUTH_CONFIG`. Token lifetimes are measured in seconds, defining short-lived authorization codes and access tokens alongside long-lived refresh tokens. Token and identifier lengths specify exact character counts, while prefix constants standardize naming conventions for generated identifiers and secrets across the system.
| Constant Name | Value / Length | Meaning / Purpose |
| :--- | :--- | :--- |
| `ACCESS_TOKEN_LIFETIME` | `7200` (2 hours) | Validity duration for issued access tokens |
| `REFRESH_TOKEN_LIFETIME` | `10368000` (120 days) | Validity duration for issued refresh tokens |
| `CODE_LIFETIME` | `120` (2 minutes) | Expiry window for authorization codes |
| `CLIENT_ID_LENGTH` | `24` characters | Generated length for client identifiers |
| `CLIENT_SECRET_LENGTH` | `30` characters | Generated length for raw client secrets |
| `ACCESS_TOKEN_LENGTH` | `40` characters | Generated length for access tokens |
| `REFRESH_TOKEN_LENGTH` | `40` characters | Generated length for refresh tokens |
| `CODE_LENGTH` | `40` characters | Generated length for authorization codes |
| `CLIENT_ID_PREFIX` | `dub_app_` | Prefix string prepended to client IDs |
| `CLIENT_SECRET_PREFIX` | `dub_app_secret_` | Prefix string prepended to client secrets |
| `ACCESS_TOKEN_PREFIX` | `dub_access_token_` | Prefix string prepended to access tokens |
Sources: [apps/web/lib/api/oauth/constants.ts:1-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L1-L16)
> [!NOTE]
> The `user.read` permission scope acts as the default baseline scope, meaning client applications do not need to explicitly request it during the authorization phase. All other scopes like `links.read`, `links.write`, and `analytics.read` must be explicitly declared.
Sources: [apps/web/lib/api/oauth/constants.ts:21-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L21-L34)
### Supported Scopes and Descriptions
OAuth applications can request targeted permission scopes on behalf of users. The available scopes govern granular access to workspace resources, webhooks, and account profiles.
| Scope Identifier | Description |
| :--- | :--- |
| `links.read` | Read access to links |
| `links.write` | Read and Write access to links |
| `tags.read` | Read access to tags |
| `tags.write` | Read and Write access to tags |
| `analytics.read` | Read access to analytics and events |
| `domains.read` | Read access to domains |
| `domains.write` | Read and Write access to domains |
| `user.read` | Read your name, email and profile image |
| `webhooks.read` | Read access to webhooks |
| `webhooks.write` | Read and Write access to webhooks |
| `folders.read` | Read access to folders |
| `folders.write` | Read and Write access to folders |
Sources: [apps/web/lib/api/oauth/constants.ts:21-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L21-L50)
## OAuth App Management in Dashboard
### Workspace Developer Settings and App Registration
Workspace settings provide a developer section under `/[slug]/settings/oauth-apps` for managing integrations. The user interface fetches registered applications via SWR from `/api/oauth/apps?workspaceId={workspaceId}` or presents an empty state via `EmptyState` with a cube icon when no apps exist.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/page-client.tsx:12-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/page-client.tsx#L12-L43), [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/layout.tsx:8-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/layout.tsx#L8-L19)
Applications are registered via `POST /api/oauth/apps`, which requires the `oauth_apps.write` permission. The endpoint parses request bodies using `createOAuthAppSchema`, checks for slug conflicts against existing `Integration` records, and generates a client ID using `createToken` with `OAUTH_CONFIG.CLIENT_ID_LENGTH` and `OAUTH_CONFIG.CLIENT_ID_PREFIX`. If PKCE is disabled (`!pkce`), a raw client secret is generated using `OAUTH_CONFIG.CLIENT_SECRET_LENGTH` and `OAUTH_CONFIG.CLIENT_SECRET_PREFIX`, hashed via `hashToken`, and partially exposed as `dub_app_secret_****${clientSecret.slice(-8)}`. Logo uploads are stored in object storage under `integrations/{integration.id}_{nanoid(7)}`.
Sources: [apps/web/app/api/oauth/apps/route.ts:45-160](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/route.ts#L45-L160)
> [!CAUTION]
> The raw client secret is returned in the HTTP response body exactly once upon creation. If lost, it cannot be retrieved and must be regenerated through the secret rotation mechanism.
Sources: [apps/web/app/api/oauth/apps/route.ts:136-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/route.ts#L136-L142)
### App Inspection and Secret Rotation
Individual apps are managed at `/[slug]/settings/oauth-apps/[appId]`. The management client validates write access using `clientAccessCheck` and loads application metadata via SWR from `/api/oauth/apps/[appId]?workspaceId={workspaceId}`.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/oauth-apps/appId/page-client.tsx:23-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/oauth-apps/%5BappId%5D/page-client.tsx#L23-L57)
Client secrets can be rotated using the server action exported from `generate-client-secret.ts`, wrapped by `authActionClient`. The action verifies that the user holds the `oauth_apps.write` permission, checks that the integration exists within the workspace, generates a new token of length `OAUTH_CONFIG.CLIENT_SECRET_LENGTH` with prefix `OAUTH_CONFIG.CLIENT_SECRET_PREFIX`, updates the `prisma.oAuthApp` record with a new `hashedClientSecret` and `partialClientSecret`, and returns the raw secret.
Sources: [apps/web/lib/actions/generate-client-secret.ts:17-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/actions/generate-client-secret.ts#L17-L50)
Updates and deletions are handled by `PATCH /api/oauth/apps/[appId]` and `DELETE /api/oauth/apps/[appId]`. Updates upload new logos or delete old screenshots asynchronously using `@vercel/functions` `waitUntil`. Deletions remove associated storage assets and delete the corresponding integration record in the database.
Sources: [apps/web/app/api/oauth/apps/appId/route.ts:52-214](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/apps/%5BappId%5D/route.ts#L52-L214)
## Authorization Flow and Consent UI
### Interactive Authorization and Consent Page
The OAuth authorization flow begins when a user navigates to the consent page at `/auth/oauth/authorize`. The page validates incoming query parameters using `validateAuthorizeRequest` against the `authorizeRequestSchema`. If the request parameters are invalid or the target integration is missing, an `EmptyState` component with the `CubeSettings` icon displays an error. When valid, the page renders a consent card displaying the integration's logo, name, developer information, and a warning banner if the app is unverified.
Sources: [apps/web/app/app.dub.co/auth/oauth/authorize/page.tsx:23-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx#L23-L114)
> [!WARNING]
> Unverified applications display a prominent warning banner and can only be installed by their developer or within the developer's workspace.
Sources: [apps/web/app/app.dub.co/auth/oauth/authorize/page.tsx:85-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx#L85-L101)
### Workspace Selector and Scope Validation
The consent form incorporates an interactive `WorkspaceSelector` managed through `AuthorizeWorkspaceProvider`. Users must choose a target workspace before granting API access. Requested scopes are processed by `ScopesRequested`, which automatically appends the default `user.read` scope if absent and filters permissions against the user's role in the selected workspace via `getDisplayedScopesForRole`. Missing permissions display a warning tooltip.
Sources: [apps/web/app/app.dub.co/auth/oauth/authorize/authorize-form.tsx:33-121](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx#L33-L121), [apps/web/app/app.dub.co/auth/oauth/authorize/scopes-requested.tsx:11-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx#L11-L57)
> [!NOTE]
> If a user's role lacks a requested scope, a warning icon appears beside the permission, and the scope is excluded from the final grant without failing the entire authorization request.
Sources: [apps/web/app/app.dub.co/auth/oauth/authorize/scopes-requested.tsx:43-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx#L43-L52), [apps/web/app/app.dub.co/auth/oauth/authorize/scopes-requested.tsx:93-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx#L93-L100)
### Authorization Request Approval and Code Issuance
Submitting the consent form triggers a `POST` request to `/api/oauth/authorize` with the selected workspace identifier. The endpoint enforces `integrations.write` permissions, calculates granted scopes using `getGrantedScopesForRole`, and validates client configuration, redirect URIs, and PKCE parameters. For Stripe and Shopify integrations, it checks that the workspace plan is Business tier or higher.
Sources: [apps/web/app/api/oauth/authorize/route.ts:17-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/authorize/route.ts#L17-L87)
| Validation Check | Error Code | Trigger Condition |
| :--- | :--- | :--- |
| Application existence | `not_found` | Integration record not found for `clientId` |
| Plan requirement | `bad_request` | Stripe or Shopify integration requested on a `free` or `pro` workspace plan |
| Redirect URI | `bad_request` | Provided `redirect_uri` is absent from the application's allowed list |
| PKCE parameters | `bad_request` | `app.pkce` is enabled but `code_challenge` or `code_challenge_method` is missing |
| App installation | `forbidden` | User lacks installation rights for an unverified application |
Sources: [apps/web/app/api/oauth/authorize/route.ts:52-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/authorize/route.ts#L52-L100)
Upon successful validation, an authorization code is generated using `createToken` with a length of `OAUTH_CONFIG.CODE_LENGTH` and persisted in the database via `prisma.oAuthCode.create` with an expiration window defined by `OAUTH_CONFIG.CODE_LIFETIME` (2 minutes). The endpoint constructs a callback URL appending the authorization code and optional `state`, returning it to the client for redirection.
Sources: [apps/web/app/api/oauth/authorize/route.ts:102-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/authorize/route.ts#L102-L129), [apps/web/lib/api/oauth/constants.ts:5](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L5), [apps/web/lib/api/oauth/constants.ts:11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L11)
## Token Exchange and PKCE Verification
### Handling Token Grant Requests
The endpoint located at `/api/oauth/token` processes incoming `POST` requests containing form-urlencoded payloads. The maximum execution duration for this route is set to 30 seconds, and all responses incorporate standard Cross-Origin Resource Sharing (CORS) headers via `COMMON_CORS_HEADERS`. Incoming data is parsed using `tokenGrantSchema`, routing payloads with a `grant_type` of `authorization_code` to `exchangeAuthCodeForToken` and `refresh_token` requests to `refreshAccessToken`.
```typescript
export const maxDuration = 30;
// POST /api/oauth/token - Exchange authorization code for access token and refresh access token
export async function POST(req: NextRequest) {
try {
const formData = Object.fromEntries(await req.formData());
const validatedData = tokenGrantSchema.parse(formData);
if (validatedData.grant_type === "authorization_code") {
const data = await exchangeAuthCodeForToken(req, validatedData);
return NextResponse.json(data, {
headers: COMMON_CORS_HEADERS,
});
} else if (validatedData.grant_type === "refresh_token") {
const data = await refreshAccessToken(req, validatedData);
return NextResponse.json(data, {
headers: COMMON_CORS_HEADERS,
});
}
} catch (error) {
return handleAndReturnErrorResponse(error, COMMON_CORS_HEADERS);
}
}
```
Sources: [apps/web/app/api/oauth/token/route.ts:8-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/route.ts#L8-L30)
| Grant Type | Handler Function | Purpose |
| :--- | :--- | :--- |
| `authorization_code` | `exchangeAuthCodeForToken` | Exchanges a valid authorization code for an access token and refresh token |
| `refresh_token` | `refreshAccessToken` | Rotates an existing refresh token to issue a new access token |
Sources: [apps/web/app/api/oauth/token/route.ts:16-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/route.ts#L16-L26)
> [!NOTE]
> If neither `client_id` nor `client_secret` is present in the request body, the handler inspects the `Authorization` header for `Basic` authentication credentials, decoding the base64-encoded string to extract the client identifier and secret.
Sources: [apps/web/app/api/oauth/token/exchange-code-for-token.ts:27-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L27-L41)
### PKCE and Client Secret Validation
When PKCE is enabled on an OAuth application (`app.pkce`), the `code_verifier` parameter becomes mandatory. If PKCE is disabled, the `client_secret` is required, hashed via `hashToken`, and compared against `app.hashedClientSecret` using `timingSafeCompare` to prevent timing attacks.
```typescript
// When PKCE is enabled, the code_verifier is required
if (app.pkce) {
if (!codeVerifier) {
throw new DubApiError({
code: "bad_request",
message: "Missing code_verifier parameter",
});
}
}
// When PKCE is not enabled, the client_secret is required
else if (!app.pkce) {
if (!clientSecret) {
throw new DubApiError({
code: "unauthorized",
message: "Missing client_secret",
});
}
const hashedClientSecret = await hashToken(clientSecret);
if (!timingSafeCompare(hashedClientSecret, app.hashedClientSecret)) {
throw new DubApiError({
code: "unauthorized",
message: "Invalid client_secret",
});
}
}
```
Sources: [apps/web/app/api/oauth/token/exchange-code-for-token.ts:85-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L85-L111)
For PKCE-enabled exchanges, the code challenge verification inspects `accessCode.codeChallengeMethod`. If set to `S256`, the `code_verifier` is hashed using `generateCodeChallengeHash`; otherwise, it is evaluated directly against `accessCode.codeChallenge`. Mismatches result in an `unauthorized` error with an `invalid_grant` message.
```typescript
if (app.pkce) {
const codeChallenge =
accessCode.codeChallengeMethod === "S256"
? await generateCodeChallengeHash(codeVerifier!)
: codeVerifier;
if (accessCode.codeChallenge != codeChallenge) {
throw new DubApiError({
code: "unauthorized",
message: "invalid_grant",
});
}
}
```
Sources: [apps/web/app/api/oauth/token/exchange-code-for-token.ts:120-132](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L120-L132)
> [!WARNING]
> Expired authorization codes trigger an immediate deletion via `prisma.oAuthCode.delete` accompanied by a `bad_request` error response indicating that the code has expired.
Sources: [apps/web/app/api/oauth/token/exchange-code-for-token.ts:134-146](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L134-L146)
### Token Issuance and Persistence
Upon successful validation, the system installs the integration for the user and workspace, then provisions a restricted access token and a refresh token. Lifetimes and token string characteristics are governed by `OAUTH_CONFIG`.
```typescript
export const OAUTH_CONFIG = {
ACCESS_TOKEN_LIFETIME: 2 * 60 * 60, // 2 hours
REFRESH_TOKEN_LIFETIME: 120 * 24 * 60 * 60, // 120 days
CODE_LIFETIME: 2 * 60, // 2 minutes
CLIENT_ID_LENGTH: 24,
CLIENT_SECRET_LENGTH: 30,
ACCESS_TOKEN_LENGTH: 40,
REFRESH_TOKEN_LENGTH: 40,
CODE_LENGTH: 40,
CLIENT_ID_PREFIX: "dub_app_",
CLIENT_SECRET_PREFIX: "dub_app_secret_",
ACCESS_TOKEN_PREFIX: "dub_access_token_",
};
```
Sources: [apps/web/lib/api/oauth/constants.ts:2-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L2-L16)
| Configuration Parameter | Value | Description |
| :--- | :--- | :--- |
| `ACCESS_TOKEN_LIFETIME` | `7200` (2 hours) | Lifetime of issued access tokens in seconds |
| `REFRESH_TOKEN_LIFETIME` | `10368000` (120 days) | Lifetime of refresh tokens in seconds |
| `CODE_LIFETIME` | `120` (2 minutes) | Expiration window for authorization codes |
| `ACCESS_TOKEN_LENGTH` | `40` | Character length for access tokens |
| `REFRESH_TOKEN_LENGTH` | `40` | Character length for refresh tokens |
| `ACCESS_TOKEN_PREFIX` | `dub_access_token_` | String prefix prepended to access tokens |
Sources: [apps/web/lib/api/oauth/constants.ts:2-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/oauth/constants.ts#L2-L16)
Once tokens are created, Vercel's `waitUntil` function asynchronously deletes the consumed authorization code and purges any prior restricted tokens associated with the same installation identifier, ensuring only one active token set remains valid per client-user-workspace combination.
```typescript
waitUntil(
Promise.all([
// Delete the code after it's been used
prisma.oAuthCode.delete({
where: {
code,
},
}),
// Remove all existing tokens for this client
prisma.restrictedToken.deleteMany({
where: {
installationId: installation.id,
id: {
not: restrictedToken.id,
},
},
}),
]),
);
```
Sources: [apps/web/app/api/oauth/token/exchange-code-for-token.ts:201-220](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/exchange-code-for-token.ts#L201-L220)
## Token Refresh and User Info
### Refreshing Expired Access Tokens
Clients request new access tokens by submitting a `POST` request to `/api/oauth/token` with `grant_type` set to `refresh_token`. The `refreshAccessToken` handler accepts the payload, resolving credentials from the request body or via HTTP Basic Authentication credentials parsed from the `Authorization` header.
```typescript
export const refreshAccessToken = async (
req: NextRequest,
params: z.infer,
) => {
let {
refresh_token,
client_id: clientId,
client_secret: clientSecret,
} = params;
// If no client_id or client_secret is provided in the request body
// then it should be provided in the Authorization header as Basic Auth for non-PKCE
if (!clientId && !clientSecret) {
const authorizationHeader = req.headers.get("Authorization") || "";
const [type, token] = authorizationHeader.split(" ");
if (type === "Basic") {
const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
if (splits.length > 1) {
clientId = splits[0];
clientSecret = splits[1];
}
}
}
```
Sources: [apps/web/app/api/oauth/token/refresh-access-token.ts:13-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/refresh-access-token.ts#L13-L37)
The application validates the `client_id` against `prisma.oAuthApp` and evaluates PKCE support. If PKCE is disabled, the supplied `client_secret` is hashed and checked against `hashedClientSecret` using `timingSafeCompare`.
```typescript
const oAuthApp = await prisma.oAuthApp.findUnique({
where: {
clientId,
},
select: {
pkce: true,
integrationId: true,
hashedClientSecret: true,
},
});
if (!oAuthApp) {
throw new DubApiError({
code: "unauthorized",
message: "OAuth app not found for the provided client_id",
});
}
if (!oAuthApp.pkce) {
if (!clientSecret) {
throw new DubApiError({
code: "unauthorized",
message: "Missing client_secret",
});
}
const hashedClientSecret = await hashToken(clientSecret);
if (!timingSafeCompare(hashedClientSecret, oAuthApp.hashedClientSecret)) {
throw new DubApiError({
code: "unauthorized",
message: "Invalid client_secret",
});
}
}
```
Sources: [apps/web/app/api/oauth/token/refresh-access-token.ts:46-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/refresh-access-token.ts#L46-L79)
> [!CAUTION]
> If a refresh token record is missing in `prisma.oAuthRefreshToken`, or if its `expiresAt` timestamp precedes the current system time, an unauthorized error is thrown, invalidating the refresh attempt.
Sources: [apps/web/app/api/oauth/token/refresh-access-token.ts:99-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/refresh-access-token.ts#L99-L112)
Upon validating the refresh token and its installation association, the old restricted access token is deleted within a Prisma transaction, and a replacement access token and refresh token are generated.
```typescript
await prisma.$transaction([
// Delete the old access token
prisma.restrictedToken.delete({
where: {
id: accessToken.id,
},
}),
// Create the access token and refresh token
prisma.restrictedToken.create({
data: {
name: generateRandomName(),
hashedKey: await hashToken(newAccessToken),
partialKey: `${newAccessToken.slice(0, 3)}...${newAccessToken.slice(-4)}`,
scopes: accessToken.scopes,
expires: accessTokenExpires,
userId: authorizedApp.userId,
projectId: authorizedApp.projectId,
installationId: authorizedApp.id,
refreshTokens: {
create: {
installationId: authorizedApp.id,
hashedRefreshToken: await hashToken(newRefreshToken),
expiresAt: new Date(
Date.now() + OAUTH_CONFIG.REFRESH_TOKEN_LIFETIME * 1000,
),
},
},
},
}),
]);
```
Sources: [apps/web/app/api/oauth/token/refresh-access-token.ts:168-198](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/token/refresh-access-token.ts#L168-L198)
### Resolving User Identity via User Info
The `GET /api/oauth/userinfo` endpoint extracts the bearer token from incoming requests using `getAuthTokenOrThrow`, hashes it, and queries active restricted token records that possess an associated installation ID and have not expired.
```typescript
export async function GET(req: NextRequest) {
try {
const accessToken = getAuthTokenOrThrow(req);
const tokenRecord = await prisma.restrictedToken.findFirst({
where: {
hashedKey: await hashToken(accessToken),
expires: {
gte: new Date(),
},
installationId: {
not: null,
},
},
select: {
user: {
select: {
id: true,
name: true,
image: true,
},
},
project: {
select: {
id: true,
name: true,
slug: true,
logo: true,
},
},
},
});
```
Sources: [apps/web/app/api/oauth/userinfo/route.ts:16-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/userinfo/route.ts#L16-L47)
If the token record is valid, the endpoint constructs an identity response containing the user identifier, display name, user image URL, and workspace details featuring a prefixed workspace identifier.
```typescript
const { user } = tokenRecord;
const userInfo = {
id: user.id,
name: user.name,
image: user.image,
workspace: {
id: prefixWorkspaceId(tokenRecord.project.id),
slug: tokenRecord.project.slug,
name: tokenRecord.project.name,
logo: tokenRecord.project.logo,
},
};
return NextResponse.json(userInfo, {
headers: CORS_HEADERS,
});
```
Sources: [apps/web/app/api/oauth/userinfo/route.ts:56-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/userinfo/route.ts#L56-L72)
## Client SDK and CLI Integration
### Dub CLI Authentication Flow
The Dub CLI utilizes `@badgateway/oauth2-client` to manage the OAuth 2.0 authorization code flow with PKCE. The client configuration hardcodes the client identifier `dub_app_39527dcc11b452f38bb54a3a1664fd044d7158dfea8abcde`, the authorization endpoint `https://app.dub.co/oauth/authorize`, and the token endpoint `https://api.dub.co/oauth/token`.
```typescript
import { OAuth2Client } from "@badgateway/oauth2-client";
export const oauthClient = new OAuth2Client({
// TODO: add client id here
clientId: "dub_app_39527dcc11b452f38bb54a3a1664fd044d7158dfea8abcde",
authorizationEndpoint: "https://app.dub.co/oauth/authorize",
tokenEndpoint: "https://api.dub.co/oauth/token",
});
```
Sources: [packages/cli/src/utils/oauth.ts:1-8](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/oauth.ts#L1-L8)
When running the `dub login` command, a 64-character code verifier is generated using nanoid, and an authorization URL is requested with scopes `links.read`, `links.write`, and `domains.read`. An interactive browser window opens automatically via the `open` package, pointing to the authorization endpoint on `app.dub.co`.
```typescript
export const login = new Command()
.name("login")
.description("Log into the Dub platform")
.action(async () => {
try {
const codeVerifier = getNanoid(64);
const redirectUri = "http://localhost:4587/callback";
const authUrl = await oauthClient.authorizationCode.getAuthorizeUri({
redirectUri,
codeVerifier,
scope: ["links.read", "links.write", "domains.read"],
});
const spinner = ora("Opening browser for authentication").start();
await open(authUrl);
spinner.text = "Waiting for authentication";
oauthCallbackServer({
oauthClient,
redirectUri,
codeVerifier,
spinner,
});
} catch (error) {
handleError(error);
}
```
Sources: [packages/cli/src/commands/login.ts:9-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts#L9-L37)
Concurrently, a local HTTP server listens on port `4587` specifically for the `/callback` path redirection from the authorization server.
```typescript
export function oauthCallbackServer({
oauthClient,
redirectUri,
codeVerifier,
spinner,
}: OAuthCallbackServerProps) {
const server = http.createServer(async (req, res) => {
const reqUrl = url.parse(req.url || "", true);
if (reqUrl.pathname !== "/callback" || req.method !== "GET") {
res.writeHead(404);
res.end("Not found");
return;
}
```
Sources: [packages/cli/src/api/callback.ts:17-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L17-L30)
> [!WARNING]
> The local OAuth callback server enforces a strict 5-minute timeout window (`300000` milliseconds), after which the server forcefully closes and terminates the process if authentication has not finished.
Sources: [packages/cli/src/api/callback.ts:80-84](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L80-L84)
Once the authorization code is received at the local loopback receiver, the CLI exchanges the code for tokens and persists the session configuration locally.
```typescript
try {
spinner.text = "Verifying";
const { accessToken, refreshToken, expiresAt } =
await oauthClient.authorizationCode.getToken({
code,
redirectUri,
codeVerifier,
});
spinner.text = "Configuring";
const configInfo: DubConfig = {
access_token: accessToken.trim(),
refresh_token: refreshToken,
expires_at: expiresAt,
domain: "dub.sh",
};
await setConfig(configInfo);
spinner.succeed("Configuration completed");
```
Sources: [packages/cli/src/api/callback.ts:43-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L43-L63)
### External Client Integration Parameters
External integrations and companion packages interact with Dub's OAuth endpoints by configuring parameters such as response types, grant types, and code challenge methods. The [Stripe App](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/stripe-app) integration builds authorization URLs with PKCE S256 parameters and exchanges codes directly via `POST` requests to the token endpoint.
| Parameter Name | Value / Type | Purpose |
| :--- | :--- | :--- |
| `response_type` | `"code"` | Specifies the authorization code grant flow |
| `code_challenge_method` | `"S256"` | Cryptographic hashing method for PKCE verification |
| `grant_type` | `"authorization_code"` / `"refresh_token"` | Token endpoint grant type specifier |
| `scope` | `["links.read", "links.write", "domains.read"]` | Requested permission scopes for CLI operations |
Sources: [packages/cli/src/commands/login.ts:20-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts#L20-L20), [packages/stripe-app/src/utils/oauth.ts:20-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L20-L27), [packages/stripe-app/src/utils/oauth.ts:51-54](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L51-L54), [packages/stripe-app/src/utils/oauth.ts:134-136](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/utils/oauth.ts#L134-L136)
## Related
- [Authentication](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/core-architecture/authentication)
- [REST API](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api)
---
## Technical docs: Scheduled Cron Tasks
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/scheduled-cron-tasks
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/vercel.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/vercel.json)
- [apps/web/app/ee/api/cron/sync-redis-resources/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/sync-redis-resources/route.ts)
- [apps/web/app/ee/api/cron/cleanup/orphaned/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/orphaned/route.ts)
- [apps/web/app/ee/api/cron/usage/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/usage/route.ts)
- [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts)
- [apps/web/app/ee/api/cron/import/tapfiliate/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/tapfiliate/route.ts)
- [apps/web/app/ee/api/cron/groups/remap-default-links/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts)
- [apps/web/app/ee/api/cron/domains/renewal-reminders/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-reminders/route.ts)
- [apps/web/app/ee/api/cron/domains/renewal-succeeded/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts)
- [apps/web/app/ee/api/cron/workspaces/delete/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/workspaces/delete/route.ts)
- [apps/web/app/ee/api/cron/fx-rates/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/fx-rates/route.ts)
- [apps/web/app/ee/api/cron/cleanup/e2e-tests/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts)
- [apps/web/app/ee/api/cron/domains/verify/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/verify/route.ts)
- [apps/web/app/ee/api/cron/rewards/queue-custom-commissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/rewards/queue-custom-commissions/route.ts)
- [apps/web/app/ee/api/cron/aggregate-clicks/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts)
- [apps/web/app/ee/api/cron/campaigns/queue-scheduled/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/campaigns/queue-scheduled/route.ts)
- [apps/web/app/ee/api/cron/sitemaps/import/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/sitemaps/import/route.ts)
- [apps/web/app/ee/api/cron/domains/renewal-payments/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts)
- [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts)
- [apps/web/app/ee/api/cron/disposable-emails/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/disposable-emails/route.ts)
- [apps/web/app/ee/api/cron/partner-platforms/website/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/partner-platforms/website/route.ts)
- [apps/web/app/ee/api/cron/import/lemonsqueezy/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts)
- [apps/web/app/ee/api/cron/cleanup/demo-embed-partners/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/demo-embed-partners/route.ts)
- [apps/web/app/ee/api/cron/bounties/queue-sync-social-metrics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts)
- [apps/web/app/ee/api/cron/cleanup/expired-fraud-groups/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/expired-fraud-groups/route.ts)
- [apps/web/app/ee/api/cron/payouts/force-withdrawals/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/force-withdrawals/route.ts)
- [apps/web/app/ee/api/cron/program-application-reminder/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/program-application-reminder/route.ts)
- [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts)
- [apps/web/app/ee/api/cron/partner-program-summary/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/import/bitly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/bitly/route.ts)
## Overview
Scheduled Cron Tasks orchestrates Dub's background maintenance, lifecycle automation, data synchronization, and deferred processing operations. Built to handle routine tasks across domains, [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs), link analytics, and billing, the system relies on scheduled Vercel cron jobs combined with Upstash QStash delivery to secure, queue, and execute backend routines reliably. These workflows solve problems related to database bloat, expired [domain management](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/link-attribution/domain-management), asynchronous metric collection, and partner commission settlement without overloading primary web service routes.
Sources: [apps/web/vercel.json:1-109](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/vercel.json#L1-L109), [apps/web/app/ee/api/cron/cleanup/orphaned/route.ts:1-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/orphaned/route.ts#L1-L48), [apps/web/app/ee/api/cron/domains/verify/route.ts:1-108](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/verify/route.ts#L1-L108)
## Execution Middleware and Authentication
### Cron Endpoint Protection and Signature Verification
Cron endpoints expose public HTTP handlers marked with `export const dynamic = "force-dynamic"` to bypass static rendering. To prevent unauthorized invocation, these routes protect their execution entry points using either a higher-order wrapper or direct signature validation against Upstash QStash headers.
The usage update cron endpoint wraps its handler with `withCron`, which encapsulates authentication checks before invoking the underlying routine:
```typescript
export const POST = withCron(async () => {
const result = await updateUsage();
return logAndRespond(result);
});
```
Sources: [apps/web/app/ee/api/cron/usage/route.ts:1-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/usage/route.ts#L1-L14)
Conversely, the link retention cleanup endpoint explicitly reads the raw request text to verify its QStash signature before parsing the request payload with Zod:
```typescript
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({
req,
rawBody,
});
const { domain: passedDomain } = z
.object({
domain: z.string().optional(),
})
.parse(JSON.parse(rawBody));
```
Sources: [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts:16-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts#L16-L29)
> [!WARNING]
> Failing to supply or validate the raw request body against `verifyQstashSignature` permits arbitrary payload spoofing, bypassing the cryptographic guarantees provided by Upstash QStash delivery channels.
Sources: [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts:18-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts#L18-L23)
## Domain Renewal and Lifecycle Automation
### Domain Renewal Reminder Notifications
Dub automates `.link` domain expiration alerts through a daily cron job that evaluates active, non-disabled domains against specific countdown thresholds. The renewal reminder sequence evaluates domains where `autoRenewalDisabledAt` is null across three distinct intervals prior to expiration.
| Reminder Stage | Days Prior to Expiration | Target Date Range Calculation |
| :--- | :--- | :--- |
| First Reminder | 30 days | `subDays(now, -30)` |
| Second Reminder | 23 days | `subDays(now, -23)` |
| Third Reminder | 16 days | `subDays(now, -16)` |
Sources: [apps/web/app/ee/api/cron/domains/renewal-reminders/route.ts:16-54](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-reminders/route.ts#L16-L54)
When eligible domains are identified, the system loads workspace owner records and maps out reminder payloads containing the domain slug, expiration date, renewal fee, charge date (fixed at 14 days prior to expiration), and human-readable text formatting. Batches of up to 100 emails are dispatched via `sendBatchEmail` using the `DomainRenewalReminder` React-email template with the `notifications` variant.
```typescript
const reminderDomainsChunks = chunk(reminderDomains, 100);
for (const reminderDomainsChunk of reminderDomainsChunks) {
const res = await sendBatchEmail(
reminderDomainsChunk.map(({ workspace, user, domain }) => ({
to: user.email!,
subject: "Your domain is expiring soon",
variant: "notifications",
react: DomainRenewalReminder({
email: user.email!,
workspace,
domain,
}),
})),
);
console.log(`Sent ${reminderDomainsChunk.length} emails`, res);
}
```
Sources: [apps/web/app/ee/api/cron/domains/renewal-reminders/route.ts:104-120](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-reminders/route.ts#L104-L120)
### Payment Intent Generation and Invoice Creation
Fourteen days before a registered domain expires, a separate cron routine queries for eligible domains and initiates payment processing. The routine groups domains by workspace ID, generates sequential invoice numbers using workspace-specific prefixes, and records a `domainRenewal` invoice inside a Prisma transaction.
```typescript
const invoice = await prisma.$transaction(async (tx) => {
const totalInvoices = await tx.invoice.count({
where: {
workspaceId: workspace.id,
},
});
const paddedNumber = String(totalInvoices + 1).padStart(4, "0");
const invoiceNumber = `${workspace.invoicePrefix}-${paddedNumber}`;
const totalAmount = domains.reduce(
(acc, domain) => acc + domain.renewalFee,
0,
);
return await tx.invoice.create({
data: {
id: createId({ prefix: "inv_" }),
workspaceId: workspace.id,
number: invoiceNumber,
type: "domainRenewal",
amount: totalAmount,
total: totalAmount,
registeredDomains: domains.map(({ slug }) => slug), // array of domain slugs,
},
});
});
```
Sources: [apps/web/app/ee/api/cron/domains/renewal-payments/route.ts:30-117](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts#L30-L117)
> [!NOTE]
> If a renewal payment targets the special `ACME_WORKSPACE_ID`, the routine automatically substitutes its Stripe configuration with the `DUB_WORKSPACE_ID` stripe identifier to bill against the correct platform account.
Sources: [apps/web/app/ee/api/cron/domains/renewal-payments/route.ts:131-147](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts#L131-L147)
Following invoice creation, Stripe payment intents are dispatched for each invoice with the statement descriptor `DUB.CO DOMAIN RENEWAL`, utilizing an idempotency key composed of the invoice identifier and its failed attempt count.
Sources: [apps/web/app/ee/api/cron/domains/renewal-payments/route.ts:127-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts#L127-L164)
### Success Confirmation and Registrar Extension
Upon successful payment settlement, the `renewal-succeeded` cron routine validates the incoming payload against an `invoiceId` schema, ensuring the invoice is marked as `completed` with a valid `paidAt` timestamp and a type of `domainRenewal`.
```typescript
const inputSchema = z.object({
invoiceId: z.string(),
});
```
Sources: [apps/web/app/ee/api/cron/domains/renewal-succeeded/route.ts:17-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts#L17-L25)
The service parses domain slugs from the invoice record and processes renewals in batches of 5. For each domain, it invokes `setRenewOption` against the Dynadot registrar API, calculates the new expiration date by extending the term by 365 days from either the existing expiration date or today (whichever is later), and updates the database record while clearing any prior `autoRenewalDisabledAt` flags.
```typescript
const renewalBase =
domain.expiresAt > todayStart ? domain.expiresAt : todayStart;
succeeded.push({
domain,
newExpiresAt: addDays(renewalBase, 365),
});
```
Sources: [apps/web/app/ee/api/cron/domains/renewal-succeeded/route.ts:98-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts#L98-L129)
> [!CAUTION]
> If any domain update fails against Dynadot during batch execution, the cron routine records an error log, triggers an internal system notification mentioning relevant personnel, and throws an exception to abort execution and force a retry.
Sources: [apps/web/app/ee/api/cron/domains/renewal-succeeded/route.ts:155-170](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts#L155-L170)
If all domains renew successfully, workspace owners receive a transactional success email using the `DomainRenewed` React-email template, displaying the earliest new expiration date across all renewed domains in the batch.
Sources: [apps/web/app/ee/api/cron/domains/renewal-succeeded/route.ts:178-225](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/renewal-succeeded/route.ts#L178-L225)
## Data Cleanup and Cascade Deletion
### Link Retention and Expired Fraud Groups
The link retention cleanup routine executes every 12 hours via the cron expression `0 */12 * * *` to purge outdated links for domains configured with a retention policy. The handler verifies incoming requests via `verifyQstashSignature` and processes either all matching domains or a specific domain slug passed in the request body.
```typescript
// This route is used to delete old links for domains with linkRetentionDays set
// Runs once every 12 hours (0 */12 * * *)
// POST /api/cron/cleanup/link-retention
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({
req,
rawBody,
});
const { domain: passedDomain } = z
.object({
domain: z.string().optional(),
})
.parse(JSON.parse(rawBody));
if (!passedDomain) {
const domains = await prisma.domain.findMany({
where: {
linkRetentionDays: {
not: null,
},
},
});
await Promise.all(domains.map((domain) => deleteOldLinks(domain)));
} else {
const domain = await prisma.domain.findUniqueOrThrow({
where: {
slug: passedDomain,
},
});
await deleteOldLinks(domain);
}
```
Sources: [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts:13-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts#L13-L49)
For each domain, the worker queries up to 10 batches of 100 links (`LINKS_PER_BATCH = 100`, `MAX_LINK_BATCHES = 10`) created earlier than the retention threshold (`domain.linkRetentionDays`) and lacking any `linkRetentionCleanupDisabledAt` timestamp. Links are deleted in bulk using `bulkDeleteLinks`, with a 250ms pause between batches. If the batch limit is reached and more links remain (`hasMoreLinks`), the worker publishes a continuation job back to QStash for the same domain slug.
```typescript
const LINKS_PER_BATCH = 100;
const MAX_LINK_BATCHES = 10;
async function deleteOldLinks(
domain: Pick,
) {
if (
!domain.linkRetentionDays ||
!domain.projectId ||
domain.linkRetentionDays <= 0
)
return;
let processedBatches = 0;
let hasMoreLinks = false;
while (processedBatches < MAX_LINK_BATCHES) {
const links = await prisma.link.findMany({
where: {
domain: domain.slug,
createdAt: {
lt: new Date(
Date.now() - 1000 * 60 * 60 * 24 * domain.linkRetentionDays,
),
},
linkRetentionCleanupDisabledAt: null,
},
orderBy: {
createdAt: "asc",
},
take: LINKS_PER_BATCH,
});
console.log(
`[Link retention cleanup] Found ${links.length} links to delete for ${domain.slug} that are older than ${domain.linkRetentionDays} days`,
);
if (links.length === 0) break;
// Check if we might have more links (if we got a full batch)
hasMoreLinks = links.length === LINKS_PER_BATCH;
console.log(
`[Link retention cleanup] Deleting ${links.length} links for ${domain.slug} (batch ${processedBatches + 1})...`,
);
console.table(links, ["shortLink", "createdAt"]);
await bulkDeleteLinks(links);
++processedBatches;
// sleep for 250ms
await sleep(250);
}
// Only schedule another run if we hit the batch limit AND we found a full batch
// (indicating there might be more links to process)
if (processedBatches >= MAX_LINK_BATCHES && hasMoreLinks) {
await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/cleanup/link-retention`,
method: "POST",
body: {
domain: domain.slug,
},
});
}
```
Sources: [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts:56-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts#L56-L122)
> [!WARNING]
> Links possessing an active `linkRetentionCleanupDisabledAt` flag are explicitly excluded from retention purges, protecting preserved links from automated deletion even if they exceed the domain's retention window.
Sources: [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts:73-82](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts#L73-L82)
Separately, the expired fraud groups cleanup job runs daily at 02:30 AM UTC (`30 2 * * *`) to expire pending fraud event groups that have remained inactive past their expiration window.
```typescript
// Runs once every day at 02:30:00 AM UTC (30 2 * * *)
// POST /api/cron/cleanup/expired-fraud-groups
export const POST = withCron(async () => {
let expiredCount = 0;
while (true) {
const groupsToExpire = await prisma.fraudEventGroup.findMany({
where: {
status: "pending",
type: {
notIn: NON_EXPIRING_FRAUD_RULE_TYPES,
},
lastEventAt: {
lt: subDays(new Date(), FRAUD_GROUP_EXPIRY_DAYS),
},
},
select: {
id: true,
},
take: BATCH_SIZE,
});
```
Sources: [apps/web/app/ee/api/cron/cleanup/expired-fraud-groups/route.ts:17-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/expired-fraud-groups/route.ts#L17-L36)
The routine queries `FraudEventGroup` records in batches of 250 where the status is `pending`, the type is not included in `NON_EXPIRING_FRAUD_RULE_TYPES`, and `lastEventAt` falls past `FRAUD_GROUP_EXPIRY_DAYS`. Matching groups are updated to an `expired` status, triggering a queued release of hold commissions via `queueReleaseHoldCommissions`.
```typescript
const { count } = await prisma.fraudEventGroup.updateMany({
where: {
id: {
in: groupIds,
},
status: "pending",
},
data: {
status: "expired",
},
});
expiredCount += count;
console.log(`Expired ${count} fraud groups`);
if (count > 0) {
await queueReleaseHoldCommissions(groupIds);
}
```
Sources: [apps/web/app/ee/api/cron/cleanup/expired-fraud-groups/route.ts:44-61](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/expired-fraud-groups/route.ts#L44-L61)
### Orphaned Records and Test Fixture Purges
The orphaned record cleanup cron routine (`POST /api/cron/cleanup/orphaned`) hard-deletes leftover database rows that were previously soft-deleted or unassigned during request-path operations. Utilizing a staleness cutoff of 60 minutes (`STALE_AFTER_MINUTES = 60`), it executes four parallel cleanup handlers via `Promise.all`:
```typescript
export const POST = withCron(async () => {
const cutoff = subMinutes(new Date(), STALE_AFTER_MINUTES);
const [
deletedRewardsCount,
deletedDiscountsCount,
deletedDefaultLinksCount,
deletedLinkRewardsCount,
] = await Promise.all([
deleteOrphanedRewards(cutoff),
deleteOrphanedDiscounts(cutoff),
deleteOrphanedDefaultLinks(cutoff),
deleteEmptyLinkRewards(),
]);
```
Sources: [apps/web/app/ee/api/cron/cleanup/orphaned/route.ts:25-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/orphaned/route.ts#L25-L38)
| Cleanup Function | Target Entity | Removal Condition / Mechanism |
| :--- | :--- | :--- |
| `deleteOrphanedRewards` | Rewards | Hard-deleted once enrollments are cleared and no references remain (`programId` is null). |
| `deleteOrphanedDiscounts` | Discounts | Hard-deleted once codes are detached and no references remain (`programId` is null). |
| `deleteOrphanedDefaultLinks` | PartnerGroupDefaultLinks | Hard-deleted once group deletion unassigns the row (`groupId` is null) and no links reference it. |
| `deleteEmptyLinkRewards` | LinkRewards | Purged when override IDs or discount IDs have been nullified. |
Sources: [apps/web/app/ee/api/cron/cleanup/orphaned/route.ts:13-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/orphaned/route.ts#L13-L38)
Test fixture cleanup runs every 6 hours to purge resources created during end-to-end testing, scoped to specific test constants (`E2E_USER_ID = "clxz1q7c7000hbqx5ckv4r82h"`, `E2E_WORKSPACE_ID = "clrei1gld0002vs9mzn93p8ik"`).
```typescript
const E2E_USER_ID = "clxz1q7c7000hbqx5ckv4r82h";
const E2E_WORKSPACE_ID = "clrei1gld0002vs9mzn93p8ik";
// This route is used to remove links, domains and tags created during our E2E tests.
// Runs every 6 hours (0 * / 6 * * *)
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({
req,
rawBody,
});
const oneDayAgo = new Date(Date.now() - 1000 * 60 * 60 * 24);
const [links, domains, tags, partners, users] = await Promise.all([
prisma.link.findMany({
where: {
userId: E2E_USER_ID,
projectId: E2E_WORKSPACE_ID,
createdAt: {
lt: oneDayAgo,
},
},
include: {
...includeTags,
...includeProgramEnrollment,
},
take: 100,
}),
prisma.domain.findMany({
where: {
projectId: E2E_WORKSPACE_ID,
slug: {
endsWith: ".dub-internal-test.com",
},
createdAt: {
lt: oneDayAgo,
},
},
select: {
slug: true,
},
}),
prisma.tag.findMany({
where: {
projectId: E2E_WORKSPACE_ID,
name: {
startsWith: "e2e-",
},
createdAt: {
lt: oneDayAgo,
},
},
}),
prisma.partner.findMany({
where: {
email: {
endsWith: "@dub-internal-test.com",
},
createdAt: {
lt: oneDayAgo,
},
},
select: {
id: true,
},
}),
prisma.user.findMany({
where: {
email: {
endsWith: "@dub-internal-test.com",
},
createdAt: {
lt: oneDayAgo,
```
Sources: [apps/web/app/ee/api/cron/cleanup/e2e-tests/route.ts:14-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts#L14-L97)
The worker queries records older than one day (`oneDayAgo`) matching test patterns across five tables and disposes of them using specific deletion workflows: links via `bulkDeleteLinks`, domains ending in `.dub-internal-test.com` via `markDomainAsDeleted`, tags starting with `e2e-` via `prisma.tag.deleteMany`, partners ending in `@dub-internal-test.com` via `bulkDeletePartners`, and test users via `prisma.user.deleteMany`.
```typescript
// Delete the links
if (links.length > 0) {
await bulkDeleteLinks(links);
}
// Delete the domains
if (domains.length > 0) {
await Promise.all(
domains.map(({ slug }) =>
markDomainAsDeleted({
domain: slug,
}),
),
);
}
// Delete the tags
if (tags.length > 0) {
await prisma.tag.deleteMany({
where: {
id: {
in: tags.map((tag) => tag.id),
},
},
});
}
// Delete the partners
if (partners.length > 0) {
await bulkDeletePartners({
partnerIds: partners.map((partner) => partner.id),
deletePartners: true,
});
}
if (users.length > 0) {
await prisma.user.deleteMany({
where: {
id: {
in: users.map((user) => user.id),
},
},
});
}
```
Sources: [apps/web/app/ee/api/cron/cleanup/e2e-tests/route.ts:99-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/e2e-tests/route.ts#L99-L142)
## Partner and Affiliate Synchronization
### Affiliate Platform Ingestion Routes
Dub coordinates external affiliate platform synchronizations through dedicated cron endpoints that ingest payloads using Zod schemas before dispatching them to specific handler functions. The Tapfiliate import route (`POST /api/cron/import/tapfiliate`) parses incoming JSON bodies against `tapfiliateImportPayloadSchema` and routes execution via a `switch` statement on `payload.action`.
```typescript
export const POST = withCron(async ({ rawBody }) => {
const payload = tapfiliateImportPayloadSchema.parse(JSON.parse(rawBody));
switch (payload.action) {
case "import-groups":
await importGroups(payload);
break;
case "import-partners":
await importPartners(payload);
break;
case "import-customers":
await importCustomers(payload);
break;
case "import-commissions":
await importCommissions(payload);
break;
case "update-stripe-customers":
await updateStripeCustomers(payload);
break;
case "cleanup-partners":
await cleanupPartners(payload);
break;
}
```
Sources: [apps/web/app/ee/api/cron/import/tapfiliate/route.ts:13-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/tapfiliate/route.ts#L13-L35)
| Tapfiliate Action | Handler Function | Purpose |
| :--- | :--- | :--- |
| `import-groups` | `importGroups(payload)` | Synchronizes affiliate groups and tier hierarchies. |
| `import-partners` | `importPartners(payload)` | Imports affiliate profiles and associates them with partner records. |
| `import-customers` | `importCustomers(payload)` | Syncs referred customers and referral associations. |
| `import-commissions` | `importCommissions(payload)` | Ingests historical or pending commission records. |
| `update-stripe-customers` | `updateStripeCustomers(payload)` | Reconciles external customer identifiers with Stripe billing data. |
| `cleanup-partners` | `cleanupPartners(payload)` | Removes orphaned or deactivated import artifacts. |
Sources: [apps/web/app/ee/api/cron/import/tapfiliate/route.ts:16-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/tapfiliate/route.ts#L16-L34)
Similarly, the Lemon Squeezy import route (`POST /api/cron/import/lemonsqueezy`) validates requests using `lemonSqueezyImportPayloadSchema` and routes actions to platform-specific modules.
```typescript
export const POST = withCron(async ({ rawBody }) => {
const payload = lemonSqueezyImportPayloadSchema.parse(JSON.parse(rawBody));
switch (payload.action) {
case "import-partners":
await importPartners(payload);
break;
case "import-customers":
await importCustomers(payload);
break;
case "import-commissions":
await importCommissions(payload);
break;
}
```
Sources: [apps/web/app/ee/api/cron/import/lemonsqueezy/route.ts:10-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts#L10-L23)
| Lemon Squeezy Action | Handler Function | Purpose |
| :--- | :--- | :--- |
| `import-partners` | `importPartners(payload)` | Ingests affiliate profiles from Lemon Squeezy. |
| `import-customers` | `importCustomers(payload)` | Syncs customer transactions and buyer references. |
| `import-commissions` | `importCommissions(payload)` | Processes imported affiliate earnings and payouts. |
Sources: [apps/web/app/ee/api/cron/import/lemonsqueezy/route.ts:13-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts#L13-L22)
### Default Link Remapping and Website Ratings
When partners are moved between groups, the default link remapping job (`POST /api/cron/groups/remap-default-links`) verifies QStash signatures and extracts `programId`, `groupId`, `partnerIds`, and `userId` to synchronize partner link assignments against new group configurations.
```typescript
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
const { programId, groupId, partnerIds, userId } = schema.parse(
JSON.parse(rawBody),
);
```
Sources: [apps/web/app/ee/api/cron/groups/remap-default-links/route.ts:42-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts#L42-L49)
> [!NOTE]
> If an emptied source group is deleted before remapping finishes, its default links are soft-deleted with a null `groupId`, ensuring `partnerGroupDefaultLinkId` remains intact until the background job completes the remapping lifecycle.
Sources: [apps/web/app/ee/api/cron/groups/remap-default-links/route.ts:36-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts#L36-L39)
To keep partner platform metrics updated, the website rating cron route (`GET /api/cron/partner-platforms/website`) runs once per minute to update Domain Rating (DR) metrics for verified website partners using the Ahrefs API.
```typescript
export const GET = withCron(async () => {
const websites = await prisma.partnerPlatform.findMany({
where: {
type: PlatformType.website,
verifiedAt: {
not: null,
},
// only check websites that haven't been checked in the last 24 hours
lastCheckedAt: {
lt: new Date(Date.now() - 1000 * 60 * 60 * 24),
},
},
take: BATCH_SIZE,
orderBy: {
lastCheckedAt: "asc",
},
});
```
Sources: [apps/web/app/ee/api/cron/partner-platforms/website/route.ts:18-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/partner-platforms/website/route.ts#L18-L34)
The worker processes platforms with strict concurrency and batch controls (`BATCH_SIZE = 60`, `CONCURRENCY = 5`), selecting records where `type` is `website`, `verifiedAt` is not null, and `lastCheckedAt` exceeds 24 hours.
```typescript
const BATCH_SIZE = 60;
const CONCURRENCY = 5;
…
const websiteChunks = chunk(websites, CONCURRENCY);
for (const websiteChunk of websiteChunks) {
```
Sources: [apps/web/app/ee/api/cron/partner-platforms/website/route.ts:10-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/partner-platforms/website/route.ts#L10-L11), [apps/web/app/ee/api/cron/partner-platforms/website/route.ts:40-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/partner-platforms/website/route.ts#L40-L42)
### Demo Embed Partner Maintenance
The demo embed cleanup cron (`POST /api/cron/cleanup/demo-embed-partners`) runs hourly to purge non-whitelisted program enrollments from the Acme demo program (`ACME_PROGRAM_ID`) created over one hour ago.
```typescript
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({
req,
rawBody,
});
const programEnrollmentsToDelete = await prisma.programEnrollment.findMany({
where: {
programId: ACME_PROGRAM_ID,
createdAt: {
lt: subHours(new Date(), 1), // 1 hour ago
},
```
Sources: [apps/web/app/ee/api/cron/cleanup/demo-embed-partners/route.ts:13-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/demo-embed-partners/route.ts#L13-L27)
> [!WARNING]
> Program enrollments associated with internal test email domains (`@dub.co`, `@dub-internal-test.com`) and specific whitelisted fixture accounts are explicitly excluded from deletion, protecting core showcase data from being purged by the hourly cycle.
Sources: [apps/web/app/ee/api/cron/cleanup/demo-embed-partners/route.ts:28-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/demo-embed-partners/route.ts#L28-L58)
## Commission Aggregation and Payout Triggers
### Periodic Commission Aggregation and Batching
The aggregate due commissions cron route (`GET /api/cron/payouts/aggregate-due-commissions`) runs once every hour (`0 * * * *`) with a maximum execution duration of 600 seconds to convert pending commissions past their holding period into structured payouts.
```typescript
export const maxDuration = 600;
export const dynamic = "force-dynamic";
// This cron job aggregates due commissions (pending commissions that are past the partner group's holding period) into payouts.
// Runs once every hour (0 * * * *) + calls itself recursively to look through all pending commissions available.
// GET /api/cron/payouts/aggregate-due-commissions
export const GET = withCron(async () => {
```
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts:9-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts#L9-L15)
The handler queries programs that contain at least one commission with a `pending` status, extracts their unique identifiers, and chunks them into groups of 50 to prevent database exhaustion.
```typescript
const programsWithPendingCommissions = await prisma.program.findMany({
where: {
commissions: {
some: {
status: CommissionStatus.pending,
},
},
},
select: {
id: true,
},
});
const programIds = programsWithPendingCommissions.map((p) => p.id);
if (programIds.length === 0) {
return logAndRespond("No programs with due commissions found. Skipping...");
}
console.log(`Found ${programIds.length} programs with pending commissions.`);
// process 50 programs at a time to avoid overwhelming the database
const programIdChunks = chunk(programIds, 50);
```
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts:16-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts#L16-L38)
Each program chunk is dispatched to Upstash QStash via `qstash.batchJSON` with a staggered delay of 10 seconds per chunk index (`index * 10`). Every published job specifies a strict deduplication ID and flow control configuration with a parallelism limit of 1.
```typescript
for (const [index, programIdChunk] of programIdChunks.entries()) {
const delaySeconds = index * 10; // delay by 10s between program chunks
const jobs: PublishBatchRequest<{ programId: string }>[] =
programIdChunk.map((programId) => ({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/aggregate-due-commissions/process`,
body: {
programId,
},
deduplicationId: `aggregate-due-commissions-${programId}`,
label: "aggregate-due-commissions",
flowControl: {
key: `aggregate-due-commissions-${programId}`,
parallelism: 1,
},
delay: delaySeconds,
}));
await qstash.batchJSON(jobs);
console.log(
`Enqueued index ${index + 1}/${programIdChunks.length} jobs to be processed (with ${delaySeconds}s delay).`,
);
}
```
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts:40-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts#L40-L63)
> [!NOTE]
> The deduplication identifier format `aggregate-due-commissions-${programId}` ensures that concurrent or overlapping execution attempts for the same program are safely collapsed by QStash.
Sources: [apps/web/app/ee/api/cron/payouts/aggregate-due-commissions/route.ts:49-54](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts#L49-L54)
### Force Withdrawals and Account Reminders
To handle stagnant affiliate funds, the force-withdrawals cron route (`GET/POST /api/cron/payouts/force-withdrawals`) runs daily at 5:00 AM PST (`0 12 * * *`). It processes partners whose processed payouts meet or exceed `MIN_FORCE_WITHDRAWAL_AMOUNT_CENTS` and have remained unwithdrawn for more than 90 days.
```typescript
// This route is used to force withdrawals for partners that haven't withdrew their earnings for than 90 days
// Runs once a day at 5AM PST (0 12 * * *) + calls itself recursively to process all partners in batches
// GET/POST /api/cron/payouts/force-withdrawals
export const GET = withCron(async ({ rawBody }) => {
let { startingAfter } = schema.parse(rawBody ? JSON.parse(rawBody) : {});
// Get batch of partners with processed payouts (cursor-based pagination)
const partnersToProcess = await prisma.partner.findMany({
where: {
payoutsEnabledAt: {
not: null,
},
defaultPayoutMethod: {
in: ["stablecoin", "connect"],
},
payouts: {
some: {
status: "processed",
amount: {
gte: MIN_FORCE_WITHDRAWAL_AMOUNT_CENTS,
},
paidAt: {
lte: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000), // 90 days ago
},
},
},
```
Sources: [apps/web/app/ee/api/cron/payouts/force-withdrawals/route.ts:18-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/force-withdrawals/route.ts#L18-L44)
| Parameter / Constant | Value / Type | Purpose |
| :--- | :--- | :--- |
| `BATCH_SIZE` | `20` | Number of partner records processed per execution batch. |
| `defaultPayoutMethod` | `["stablecoin", "connect"]` | Eligible withdrawal channels for forced settlement. |
| `payouts.status` | `"processed"` | Filter requiring payouts to be marked as processed. |
| `paidAt` | `lte: 90 days ago` | Age threshold triggering mandatory withdrawal action. |
Sources: [apps/web/app/ee/api/cron/payouts/force-withdrawals/route.ts:10-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/force-withdrawals/route.ts#L10-L44)
The router processes partners in batches of 20 using cursor-based pagination sorted by ascending identifier (`id: "asc"`). If more records remain (`hasMoreToProcess`), it recursively enqueues the next batch via QStash using the last processed partner's identifier as `startingAfter`.
```typescript
take: BATCH_SIZE,
orderBy: {
id: "asc",
},
...(startingAfter && {
skip: 1,
cursor: {
id: startingAfter,
},
}),
select: {
id: true,
defaultPayoutMethod: true,
},
});
if (!partnersToProcess.length) {
return logAndRespond(
"No partners to process. Skipping force withdrawals...",
);
}
const hasMoreToProcess = partnersToProcess.length === BATCH_SIZE;
console.log(
`Found ${partnersToProcess.length} partners to process${hasMoreToProcess ? " (more to process)" : ""}`,
);
await Promise.allSettled(
partnersToProcess.map((partner) => forceWithdrawal(partner)),
);
if (hasMoreToProcess) {
console.log(
"More partners need force withdrawals, scheduling next batch...",
);
const nextStartingAfter =
partnersToProcess[partnersToProcess.length - 1].id;
const qstashResponse = await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/force-withdrawals`,
method: "POST",
body: {
startingAfter: nextStartingAfter,
},
});
```
Sources: [apps/web/app/ee/api/cron/payouts/force-withdrawals/route.ts:46-92](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/payouts/force-withdrawals/route.ts#L46-L92)
In parallel, the program application reminder job route (`POST /api/cron/program-application-reminder`) executes `programApplicationReminderJob` to target unverified program applicants [Email Notification](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/email-notification).
```typescript
// POST - /api/cron/program-application-reminder
// Sends an email to a program application email if they haven't verified their account on Dub yet
// TODO: Remove this route once in-flight QStash messages to this URL have drained (~3 days after deploy)
export const POST = withCron(async ({ rawBody }) => {
await programApplicationReminderJob.execute(JSON.parse(rawBody));
return logAndRespond("Program application reminder processed.");
```
Sources: [apps/web/app/ee/api/cron/program-application-reminder/route.ts:7-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/program-application-reminder/route.ts#L7-L12)
## External Ingestion and Telemetry Sync
### Foreign Exchange Rates and Email Blocklists
The foreign exchange synchronization task (`POST /api/cron/fx-rates`) runs daily at 08:00 AM UTC (`0 8 * * *`) to fetch latest currency values from `currencyApiClient.getLatest()`. It transforms the response entries into a ticker-to-value map and stores them in Redis under the hash key `fxRates:usd`.
```typescript
export const POST = withCron(async () => {
const { data } = await currencyApiClient.getLatest();
const transformedRates: Record = {};
for (const [ticker, details] of Object.entries(data)) {
transformedRates[ticker] = details.value;
}
// Store FX rates in Redis (with USD as the base currency)
await redis.hset("fxRates:usd", transformedRates);
return logAndRespond(
`Updated ${Object.keys(transformedRates).length} FX rates.`,
);
```
Sources: [apps/web/app/ee/api/cron/fx-rates/route.ts:11-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/fx-rates/route.ts#L11-L25)
Similarly, the disposable email synchronization task (`POST /api/cron/disposable-emails`) runs every Monday at noon UTC (`0 12 * * 1`) to ingest domain blocklists from external sources and update Redis sets without downtime [Caching & Rate Limiting](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/core-architecture/caching-rate-limiting).
```typescript
export const POST = withCron(async () => {
const [disposableRes, tremendousRes] = await Promise.allSettled([
fetch(
"https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/master/disposable_email_blocklist.conf",
),
fetch("https://api.tremendous.com/prohibited_email_domains.txt"),
]);
if (disposableRes.status === "rejected") {
console.warn(
`Failed to fetch disposable email domains list: ${disposableRes.status} ${disposableRes.reason}`,
);
}
if (tremendousRes.status === "rejected") {
console.warn(
`Failed to fetch Tremendous prohibited email domains list: ${tremendousRes.status} ${tremendousRes.reason}`,
);
}
const disposableDomains =
disposableRes.status === "fulfilled"
? (await disposableRes.value.text()).split("\n").filter(Boolean)
: [];
const tremendousDomains =
tremendousRes.status === "fulfilled"
? (await tremendousRes.value.text())
.split("\n")
.map((d) => d.trim().toLowerCase())
.filter(Boolean)
: [];
if (disposableDomains.length > 0) {
// Use temporary sets to avoid emptying the old sets
await redis.del("disposableEmailDomainsTmp");
await redis.sadd(
"disposableEmailDomainsTmp",
...(disposableDomains as [string]),
);
await redis.rename("disposableEmailDomainsTmp", "disposableEmailDomains");
}
if (tremendousDomains.length > 0) {
await redis.del("tremendousProhibitedEmailDomainsTmp");
await redis.sadd(
"tremendousProhibitedEmailDomainsTmp",
...(tremendousDomains as [string]),
);
await redis.rename(
"tremendousProhibitedEmailDomainsTmp",
"tremendousProhibitedEmailDomains",
);
}
return logAndRespond(
`Synced ${disposableDomains.length} disposable and ${tremendousDomains.length} Tremendous prohibited email domains.`,
);
```
Sources: [apps/web/app/ee/api/cron/disposable-emails/route.ts:10-67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/disposable-emails/route.ts#L10-L67)
| Source URL | Redis Temporary Set | Redis Final Set Key | Purpose |
| :--- | :--- | :--- | :--- |
| `disposable_email_blocklist.conf` | `disposableEmailDomainsTmp` | `disposableEmailDomains` | Blocks temporary disposable email domains. |
## Related
- [Queue Workers](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/queue-workers)
- [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement)
---
## Technical docs: PATCH Update marketplace program details
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/patchadminprogram
## Parameters
## Request Body
Program update fields
## Responses
## Try It
---
## Technical docs: Queue Workers
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/queue-workers
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/api/cron/streams/send-link-clicked-webhooks/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/send-link-clicked-webhooks/route.ts)
- [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts)
- [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts)
- [apps/web/app/ee/api/cron/export/events/workspace/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/export/events/workspace/route.ts)
- [apps/web/app/ee/api/cron/usage/utils.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/usage/utils.ts)
- [apps/web/lib/upstash/redis-streams/workspace-links-usage.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-links-usage.ts)
- [apps/web/app/ee/api/cron/queue/retry/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/queue/retry/route.ts)
- [apps/web/app/ee/api/cron/rewards/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/rewards/process/route.ts)
- [apps/web/app/ee/api/cron/domains/transfer/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/domains/transfer/route.ts)
- [apps/web/lib/upstash/redis-streams/workspace-click-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-click-events.ts)
- [apps/web/lib/upstash/redis-streams/link-click-events.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/link-click-events.ts)
- [apps/web/lib/jobs/outbox.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts)
- [apps/web/app/ee/api/cloudflare/webhook/r2-object-created/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cloudflare/webhook/r2-object-created/route.ts)
- [apps/web/app/ee/api/cron/sync-redis-resources/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/sync-redis-resources/route.ts)
- [apps/web/app/ee/api/cron/aggregate-clicks/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts)
- [apps/web/lib/jobs/send-workflows.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/send-workflows.ts)
- [apps/web/app/ee/api/stripe/webhook/utils/update-workspace-plan.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts)
- [apps/web/app/ee/api/cron/workspaces/delete/utils.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/workspaces/delete/utils.ts)
- [apps/web/app/ee/api/cron/streams/update-partner-stats/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts)
- [apps/web/app/ee/api/cron/cleanup/link-retention/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/link-retention/route.ts)
- [apps/web/lib/jobs/handlers/process-shopify-order-job.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/process-shopify-order-job.ts)
- [apps/web/lib/webhook/failure.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/failure.ts)
- [apps/web/lib/webhook/click-webhook-workspaces.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/click-webhook-workspaces.ts)
- [apps/web/app/api/jobs/process/jobName/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/jobs/process/%5BjobName%5D/route.ts)
- [apps/web/lib/upstash/redis-streams/client.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/client.ts)
- [apps/web/lib/api/rewards/queue-reward-processing.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/api/rewards/queue-reward-processing.ts)
- [apps/web/app/ee/api/cron/sync-redis-resources/cleanup-redundant-link-webhook-entries.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/sync-redis-resources/cleanup-redundant-link-webhook-entries.ts)
- [apps/web/lib/jobs/handlers/partner-search-sync-job.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/partner-search-sync-job.ts)
- [apps/web/lib/integrations/shopify/checkout-cache.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/shopify/checkout-cache.ts)
- [apps/web/lib/jobs/handlers/process-partner-group-change-job.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/process-partner-group-change-job.ts)
## Overview
Dub implements a resilient queue worker and event-streaming architecture built around Upstash Redis streams and QStash job dispatching. High-frequency telemetry—such as link clicks and workspace usage updates—is ingested into Redis streams and processed in batch consumers by cron routines with distributed locking. For transactional background tasks, the system uses a database-backed outbox pattern that persists failed QStash publishes for automated retry recovery. Asynchronous jobs route through dynamic endpoints and type-safe job definitions to execute domain-specific workflows for partner searches, order processing, and aggregate analytics.
Sources: [apps/web/app/ee/api/cron/streams/send-link-clicked-webhooks/route.ts:5-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/send-link-clicked-webhooks/route.ts#L5-L65), [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:3-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L3-L112), [apps/web/app/ee/api/cron/queue/retry/route.ts:1-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/queue/retry/route.ts#L1-L46), [apps/web/lib/jobs/outbox.ts:88-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts#L88-L122), [apps/web/app/api/jobs/process/jobName/route.ts:11-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/jobs/process/%5BjobName%5D/route.ts#L11-L105)
## Redis Stream Pipeline Infrastructure
### Stream Operations and Client Abstraction
The `RedisStream` class encapsulates interaction with Upstash Redis streams, providing methods for batch message reading, transactional deletion, and metadata inspection. It initializes with a designated `streamKey` and exposes `processBatch` to fetch ranges of stream entries using `redis.xrange`, execute a handler function against them, and optionally delete successfully processed messages via `redis.xdel` to prevent memory accumulation.
```typescript
export class RedisStream {
private streamKey: string;
constructor(streamKey: string) {
this.streamKey = streamKey;
}
/**
* Read and process a batch of items from the stream
* This provides a consumable batch of messages with the ability to delete them upon successful completion of the handler
*/
async processBatch(
handler: (
records: RedisStreamEntry[],
) => Promise,
options: {
startId?: string;
endId?: string;
count?: number;
deleteAfterRead?: boolean;
} = {},
): Promise {
const {
startId = "0",
endId = "+",
count = 1000,
deleteAfterRead = true,
} = options;
try {
// Read entries from the stream
const entriesMap = await redis.xrange(
this.streamKey,
startId,
endId,
count,
);
const entries: RedisStreamEntry[] = Object.entries(entriesMap).map(
([id, data]) => ({
id,
data: data as any,
}),
);
const { processedEntryIds, ...response } = await handler(entries);
// Optionally delete processed entries to prevent memory buildup
if (deleteAfterRead) {
try {
if (processedEntryIds.length > 0) {
// xdel supports deleting multiple IDs at once
await redis.xdel(this.streamKey, processedEntryIds);
}
} catch (error) {
console.warn("Failed to clean up processed stream entries:", error);
// Don't throw - this is not critical
}
}
return response as Response;
} catch (error) {
console.error(
"Failed to read workspace usage updates from stream:",
error,
);
throw error;
}
}
```
Sources: [apps/web/lib/upstash/redis-streams/client.ts:8-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/client.ts#L8-L76)
The client also provides a `getStreamInfo` method to inspect the current state of a stream by querying its length, first entry ID via `redis.xrange`, and last entry ID via `redis.xrevrange`. If a stream does not exist or remains empty, the inspection catches the error state and returns zeroed metrics.
```typescript
/**
* Get stream information (length, first/last entry, etc.)
*/
async getStreamInfo(): Promise<{
length: number;
firstEntryId: string | null;
lastEntryId: string | null;
}> {
try {
// Get stream length - check if stream exists first
let length = 0;
let firstEntryId: string | null = null;
let lastEntryId: string | null = null;
try {
// Try to get first entry to check if stream exists
const firstEntry = await redis.xrange(this.streamKey, "-", "+", 1);
if (firstEntry && Object.keys(firstEntry).length > 0) {
firstEntryId = Object.keys(firstEntry)[0];
// If stream exists, get its length and last entry
const entries = await redis.xrange(this.streamKey, "-", "+");
length = Object.keys(entries || {}).length;
if (length > 0) {
// Use "$" to get the last entry instead of "+"
const lastEntry = await redis.xrevrange(
this.streamKey,
"+",
"-",
1,
);
if (lastEntry && Object.keys(lastEntry).length > 0) {
const entryId = Object.keys(lastEntry)[0];
if (entryId !== firstEntryId) {
lastEntryId = entryId;
}
}
}
}
} catch (streamError) {
// Stream might not exist yet, which is fine
console.log("Stream does not exist or is empty:", streamError);
console.log(streamError.message);
console.log(streamError.type);
console.log(JSON.stringify(streamError, null, 2));
}
return {
length,
firstEntryId,
lastEntryId,
};
} catch (error) {
console.error("Failed to get stream info:", error);
throw error;
}
}
```
Sources: [apps/web/lib/upstash/redis-streams/client.ts:78-138](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/client.ts#L78-L138)
> [!NOTE]
> `RedisStream` handles missing streams gracefully during inspection by catching stream errors and returning null identifiers with a zero length, preventing worker crashes when polling uninitialized streams.
Sources: [apps/web/lib/upstash/redis-streams/client.ts:121-127](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/client.ts#L121-L127)
### Event Publishers and Database Fallbacks
Three primary stream publishers handle high-throughput event ingestion for link clicks, workspace click telemetry, and workspace link usage counts. Each publisher attempts an asynchronous `xadd` operation onto its respective Upstash Redis stream key, falling back to direct database execution if the Redis connection fails.
| Stream Key Constant | Module File | Payload Interface / Schema | Database Fallback Action |
| :--- | :--- | :--- | :--- |
| `link:click:events` | `link-click-events.ts` | `LinkClickEvent` | `UPDATE Link SET clicks = clicks + 1...` & optional Project/Program update |
| `workspace:click:events` | `workspace-click-events.ts` | `clickEventSchemaTB` | Log error to Axiom and rethrow |
| `workspace:linksUsage:updates` | `workspace-links-usage.ts` | `WorkspaceLinksUsageEvent` | `UPDATE Project SET linksUsage = linksUsage + ?, totalLinks = totalLinks + ? WHERE id = ?` |
Sources: [apps/web/lib/upstash/redis-streams/link-click-events.ts:6-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/link-click-events.ts#L6-L73), [apps/web/lib/upstash/redis-streams/workspace-click-events.ts:7-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-click-events.ts#L7-L43), [apps/web/lib/upstash/redis-streams/workspace-links-usage.ts:6-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-links-usage.ts#L6-L40)
The `publishLinkClickEvent` function constructs payloads containing `linkId`, `timestamp`, and optional `workspaceId`, `programId`, and `partnerId`. If publishing fails, it executes `Promise.allSettled` to increment link click counters and workspace usage directly in PlanetScale while flushing error logs.
```typescript
export const publishLinkClickEvent = async ({
linkId,
timestamp,
workspaceId,
programId,
partnerId,
}: LinkClickEvent) => {
const payload = {
linkId,
timestamp,
...(workspaceId && { workspaceId }),
...(programId && partnerId && { programId, partnerId }),
};
try {
return await redis.xadd(STREAM_KEY, "*", payload);
} catch (error) {
logger.error("stream.publish_failed", {
service: "upstash",
streamKey: STREAM_KEY,
error: toErrorFields(error),
correlation: {
linkId,
workspaceId,
programId,
partnerId,
},
});
return await Promise.allSettled([
conn.execute(
"UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
[linkId],
),
workspaceId
? conn.execute(
"UPDATE Project p SET p.usage = p.usage + 1, p.totalClicks = p.totalClicks + 1 WHERE id = ?",
[workspaceId],
)
: null,
programId && partnerId
? conn.execute(
"UPDATE ProgramEnrollment SET totalClicks = totalClicks + 1 WHERE programId = ? AND partnerId = ?",
[programId, partnerId],
)
: null,
logger.flush(),
]);
}
```
Sources: [apps/web/lib/upstash/redis-streams/link-click-events.ts:22-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/link-click-events.ts#L22-L73)
> [!WARNING]
> `publishWorkspaceClickEvent` validates incoming events against the `clickEventSchemaTB` Zod schema and checks `clickWebhookWorkspaces` membership before adding to the stream; events for workspaces without active `link.clicked` webhooks are dropped entirely.
Sources: [apps/web/lib/upstash/redis-streams/workspace-click-events.ts:12-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/upstash/redis-streams/workspace-click-events.ts#L12-L26)
## Link Click Event Processing
### Link Click Event Processing and Webhook Dispatches
Consuming click event streams involves cron-triggered batch workers that drain Redis streams, aggregate statistics into PlanetScale, and dispatch workspace webhook notifications via QStash. Two independent cron routines handle these operations: `update-click-stats` processes high-throughput click telemetry to increment link and workspace counters, while `send-link-clicked-webhooks` scans workspace click streams to trigger asynchronous delivery.
| Cron Route Path | Redis Stream Key | Lock Key | Lock TTL (s) | Batch Size |
| :--- | :--- | :--- | :--- | :--- |
| `/api/cron/streams/update-click-stats` | `link:click:events` | `lock:update-click-stats` | 600 | 10,000 |
| `/api/cron/streams/send-link-clicked-webhooks` | `workspace:click:events` | `lock:send-link-clicked-webhooks` | 600 | 6,000 |
Sources: [apps/web/app/ee/api/cron/streams/send-link-clicked-webhooks/route.ts:18-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/send-link-clicked-webhooks/route.ts#L18-L27), [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:15-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L15-L20)
> [!CAUTION]
> Cron handlers acquire a distributed Redis lock with `nx: true` and an expiration matching the Vercel execution maximum duration (`600s`). If a run fails to acquire `lock:send-link-clicked-webhooks` or `lock:update-click-stats`, the execution exits immediately to prevent concurrent duplicate updates or double-counted webhook deliveries.
Sources: [apps/web/app/ee/api/cron/streams/send-link-clicked-webhooks/route.ts:32-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/send-link-clicked-webhooks/route.ts#L32-L42), [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:19-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L19-L20)
### Aggregating Link and Partner Statistics
The `update-click-stats` cron job reads up to 10,000 entries per run from the `link:click:events` stream using `linkClickEventStream.processBatch`. The `aggregateClickStats` function groups incoming entries into map structures to batch database writes across three distinct aggregates: link click counters, workspace totals, and program enrollment stats.
```typescript
const aggregateClickStats = (
entries: RedisStreamEntry[],
): {
linkUpdates: LinkAggregate[];
workspaceUpdates: WorkspaceAggregate[];
enrollmentUpdates: EnrollmentAggregate[];
} => {
const links = new Map();
const workspaces = new Map();
const enrollments = new Map();
for (const entry of entries) {
const { linkId, workspaceId, programId, partnerId, timestamp } = entry.data;
if (!linkId) {
continue;
}
const parsedTimestamp = Date.parse(timestamp);
const lastClicked = Number.isFinite(parsedTimestamp)
? parsedTimestamp
: Date.now();
const existingLink = links.get(linkId);
if (existingLink) {
existingLink.clicks += 1;
existingLink.lastClicked = Math.max(
existingLink.lastClicked,
lastClicked,
);
existingLink.entryIds.push(entry.id);
} else {
links.set(linkId, {
linkId,
clicks: 1,
lastClicked,
entryIds: [entry.id],
});
}
if (workspaceId) {
const existingWorkspace = workspaces.get(workspaceId);
if (existingWorkspace) {
existingWorkspace.clicks += 1;
} else {
workspaces.set(workspaceId, {
workspaceId,
clicks: 1,
});
}
}
if (programId && partnerId) {
const key = `${programId}:${partnerId}`;
const existingEnrollment = enrollments.get(key);
if (existingEnrollment) {
existingEnrollment.clicks += 1;
} else {
enrollments.set(key, {
programId,
partnerId,
clicks: 1,
});
}
}
}
return {
linkUpdates: Array.from(links.values()),
workspaceUpdates: Array.from(workspaces.values()),
enrollmentUpdates: Array.from(enrollments.values()),
};
};
```
Sources: [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:40-112](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L40-L112)
Database updates execute within parallel sub-batches of 50 items using `processInSubBatches`. Link click increments execute raw SQL statements against PlanetScale to update row totals and reconcile timestamps with `GREATEST`.
```typescript
const processInSubBatches = async (
items: T[],
handler: (item: T) => Promise<{ success: boolean; error?: unknown }>,
) => {
const errors: unknown[] = [];
let totalProcessed = 0;
for (let i = 0; i < items.length; i += SUB_BATCH_SIZE) {
const batch = items.slice(i, i + SUB_BATCH_SIZE);
const results = await Promise.allSettled(batch.map(handler));
for (const result of results) {
if (result.status === "fulfilled" && result.value.success) {
totalProcessed++;
} else if (result.status === "fulfilled" && result.value.error) {
errors.push(result.value.error);
} else if (result.status === "rejected") {
errors.push(result.reason);
}
}
}
return { totalProcessed, errors };
};
const getStreamEntryAgeMs = (entryId: string | null) => {
if (!entryId) {
return null;
}
const timestampMs = Number(entryId.split("-")[0]);
if (!Number.isFinite(timestampMs)) {
return null;
}
return Date.now() - timestampMs;
};
const processClickStatsStreamBatch = () =>
linkClickEventStream.processBatch(
async (entries) => {
if (!entries || entries.length === 0) {
return {
success: true,
linkUpdates: [],
workspaceUpdates: [],
enrollmentUpdates: [],
processedEntryIds: [],
totalProcessed: 0,
errors: [],
};
}
console.log(`Aggregating ${entries.length} click stats events`);
const { linkUpdates, workspaceUpdates, enrollmentUpdates } =
aggregateClickStats(entries);
if (linkUpdates.length === 0) {
console.log("No click stats updates to process");
return {
success: true,
linkUpdates: [],
workspaceUpdates: [],
enrollmentUpdates: [],
processedEntryIds: entries.map((entry) => entry.id),
totalProcessed: 0,
errors: [],
};
}
console.log(
`Processing ${linkUpdates.length} link, ${workspaceUpdates.length} workspace, ${enrollmentUpdates.length} enrollment click stats updates...`,
);
const processedEntryIds: string[] = [];
const errors: unknown[] = [];
const linkResult = await processInSubBatches(
linkUpdates,
```
Sources: [apps/web/app/ee/api/cron/streams/update-click-stats/route.ts:114-215](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts#L114-L215)
> [!TIP]
> Partner activity statistics in `update-partner-stats` filter out undefined and non-finite numeric values before constructing dynamic `UPDATE ProgramEnrollment` queries, formatting JavaScript Date instances into `yyyy-MM-dd HH:mm:ss` strings.
Sources: [apps/web/app/ee/api/cron/streams/update-partner-stats/route.ts:277-301](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-partner-stats/route.ts#L277-L301)
### Workspace Webhook Dispatch Workflows
The `send-link-clicked-webhooks` worker drains the `workspace:click:events` stream, batching up to 6,000 entries per run. For each event batch, it queries Prisma for matching workspaces, links, and associated webhook configurations filtered by `LINK_CLICK_WEBHOOK_TRIGGER` and non-null `disabledAt` timestamps.
```typescript
const processStreamBatch = (): Promise<{
processed: number;
sent: number;
failed: number;
processedEntryIds: string[];
}> =>
workspaceClickEventStream.processBatch(
async (entries) => {
if (!entries || entries.length === 0) {
return {
processed: 0,
sent: 0,
failed: 0,
processedEntryIds: [],
};
}
const workspaceIds = [
...new Set(entries.map((e) => e.data.workspace_id).filter(Boolean)),
];
const linkIds = [
...new Set(entries.map((e) => e.data.link_id).filter(Boolean)),
];
const [workspaces, links] = await Promise.all([
prisma.project.findMany({
where: {
id: {
in: workspaceIds,
},
},
select: {
id: true,
usage: true,
usageLimit: true,
webhooks: {
where: {
disabledAt: null,
triggers: {
array_contains: [LINK_CLICK_WEBHOOK_TRIGGER],
},
},
select: {
id: true,
url: true,
secret: true,
linkScope: true,
projectId: true,
},
},
},
}),
prisma.link.findMany({
where: {
id: {
in: linkIds,
},
},
include: {
tags: {
select: {
tag: {
select: {
id: true,
name: true,
color: true,
},
},
},
},
},
}),
]);
const webhooks = workspaces.flatMap((w) => w.webhooks);
```
Sources: [apps/web/app/ee/api/cron/streams/send-link-clicked-webhooks/route.ts:67-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/send-link-clicked-webhooks/route.ts#L67-L142)
Webhooks support scoping rules via the `linkScope` property, segregating dispatches between link-specific associations (`linkWebhook`) and folder-level groupings (`folderWebhook`). Redundant entries are cleaned up periodically by `cleanupRedundantLinkWebhookEntries`, which removes orphaned `LinkWebhook` rows linked to non-link-scoped webhooks.
Sources: [apps/web/app/ee/api/cron/sync-redis-resources/cleanup-redundant-link-webhook-entries.ts:7-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/sync-redis-resources/cleanup-redundant-link-webhook-entries.ts#L7-L20)
## Workspace Link Usage Accounting
### Stream Consumer Workflows and Batching
The `update-workspace-links-usage` cron job consumes from the `workspace:links-usage` stream, pulling batches of up to 10,000 entries using `workspaceLinksUsageStream.processBatch`. The `aggregateWorkspaceLinksUsage` helper iterates over the raw stream entries, validating that each entry contains a valid `workspaceId` and a finite, positive `linksCount`. Valid items are grouped into a `Map` keyed by `workspaceId` to accumulate link counts and track associated stream entry IDs for acknowledgment.
```typescript
const aggregateWorkspaceLinksUsage = (
entries: RedisStreamEntry[],
): {
updates: WorkspaceLinksUsageAggregate[];
lastProcessedId: string | null;
} => {
const aggregatedUsage = new Map();
let lastProcessedId: string | null = null;
for (const entry of entries) {
const workspaceId = entry.data.workspaceId;
const linksCount = Number(entry.data.linksCount);
if (!workspaceId || !Number.isFinite(linksCount) || linksCount <= 0) {
continue;
}
lastProcessedId = entry.id;
if (aggregatedUsage.has(workspaceId)) {
const existing = aggregatedUsage.get(workspaceId)!;
existing.linksCount += linksCount;
existing.entryIds.push(entry.id);
continue;
}
aggregatedUsage.set(workspaceId, {
workspaceId,
linksCount,
entryIds: [entry.id],
});
}
return {
updates: Array.from(aggregatedUsage.values()),
lastProcessedId,
};
};
```
Sources: [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts:40-77](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts#L40-L77)
The aggregated updates are split into sub-batches of 50 items and processed concurrently via `Promise.allSettled`. For each workspace in a sub-batch, Prisma updates the `Project` model by atomically incrementing both `linksUsage` and `totalLinks`, returning the updated usage and quota limits.
```typescript
const SUB_BATCH_SIZE = 50;
const batches: WorkspaceLinksUsageAggregate[][] = [];
for (let i = 0; i < updates.length; i += SUB_BATCH_SIZE) {
batches.push(updates.slice(i, i + SUB_BATCH_SIZE));
}
const processedEntryIds: string[] = [];
const errors: { workspaceId: string; error: unknown }[] = [];
const updatedWorkspaces: (WorkspaceProps & {
linksUsage: number;
linksLimit: number;
})[] = [];
let totalProcessed = 0;
for (const batch of batches) {
const batchResults = await Promise.allSettled(
batch.map(async (update) => {
const workspace = await prisma.project.update({
where: {
id: update.workspaceId,
},
data: {
linksUsage: {
increment: update.linksCount,
},
totalLinks: {
increment: update.linksCount,
},
},
select: {
id: true,
name: true,
slug: true,
linksUsage: true,
linksLimit: true,
plan: true,
},
});
processedEntryIds.push(...update.entryIds);
return workspace;
}),
);
```
Sources: [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts:101-144](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts#L101-L144)
> [!WARNING]
> If a workspace update fails within `Promise.allSettled`, the failure is captured in an `errors` array alongside the `workspaceId`, but execution continues for the remainder of the sub-batch. Successfully processed entry IDs are accumulated independently to ensure downstream acknowledgment succeeds for valid writes.
Sources: [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts:146-160](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts#L146-L160)
### Quota Thresholds and Limit Alerts
After updating workspace link counters, the worker calculates the percentage of quota consumed against each workspace's `linksLimit`. The `getLimitEmailType` utility function maps consumption percentages to notification types: percentages below 80% return `null`, values from 80% up to 100% return `firstLinksLimitEmail`, and values reaching or exceeding 100% return `secondLinksLimitEmail`.
| Percentage Range | Mapped Limit Email Type |
| :--- | :--- |
| `< 80%` | `null` (No alert) |
| `80% ≤ percentage < 100%` | `firstLinksLimitEmail` |
| `≥ 100%` | `secondLinksLimitEmail` |
Sources: [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts:28-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts#L28-L38), [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts:162-184](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts#L162-L184)
Workspaces crossing the alert threshold are filtered against previously dispatched notifications stored in the `sentEmail` table. Simultaneously, team member emails and workspace-level Slack webhooks are fetched in parallel to dispatch limit warnings.
```typescript
const workspaceIds = workspacesAboveThreshold.map(
({ workspace }) => workspace.id,
);
let notificationsSent = 0;
if (workspaceIds.length > 0) {
const [sentEmails, users, slackWebhookByWorkspace] = await Promise.all([
prisma.sentEmail.findMany({
where: {
projectId: {
in: workspaceIds,
},
type: {
in: ["firstLinksLimitEmail", "secondLinksLimitEmail"],
},
},
select: {
projectId: true,
type: true,
},
}),
prisma.user.findMany({
where: {
projects: {
some: {
projectId: {
in: workspaceIds,
},
},
},
},
select: {
email: true,
projects: {
where: {
projectId: {
in: workspaceIds,
},
},
select: {
projectId: true,
},
},
},
}),
getSlackWebhooks(workspaceIds),
]);
```
Sources: [apps/web/app/ee/api/cron/streams/update-workspace-links-usage/route.ts:185-234](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts#L185-L234)
## Transactional Job Outbox Pattern
### Job Persistence and Deferred Execution
The outbox pattern ensures guaranteed delivery of background jobs and workflows by persisting failed dispatches to the Prisma `Job` model before retry attempts. When background jobs are created via `persistBackgroundJobs`, `scheduledAt` timestamps are computed from options such as `notBefore` or `delay` offsets, and records are written with unique identifiers generated with the `job_` prefix.
```typescript
export async function persistBackgroundJobs(inputs: DispatchJobInput[]) {
const jobs: PersistableJob[] = inputs.map(({ name, payload, options }) => {
let scheduledAt = new Date();
if (options?.notBefore) {
scheduledAt = new Date(options.notBefore * 1000);
} else if (typeof options?.delay === "number") {
scheduledAt = new Date(Date.now() + options.delay * 1000);
}
const replayOptions = {
...(options?.deduplicationId && {
deduplicationId: options.deduplicationId,
}),
...(options?.retries !== undefined && { retries: options.retries }),
...(options?.queue && { queue: options.queue }),
...(options?.flowControl && { flowControl: options.flowControl }),
...(options?.label && { label: options.label }),
};
return {
id: createId({ prefix: "job_" }),
name,
payload,
options: replayOptions,
scheduledAt,
};
});
await prisma.job.createMany({
data: jobs.map((job) => toJobCreateInput({ job })),
});
return jobs;
}
```
Sources: [apps/web/lib/jobs/outbox.ts:88-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts#L88-L122)
Two primary transports handle job distribution through `transports`: workflow triggers mapped via `isWorkflowName` and standard job dispatches matched via `isDefineJobName`. The `publishPendingJobs` function queries due rows where `scheduledAt` is less than or equal to the current date and `attempts` is strictly less than `MAX_JOB_ATTEMPTS`, ordered by creation date ascending up to `MAX_JOBS_PER_BATCH`.
```typescript
type JobTransport = {
matches: (name: string) => boolean;
send: (jobs: Job[]) => Promise;
};
const transports: JobTransport[] = [
{
matches: isWorkflowName,
send: triggerWorkflows,
},
{
matches: isDefineJobName,
send: sendJobs,
},
];
```
Sources: [apps/web/lib/jobs/outbox.ts:10-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts#L10-L24), [apps/web/lib/jobs/outbox.ts:202-220](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts:202-L220)
> [!NOTE]
> The first failed publish attempt counts as attempt 1 so that the retry budget accurately matches `MAX_JOB_ATTEMPTS`. If a job name does not match any registered transport, it is treated as an unknown kind, generating a failed result with an error message and logging the event.
Sources: [apps/web/lib/jobs/outbox.ts:26-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts:26-43), [apps/web/lib/jobs/outbox.ts:245-261](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts:245-L261)
### Cron Retry Execution and Settle Mechanics
The cron endpoint `GET /api/cron/queue/retry` orchestrates periodic reprocessing of pending outbox items. A distributed Redis lock using `LOCK_KEY` (`lock:queue-retry`) with a TTL of 600 seconds prevents concurrent minute-cron overlapping invocations.
```typescript
const LOCK_KEY = "lock:queue-retry";
const LOCK_TTL_SECONDS = 600;
// GET /api/cron/queue/retry – republish jobs that failed to publish to QStash
// at dispatch time; rows are deleted on successful publish
export const GET = withCron(async () => {
const acquired = await redis.set(LOCK_KEY, "1", {
nx: true,
ex: LOCK_TTL_SECONDS,
});
if (!acquired) {
return logAndRespond(
"[queue-retry] Another run is in progress. Skipping...",
);
}
```
Sources: [apps/web/app/ee/api/cron/queue/retry/route.ts:11-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/queue/retry/route.ts#L11-L26)
Once the lock is acquired, `publishPendingJobs` runs and delegates results to `settlePublishResults`. Successfully published job IDs are deleted from the database via `prisma.job.deleteMany`, while failed dispatches increment their attempt counters and update `lastError` fields.
```typescript
try {
const { attempted, published, failed } = await publishPendingJobs();
if (attempted === 0) {
return logAndRespond("No background jobs to retry.");
}
if (failed === 0) {
return logAndRespond(
`Republished ${published} background jobs to QStash.`,
);
}
return logAndRespond(
`Republished ${published} background jobs to QStash; failed to republish ${failed}.`,
);
} finally {
await redis.del(LOCK_KEY);
}
```
Sources: [apps/web/app/ee/api/cron/queue/retry/route.ts:28-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/queue/retry/route.ts#L28-L46), [apps/web/lib/jobs/outbox.ts:125-180](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts:125-L180)
| Result Status | Action Taken | Prisma Operation |
| :--- | :--- | :--- |
| `published` | Delete successfully dispatched jobs | `prisma.job.deleteMany` |
| `failed` | Increment attempt counter and record `lastError` | `prisma.job.updateMany` |
Sources: [apps/web/lib/jobs/outbox.ts:125-180](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts:125-180)
> [!WARNING]
> When jobs exceed or equal `MAX_JOB_ATTEMPTS` during settlement failures, an error event (`jobs.retry_exhausted`) is logged to Axiom with the exhausted job identifiers and names, signaling permanent delivery abandonment.
Sources: [apps/web/lib/jobs/outbox.ts:182-194](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/outbox.ts:182-194)
## Asynchronous Job Handlers Execution
### Asynchronous Job Execution Router
The POST endpoint `POST /api/jobs/process/[jobName]` handles incoming background job execution requests originating from QStash triggers, with a maximum execution duration configured to 600 seconds. Every incoming request must pass cryptographic verification via `verifyQstashSignature` using the raw request body and request headers before any parsing or processing occurs. If signature verification fails, an error response is returned immediately.
```typescript
export const maxDuration = 600;
// POST /api/jobs/process/[jobName] – shared executor for all background jobs
export const POST = withAxiomBodyLog(
async (
req: Request,
{ params }: { params: Promise<{ jobName: string }> },
) => {
const { jobName: urlJobName } = await params;
const clonedReq = req.clone();
const rawBody = await clonedReq.text();
try {
await verifyQstashSignature({ req, rawBody });
} catch (error) {
return handleAndReturnErrorResponse(error);
}
```
Sources: [apps/web/app/api/jobs/process/jobName/route.ts:8-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/jobs/process/%5BjobName%5D/route.ts#L8-L25)
After successful verification, the request body is parsed as JSON and validated against the `jobEnvelopeSchema` envelope structure. If the envelope is malformed or invalid, an error is logged to Axiom and the endpoint returns a non-retryable response status to prevent QStash from retrying permanently corrupted payloads. The URL parameter `urlJobName` is also validated against the job name contained within the envelope data; any mismatch triggers an immediate non-retryable response.
```typescript
const envelope = jobEnvelopeSchema.safeParse(parsedBody);
// Permanently invalid — returning 2xx stops QStash retries
if (!envelope.success) {
logger.error("jobs.invalid_envelope", {
error: envelope.error.message,
});
await logger.flush();
return new Response("Invalid job envelope (non-retryable).");
}
const { name: jobName } = envelope.data;
if (urlJobName !== jobName) {
logger.error("jobs.job_name_mismatch", {
urlJobName,
envelopeJobName: jobName,
});
await logger.flush();
return new Response(
`Job name mismatch: URL "${urlJobName}" does not match envelope "${jobName}" (non-retryable).`,
);
}
```
Sources: [apps/web/app/api/jobs/process/jobName/route.ts:34-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/jobs/process/%5BjobName%5D/route.ts#L34-L58)
Once the job name and envelope are verified, the executor retrieves the registered job definition using `loadJob(jobName)`. If no matching job definition is found in the registry, an unknown job error is logged and a non-retryable response is returned.
```typescript
console.log(`[jobs:${jobName}] Executing job...`, envelope.data);
// Get the job definition
const job = await loadJob(jobName);
if (!job) {
logger.error("jobs.unknown_job", {
jobName,
});
await logger.flush();
return new Response(`Unknown job "${jobName}" (non-retryable).`);
}
```
Sources: [apps/web/app/api/jobs/process/jobName/route.ts:60-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/jobs/process/%5BjobName%5D/route.ts#L60-L72)
> [!WARNING]
> If a job's execution throws a Zod validation error (`z.ZodError`), the error is logged as an invalid payload and treated as permanent, returning a 2xx response so that QStash halts retries. Transient execution failures throw a 500 status code, signaling QStash to re-attempt delivery according to the job's retry policy.
Sources: [apps/web/app/api/jobs/process/jobName/route.ts:74-102](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/jobs/process/%5BjobName%5D/route.ts#L74-L102)
### Domain-Specific Job Handlers
Specific background job processors handle complex partner, group, and integration workflows dispatched through the central router. The `partnerSearchSyncJob` handles synchronization tasks with a parallelism limit of 20 concurrent executions using a flow control key (`partner-search-sync`), supporting a discriminated union input schema for either individual `enrollments` or bulk `partners` sync batches.
```typescript
const SYNC_PARALLELISM = 20;
/**
* Two shapes, because the two kinds of change have different blast radii.
*
* `enrollments` carries IDs the caller already has, and is the only shape that
* can express a deletion, since the handler finds out by failing to read one
* back. `partners` is for changes that fan out past one enrollment, where the
* caller knows the partner but not how many programs it reaches.
*/
const inputSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("enrollments"),
enrollmentIds: z
.array(z.string())
.min(1)
.max(PARTNER_SEARCH_SYNC_BATCH_SIZE),
}),
z.object({
type: z.literal("partners"),
partnerIds: z.array(z.string()).min(1).max(PARTNER_SEARCH_SYNC_BATCH_SIZE),
programId: z.string().optional(),
after: z.string().optional(),
}),
]);
export const partnerSearchSyncJob = defineJob({
name: "partner-search-sync-job",
schema: inputSchema,
defaults: {
retries: 3,
flowControl: {
key: "partner-search-sync",
parallelism: SYNC_PARALLELISM,
},
},
```
Sources: [apps/web/lib/jobs/handlers/partner-search-sync-job.ts:16-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/partner-search-sync-job.ts#L16-L51)
If no search provider is configured via `getPartnerSearchProvider()`, the search sync job exits early to prevent accumulating an unprocessable backlog. When processing `partners` input types, if the number of upserted items reaches the batch size limit `PARTNER_SEARCH_SYNC_BATCH_SIZE` alongside a valid `lastEnrollmentId`, the handler recursively dispatches another job instance with a 1-second delay.
```typescript
async handle(input) {
const searchProvider = getPartnerSearchProvider();
// An environment without the key should not accumulate a backlog of jobs
// that can never succeed.
if (!searchProvider) {
console.log(
"[partnerSearchSyncJob] No search provider configured. Skipping...",
);
return;
}
if (input.type === "enrollments") {
const { upserted, deleted } = await syncPartnerSearchDocuments({
enrollmentIds: input.enrollmentIds,
searchProvider,
});
console.log(
`[partnerSearchSyncJob] Synced ${upserted} and removed ${deleted} enrollment documents.`,
);
return;
}
const { upserted, lastEnrollmentId } = await syncPartnerEnrollments({
partnerIds: input.partnerIds,
programId: input.programId,
after: input.after,
take: PARTNER_SEARCH_SYNC_BATCH_SIZE,
searchProvider,
});
if (upserted === 0) {
return;
}
console.log(
`[partnerSearchSyncJob] Synced ${upserted} enrollment documents for ${input.partnerIds.length} partner(s).`,
);
if (upserted === PARTNER_SEARCH_SYNC_BATCH_SIZE && lastEnrollmentId) {
await partnerSearchSyncJob.dispatch(
{
...input,
after: lastEnrollmentId,
},
{
delay: 1,
},
);
}
},
```
Sources: [apps/web/lib/jobs/handlers/partner-search-sync-job.ts:52-104](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/partner-search-sync-job.ts#L52-L104)
```mermaid
flowchart TD
Start["Job Execution Triggered"] --> CheckProvider{"Search Provider Configured?"}
CheckProvider -- No --> ExitEarly["Log and Return Early"]
CheckProvider -- Yes --> CheckType{"Input Type?"}
CheckType -- "enrollments" --> SyncEnrollments["Sync Search Documents (upserted/deleted)"]
CheckType -- "partners" --> SyncPartners["Sync Partner Enrollments"]
SyncPartners --> CheckUpsert{"Upserted == Batch Size & lastEnrollmentId?"}
CheckUpsert -- Yes --> DispatchNext["Dispatch Follow-up Job (delay: 1s)"]
CheckUpsert -- No --> End["Complete"]
SyncEnrollments --> End
```
Sources: [apps/web/lib/jobs/handlers/partner-search-sync-job.ts:52-104](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/partner-search-sync-job.ts#L52-L104)
Order and partner group modification workflows manage transactional updates and external integrations. The `processShopifyOrderJob` validates order schemas and workspace settings, capturing webhook logs with status codes 200 on success or 400 on error. Concurrently, `processPartnerGroupChangeJob` validates group existence, clears stale link rewards and Redis link caches, queues search index updates, remaps default links, records link analytics, and triggers partner notifications.
```typescript
export const processShopifyOrderJob = defineJob({
name: "process-shopify-order-job",
schema: inputSchema,
async handle({ workspaceId, clickId, order }) {
const startTime = Date.now();
const workspace = await prisma.project.findUniqueOrThrow({
where: {
id: workspaceId,
},
select: {
id: true,
defaultProgramId: true,
webhookEnabled: true,
},
});
const requestLog = {
workspaceId: workspace.id,
method: "POST",
path: "/shopify/integration/webhook" as const,
requestBody: order,
userAgent: "Shopify Order Job",
};
try {
const result = await processShopifyOrder({
order,
workspace,
clickId,
});
await logger.flush();
await captureWebhookLog({
...requestLog,
statusCode: 200,
duration: Date.now() - startTime,
responseBody: result,
});
} catch (error) {
await captureWebhookLog({
...requestLog,
statusCode: 400,
duration: Date.now() - startTime,
responseBody: serializeError(error),
});
await logger.flush();
}
},
```
Sources: [apps/web/lib/jobs/handlers/process-shopify-order-job.ts:17-67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/process-shopify-order-job.ts#L17-L67), [apps/web/lib/jobs/handlers/process-partner-group-change-job.ts:28-145](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/jobs/handlers/process-partner-group-change-job.ts:28-L145)
## Webhook Retries and Failure Handling
### Consecutive Failure Tracking and Circuit Breaking
When a webhook delivery fails, `handleWebhookFailure` increments the `consecutiveFailures` counter and updates `lastFailedAt` on the targeted webhook record in the database. If the webhook has already been marked with a `disabledAt` timestamp, the function returns immediately without further processing.
```typescript
export const handleWebhookFailure = async (webhookId: string) => {
const webhook = await prisma.webhook.update({
where: {
id: webhookId,
},
data: {
consecutiveFailures: { increment: 1 },
lastFailedAt: new Date(),
},
select: {
id: true,
url: true,
secret: true,
triggers: true,
disabledAt: true,
consecutiveFailures: true,
lastFailedAt: true,
projectId: true,
},
});
if (webhook.disabledAt) {
return;
}
```
Sources: [apps/web/lib/webhook/failure.ts:12-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/failure.ts#L12-L35)
> [!NOTE]
> Successful deliveries reset the consecutive failure count and clear `lastFailedAt` back to `null` by calling `resetWebhookFailureCount`.
Sources: [apps/web/lib/webhook/failure.ts:65-73](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/failure.ts#L65-L73)
### Failure Notifications and Workspace Deactivation
As failures accumulate, the system dispatches notification emails to workspace owners and eventually deactivates the webhook once it breaches the disable threshold. If `consecutiveFailures` matches any value defined in `WEBHOOK_FAILURE_NOTIFY_THRESHOLDS`, `notifyWebhookFailure` queries the project's owner and sends a `WebhookFailed` email containing the webhook ID, URL, consecutive failure count, and disable threshold.
```typescript
if (
WEBHOOK_FAILURE_NOTIFY_THRESHOLDS.includes(
webhook.consecutiveFailures as any,
)
) {
await notifyWebhookFailure(webhook);
return;
}
```
Sources: [apps/web/lib/webhook/failure.ts:37-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/failure.ts#L37-L44)
When `consecutiveFailures` reaches or exceeds `WEBHOOK_FAILURE_DISABLE_THRESHOLD`, the webhook is permanently disabled by setting its `disabledAt` field to the current timestamp. Concurrently, `Promise.allSettled` triggers `notifyWebhookDisabled` to email workspace owners via the `WebhookDisabled` template and invokes `syncWorkspaceWebhookStatus` to update the project's webhook-enabled status.
```typescript
if (webhook.consecutiveFailures >= WEBHOOK_FAILURE_DISABLE_THRESHOLD) {
// Disable the webhook
const updatedWebhook = await prisma.webhook.update({
where: { id: webhookId },
data: {
disabledAt: new Date(),
},
});
await Promise.allSettled([
// Notify the user
notifyWebhookDisabled(updatedWebhook),
// Update the project webhookEnabled flag
syncWorkspaceWebhookStatus(webhook.projectId),
]);
}
};
```
Sources: [apps/web/lib/webhook/failure.ts:46-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/failure.ts#L46-L63)
## Related
- [Scheduled Cron Tasks](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/scheduled-cron-tasks)
- [Webhooks & Postbacks](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/webhooks-postbacks)
---
## Technical docs: DELETE Remove program from marketplace
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/deleteadminprogram
## Parameters
## Responses
## Try It
---
## Technical docs: Email Notification
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/email-notification
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/email/src/send-via-resend.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/send-via-resend.ts)
- [packages/email/src/templates/campaign-email.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/campaign-email.tsx)
- [apps/web/lib/email/email-templates-map.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/email/email-templates-map.ts)
- [apps/web/app/ee/api/campaigns/campaignId/preview/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/campaigns/%5BcampaignId%5D/preview/route.ts)
- [packages/email/src/templates/lead-status-updated.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/lead-status-updated.tsx)
- [packages/email/src/templates/new-submitted-lead-comments-from-program.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-submitted-lead-comments-from-program.tsx)
- [apps/web/app/ee/api/cron/send-batch-email/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/send-batch-email/route.ts)
- [packages/email/src/templates/domain-deleted.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-deleted.tsx)
- [packages/email/src/templates/broadcasts/dub-product-update-summer26.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/broadcasts/dub-product-update-summer26.tsx)
- [apps/web/lib/partners/create-stripe-transfer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts)
- [packages/email/src/resend/constants.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/resend/constants.ts)
- [packages/email/src/templates/broadcasts/dub-startup-program-announcement.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/broadcasts/dub-startup-program-announcement.tsx)
- [packages/email/src/templates/webhook-failed.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-failed.tsx)
- [packages/email/src/templates/webhook-disabled.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-disabled.tsx)
- [packages/email/src/templates/verify-email.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/verify-email.tsx)
- [packages/email/src/templates/domain-renewal-failed.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-renewal-failed.tsx)
- [packages/email/src/templates/email-domain-status-changed.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/email-domain-status-changed.tsx)
- [packages/email/src/templates/api-key-created.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/api-key-created.tsx)
- [packages/email/src/templates/new-message-from-program.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-message-from-program.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/email/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/email/page-client.tsx)
- [packages/email/src/templates/broadcasts/dub-wrapped.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/broadcasts/dub-wrapped.tsx)
- [packages/email/src/templates/bounty-new-submission.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/bounty-new-submission.tsx)
- [packages/email/src/templates/dub-partner-rewind.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/dub-partner-rewind.tsx)
- [packages/email/src/templates/new-message-from-partner.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-message-from-partner.tsx)
- [packages/email/src/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/index.ts)
- [packages/email/src/templates/domain-expired.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-expired.tsx)
- [packages/email/src/templates/new-submitted-lead-comments-from-partner.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-submitted-lead-comments-from-partner.tsx)
- [packages/email/src/templates/domain-transferred.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-transferred.tsx)
- [packages/email/src/templates/domain-renewal-reminder.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-renewal-reminder.tsx)
- [packages/email/src/templates/domain-renewed.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-renewed.tsx)
## Overview
Email notification infrastructure in Dub handles programmatic dispatch across security, lifecycle, marketing, and partner communication channels using React Email templates styled with Tailwind CSS. The system provides robust dispatch capabilities via Resend with automatic fallback to Nodemailer when Resend is unconfigured, while rewriting reserved test domains and managing sender variants such as primary, notifications, and marketing.
Sources: [packages/email/src/send-via-resend.ts:8-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/send-via-resend.ts#L8-L33), [packages/email/src/resend/constants.ts:1-4](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/resend/constants.ts#L1-L4), [packages/email/src/index.ts:6-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/index.ts#L6-L29)
## Email dispatch architecture
### Transport selection and public entrypoints
Public email dispatch is exposed through `sendEmail` and `sendBatchEmail` in `packages/email/src/index.ts`. These functions evaluate runtime configuration to select between the Resend SDK and an SMTP transport via Nodemailer. If the `resend` client is initialized, dispatch is delegated to `sendEmailViaResend` or `sendBatchEmailViaResend`. When Resend is unconfigured, the system checks whether `SMTP_HOST` and `SMTP_PORT` are present in the environment variables. If SMTP is configured, single messages dispatch through `sendViaNodeMailer`, whereas batch operations process concurrently via `Promise.all` mapping over the input array and generating random UUIDs for response simulation. If neither transport is configured, dispatch aborts and logs an informational message.
Sources: [packages/email/src/index.ts:6-71](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/index.ts#L6-L71)
### Sender variants and recipient filtering
Email options map logical variants to designated sender addresses. The system recognizes three variants (`primary`, `notifications`, and `marketing`), mapping each to its default sender string. When processing outgoing payloads, the sender defaults to the mapped variant address if an explicit `from` address is omitted.
| Variant | Default Sender Address |
| :--- | :--- |
| `primary` | `Dub.co ` |
| `notifications` | `Dub.co ` |
| `marketing` | `Steven from Dub.co ` |
Sources: [packages/email/src/resend/constants.ts:1-4](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/resend/constants.ts#L1-L4), [packages/email/src/send-via-resend.ts:40-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/send-via-resend.ts#L40-L41), [packages/email/src/send-via-resend.ts:60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/send-via-resend.ts#L60)
Recipient addresses undergo validation against reserved test domains to prevent `422` validation errors from Resend. The blocked domains include `example.com`, `example.net`, `example.org`, and `test.com`. If a recipient domain matches any blocked entry or its subdomain, `rewriteBlockedRecipient` rewrites the address to `delivered+username@resend.dev`. Furthermore, when `VERCEL_ENV` is set to `preview`, recipient addresses are forcibly overridden to `delivered@resend.dev`, and git branch references are appended to email subjects in the format `[gitBranch]`.
> [!WARNING]
> In Vercel preview environments, recipient rewriting forces all outbound messages to `delivered@resend.dev` regardless of the input parameter, ensuring test runs do not leak external mail.
Sources: [packages/email/src/send-via-resend.ts:8-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/send-via-resend.ts#L8-L33), [packages/email/src/send-via-resend.ts:53-61](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/send-via-resend.ts#L53-L61)
## Transactional notification templates
### Authentication and workspace lifecycle components
Transactional email templates are built using `@react-email/components` and styled with Tailwind CSS, wrapped inside an `Html`, `Head`, `Preview`, and `Tailwind` structure alongside a shared `Footer` component. The `VerifyEmail` template manages user authentication by rendering a 6-digit verification code (`code`) inside a monospace, letter-spaced container (`tracking-[0.25em] font-mono text-2xl`). The template explicitly states that the code expires in 10 minutes.
Sources: [packages/email/src/templates/verify-email.tsx:16-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/verify-email.tsx#L16-L52)
Workspace administrative actions generate security alerts. The `APIKeyCreated` template renders confirmation notices when a new API key is provisioned within a workspace. It displays the workspace name, token name, token type, and permissions, accompanied by a timestamp formatted via `formatDate(new Date().toString())`. It provides links directing users to manage or delete unauthorized keys at `https://app.dub.co/${workspace.slug}/settings/tokens`.
Sources: [packages/email/src/templates/api-key-created.tsx:17-87](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/api-key-created.tsx#L17-L87)
```tsx
export default function VerifyEmail({
email = "panic@thedis.co",
code = "123456",
}: {
email: string;
code: string;
}) {
```
Sources: [packages/email/src/templates/verify-email.tsx:16-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/verify-email.tsx#L16-L22)
### Webhook failure and deactivation templates
Webhook health monitoring utilizes two distinct email templates (`WebhookFailed` and `WebhookDisabled`) to notify workspace administrators of delivery disruptions. Both templates accept a `workspace` object containing `name` and `slug`, and a `webhook` object containing `id`, `url`, and a `disableThreshold` integer. `WebhookFailed` additionally accepts `consecutiveFailures`.
Sources: [packages/email/src/templates/webhook-failed.tsx:17-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-failed.tsx#L17-L41), [packages/email/src/templates/webhook-disabled.tsx:17-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-disabled.tsx#L17-L39)
| Template File | Component Name | Key Props | Action URL |
| :--- | :--- | :--- | :--- |
| `verify-email.tsx` | `VerifyEmail` | `email`, `code` | N/A (Verification page) |
| `api-key-created.tsx` | `APIKeyCreated` | `email`, `workspace`, `token` | `https://app.dub.co/{slug}/settings/tokens` |
| `webhook-failed.tsx` | `WebhookFailed` | `email`, `workspace`, `webhook` | `https://app.dub.co/{slug}/settings/webhooks/{id}/edit` |
| `webhook-disabled.tsx` | `WebhookDisabled` | `email`, `workspace`, `webhook` | `https://app.dub.co/{slug}/settings/webhooks/{id}/edit` |
Sources: [packages/email/src/templates/verify-email.tsx:16-22](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/verify-email.tsx#L16-L22), [packages/email/src/templates/api-key-created.tsx:17-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/api-key-created.tsx#L17-L39), [packages/email/src/templates/webhook-failed.tsx:17-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-failed.tsx#L17-L41), [packages/email/src/templates/webhook-disabled.tsx:17-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-disabled.tsx#L17-L39)
> [!NOTE]
> The `WebhookFailed` template warns that the target endpoint has failed `consecutiveFailures` times and will automatically deactivate once it reaches the `disableThreshold`, whereas `WebhookDisabled` confirms that deactivation has already occurred after hitting that exact threshold sequentially.
Sources: [packages/email/src/templates/webhook-failed.tsx:55-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-failed.tsx#L55-L59), [packages/email/src/templates/webhook-disabled.tsx:53-57](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/webhook-disabled.tsx#L53-L57)
## Domain lifecycle notifications
### Domain renewal and expiration workflows
Domain lifecycle notification templates handle custom link domains, domain renewals, expirations, deletions, transfers, and email sending domain verifications. The `EmailDomainStatusChanged` template monitors verification states using an `EmailDomainStatus` union type consisting of `pending`, `verified`, `failed`, `temporary_failure`, `not_started`, `partially_verified`, and `partially_failed`.
Sources: [packages/email/src/templates/email-domain-status-changed.tsx:17-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/email-domain-status-changed.tsx#L17-L24)
| Status Category | Matching `EmailDomainStatus` Values | Rendered Heading & Action |
| :--- | :--- | :--- |
| Verified | `verified` | "Your email domain has been successfully verified" |
| Failed | `failed`, `temporary_failure`, `partially_failed` | "Your email domain verification has failed" |
| Pending | `pending`, `not_started`, `partially_verified` | "Your email domain status has changed" (includes pending notice) |
Sources: [packages/email/src/templates/email-domain-status-changed.tsx:39-53](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/email-domain-status-changed.tsx#L39-L53)
> [!NOTE]
> The `EmailDomainStatusChanged` template checks whether `newStatus` evaluates to `verified`, `failed` (covering permanent, temporary, or partial failures), or `pending` (covering pending, not started, or partial verification states) to customize alert previews and guidance text.
Sources: [packages/email/src/templates/email-domain-status-changed.tsx:39-47](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/email-domain-status-changed.tsx#L39-L47)
Automated domain renewals and expirations use dedicated transactional email templates to communicate billing outcomes, upcoming charges, and deletion policies. The `DomainRenewalReminder` component notifies users of an upcoming renewal fee (`renewalFee`), expiry date (`expiresAt`), reminder window (`reminderWindow`), and scheduled charge timing (`chargeAt` and `chargeAtInText`).
Sources: [packages/email/src/templates/domain-renewal-reminder.tsx:17-43](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-renewal-reminder.tsx#L17-L43)
When payment processing fails, `DomainRenewalFailed` generates an itemized table showing each failing domain slug and its expiration date, notifying recipients that automated attempts will retry in 3 days. Similarly, `DomainExpired` lists expired domains and directs administrators to the domain settings page. If a custom domain remains invalid for 30 days, `DomainDeleted` informs the workspace owner that the domain has been permanently removed from Dub. Finally, `DomainTransferred` notifies stakeholders when a domain and its associated links are moved to a new workspace.
Sources: [packages/email/src/templates/domain-renewal-failed.tsx:20-67](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-renewal-failed.tsx#L20-L67), [packages/email/src/templates/domain-expired.tsx:19-70](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-expired.tsx#L19-L70), [packages/email/src/templates/domain-deleted.tsx:17-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-deleted.tsx#L17-L50), [packages/email/src/templates/domain-transferred.tsx:18-54](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/domain-transferred.tsx#L18-L54)
## Partner and marketplace communications
### Partner payouts and program messaging triggers
Asynchronous routines in the partner system manage financial disbursements and communication threads between programs, partners, and workspace administrators. When a partner transfer is processed via Stripe, `createStripeTransfer.ts` uses `waitUntil` and `Promise.allSettled` to execute commission status tracking and queue referral jobs via `enqueueBatchJobs` pointing to `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/queue`.
Sources: [apps/web/lib/partners/create-stripe-transfer.ts:303-321](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts#L303-L321)
> [!NOTE]
> Payout email subjects dynamically branch on `forceWithdrawal`. If forced, the subject states "A withdrawal of [amount] has been initiated from your Dub account" using `PartnerPayoutForceWithdrawal` with method `"connect"`; otherwise, it outputs "You've received a [amount] payout from [program name]" via `PartnerPayoutProcessed`.
Sources: [apps/web/lib/partners/create-stripe-transfer.ts:328-343](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/partners/create-stripe-transfer.ts#L328-L343)
Program and partner messaging templates render interactive communication streams using React Email components. `NewMessageFromProgram` and `NewMessageFromPartner` enforce a constant `MAX_DISPLAYED_MESSAGES` limit of `3` for rendered message rows, displaying fallback avatars from `OG_AVATAR_URL` when user images are null.
Sources: [packages/email/src/templates/new-message-from-program.tsx:24-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-message-from-program.tsx#L24-L24), [packages/email/src/templates/new-message-from-partner.tsx:24-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-message-from-partner.tsx#L24-L24)
| Template Name | Primary Recipient | Key Props & Identifiers | Call-to-Action Target |
| :--- | :--- | :--- | :--- |
| `NewMessageFromProgram` | Partner | `program`, `messages[]`, `email` | `https://partners.dub.co/messages/${program.slug}` |
| `NewMessageFromPartner` | Workspace Admin | `workspaceSlug`, `partner`, `messages[]`, `email` | `https://app.dub.co/${workspaceSlug}/program/messages/${partner.id}` |
| `NewBountySubmission` | Workspace Admin | `workspace`, `bounty`, `partner`, `submission`, `email` | `https://app.dub.co/${workspace.slug}/program/bounties/${bounty.id}?submissionId=${submission.id}` |
| `LeadStatusUpdated` | Partner | `partner`, `program`, `lead`, `notes` | Profile notification settings URL |
Sources: [packages/email/src/templates/new-message-from-program.tsx:76-92](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-message-from-program.tsx#L76-L92), [packages/email/src/templates/new-message-from-partner.tsx:56-69](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-message-from-partner.tsx#L56-L69), [packages/email/src/templates/bounty-new-submission.tsx:36-54](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/bounty-new-submission.tsx#L36-L54), [packages/email/src/templates/lead-status-updated.tsx:33-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/lead-status-updated.tsx#L33-L44)
### Submitted lead comments and status updates
Lead submission workflows support bi-directional commentary between programs and partners via dedicated card wrappers and routing templates. `NewSubmittedLeadCommentsFromProgram` links recipients to `https://partners.dub.co/programs/${program.slug}/leads?leadId=${lead.id}`, while `NewSubmittedLeadCommentsFromPartner` routes administrators to `https://app.dub.co/${workspace.slug}/program/leads?leadId=${lead.id}`.
Sources: [packages/email/src/templates/new-submitted-lead-comments-from-program.tsx:62-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-submitted-lead-comments-from-program.tsx#L62-L62), [packages/email/src/templates/new-submitted-lead-comments-from-partner.tsx:59-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/new-submitted-lead-comments-from-partner.tsx#L59-L59)
> [!WARNING]
> When rendering lead status updates through `LeadStatusUpdated`, if optional `notes` are supplied, the template injects an additional text block displaying custom remarks from the program alongside the updated lead status (`lead.status`) and company metadata (`lead.company`).
Sources: [packages/email/src/templates/lead-status-updated.tsx:67-76](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/lead-status-updated.tsx#L67-L76)
## Campaign authoring and broadcasts
Dynamic broadcast templates and campaign preview routes handle audience email generation. The `CampaignEmail` component renders structured campaign bodies with customizable programs and types (`transactional` or `marketing`), using `CAMPAIGN_EMAIL_TEXT_COLOR` set to `#000000` for inline text styling. When the campaign type is `marketing`, an opt-out footer is appended with a link pointing to `https://partners.dub.co/profile/notifications`. For `transactional` campaigns where `program.messagingEnabledAt` is active, a "Reply in Dub" button is rendered linking to `https://partners.dub.co/messages/${program.slug}`.
Sources: [packages/email/src/templates/campaign-email.tsx:18-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/campaign-email.tsx#L18-L20), [packages/email/src/templates/campaign-email.tsx:92-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/campaign-email.tsx#L92-L118)
Preview generation is handled by the `POST /api/campaigns/[campaignId]/preview` route, protected by workspace authentication (`withWorkspace`) with required plans `["advanced", "enterprise"]` and roles `["owner", "member"]`. Request payloads are validated against `sendPreviewEmailSchema`, which enforces a maximum of 10 email addresses via `z.email()`.
Sources: [apps/web/app/ee/api/campaigns/campaignId/preview/route.ts:30-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/campaigns/%5BcampaignId%5D/preview/route.ts#L30-L34), [apps/web/app/ee/api/campaigns/campaignId/preview/route.ts:37-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/campaigns/%5BcampaignId%5D/preview/route.ts#L37-L42), [apps/web/app/ee/api/campaigns/campaignId/preview/route.ts:129-132](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/campaigns/%5BcampaignId%5D/preview/route.ts#L129-L132)
> [!CAUTION]
> When a custom `from` address is supplied in the preview payload, the route validates it using `parseCampaignFromAddress` and ensures the sending domain matches one of the program's verified `emailDomains`. If the domain is unverified, a `DubApiError` with code `bad_request` is thrown.
Sources: [apps/web/app/ee/api/campaigns/campaignId/preview/route.ts:65-81](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/campaigns/%5BcampaignId%5D/preview/route.ts#L65-L81)
Broadcast templates like `DubWrapped`, `DubProductUpdateSummer26`, `DubStartupProgramAnnouncement`, and `DubPartnerRewind` offer specialized annual reviews and announcements. `DubWrapped` displays granular statistics (`stats`), top links with custom click intervals (`topLinks`), and country distributions (`topCountries`) utilizing `nFormatter` and flag images from `wsrv.nl` with `hatscripts.github.io/circle-flags`.
Sources: [packages/email/src/templates/broadcasts/dub-wrapped.tsx:28-75](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/broadcasts/dub-wrapped.tsx#L28-L75), [packages/email/src/templates/broadcasts/dub-wrapped.tsx:342-346](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/email/src/templates/broadcasts/dub-wrapped.tsx#L342-L346)
## Batch processing and domain management
### Batch dispatch routes and template mapping
Asynchronous batch email delivery is handled by the `POST /api/cron/send-batch-email` route, which requires QStash signature verification via `verifyQstashSignature` on the raw request body. Incoming payloads are validated using a Zod schema (`batchEmailPayloadSchema`) that accepts an array of email objects. Each object specifies a template name, template properties, recipient address (`to`), optional sender (`from`), subject, bcc, reply-to, variant (`primary`, `notifications`, or `marketing`), headers, tags, and scheduled timestamp.
Sources: [apps/web/app/ee/api/cron/send-batch-email/route.ts:13-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/send-batch-email/route.ts#L13-L46)
The system maps template string identifiers to underlying React-email components using `EMAIL_TEMPLATES_MAP`. The registered templates span partner rewards, payouts, risk summaries, system notifications, and broadcasts.
| Template Key | Source Component / Import |
| :--- | :--- |
| `BountyApproved` | `BountyApproved` |
| `ConnectPayoutReminder` | `ConnectPayoutReminder` |
| `ConnectPlatformsReminder` | `ConnectPlatformsReminder` |
| `PartnerPayoutConfirmed` | `PartnerPayoutConfirmed` |
| `PartnerPayoutProcessed` | `PartnerPayoutProcessed` |
| `PartnerDeactivated` | `PartnerDeactivated` |
| `PartnerBanned` | `PartnerBanned` |
| `ProgramPayoutThankYou` | `ProgramPayoutThankYou` |
| `UnresolvedRiskEventsSummary` | `UnresolvedRiskEventsSummary` |
| `PartnerGroupChanged` | `PartnerGroupChanged` |
| `PartnerRewardUpdated` | `PartnerRewardUpdated` |
| `WorkspaceDisabled` | `WorkspaceDisabled` |
| `DubStartupProgramAnnouncement` | `DubStartupProgramAnnouncement` |
| `DubProductUpdateSummer26` | `DubProductUpdateSummer26` |
Sources: [apps/web/lib/email/email-templates-map.ts:1-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/email/email-templates-map.ts#L1-L32)
> [!WARNING]
> If a template name provided in the batch payload is missing from `EMAIL_TEMPLATES_MAP`, `Promise.allSettled` catches the error per item. If every item in the batch fails processing or if the subsequent `sendBatchEmail` call returns a Resend API error, the route logs the failure with mention flags and returns a `500` status response.
Sources: [apps/web/app/ee/api/cron/send-batch-email/route.ts:54-173](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/send-batch-email/route.ts#L54-L173)
### Dashboard email domain administration
Workspace email domain administration is managed client-side through the `EmailDomains` component located in the workspace settings. The interface checks workspace capabilities using `getPlanCapabilities` to enforce whether email campaign sending is allowed for the active plan.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/email/page-client.tsx:23-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/email/page-client.tsx#L23-L35)
When a workspace lacks permission to send email campaigns, an animated empty state directs users to an upgrade path (`/[slug]/upgrade`) with a link to help documentation. When domains are permitted, the client monitors `searchParams` for DomainConnect callback states (`domain_connect=callback`). If errors occur (such as `user_cancel`), toast notifications alert the user; otherwise, successful submissions trigger staged SWR cache revalidations for verification endpoints (`/api/email-domains/*/verify` and `/api/email-domains`) at 0, 4000, and 10000 milliseconds before cleaning up query parameters.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/email/page-client.tsx:36-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/email/page-client.tsx#L36-L105)
## Related
- [Scheduled Cron Tasks](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/scheduled-cron-tasks)
---
## Technical docs: POST Completely delete a program
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/deleteprogramadminpost
## Request Body
Program ID or slug
## Responses
## Try It
---
## Technical docs: GET Get recent programs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getrecentadminprograms
## Parameters
## Responses
## Try It
---
## Technical docs: Webhooks & Postbacks
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/webhooks-postbacks
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/api/dub/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts)
- [apps/web/app/api/webhooks/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts)
- [apps/web/app/ee/api/appsflyer/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts)
- [apps/web/app/ee/api/partner-profile/postbacks/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/route.ts)
- [apps/web/app/ee/api/stripe/integration/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts)
- [apps/web/app/api/postbacks/callback/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/postbacks/callback/route.ts)
- [apps/web/app/ee/api/paypal/webhook/verify-signature.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/paypal/webhook/verify-signature.ts)
- [apps/web/app/ee/api/stripe/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/webhook/route.ts)
- [apps/web/app/ee/api/hubspot/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/route.ts)
- [apps/web/app/ee/api/singular/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/singular/webhook/route.ts)
- [apps/web/app/api/veriff/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/veriff/webhook/route.ts)
- [apps/web/app/ee/api/shopify/integration/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts)
- [apps/web/app/ee/partners.dub.co/dashboard/profile/postbacks/postbackId/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/%5BpostbackId%5D/page.tsx)
- [apps/web/app/ee/api/hubspot/webhook/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts)
- [apps/web/app/ee/api/paypal/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/paypal/webhook/route.ts)
- [apps/web/app/ee/api/stripe/connect/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts)
- [apps/web/app/ee/api/stripe/connect/v2/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/connect/v2/webhook/route.ts)
- [apps/web/app/ee/partners.dub.co/dashboard/profile/postbacks/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page.tsx)
- [apps/web/app/ee/api/intercom/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/route.ts)
- [apps/web/app/ee/api/cron/import/rewardful/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/import/rewardful/route.ts)
- [apps/web/app/ee/api/partner-profile/postbacks/postbackId/rotate-secret/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/%5BpostbackId%5D/rotate-secret/route.ts)
- [apps/web/app/ee/api/cloudflare/webhook/r2-object-created/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cloudflare/webhook/r2-object-created/route.ts)
- [apps/web/app/ee/api/partner-profile/postbacks/postbackId/send-test/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/%5BpostbackId%5D/send-test/route.ts)
- [apps/web/app/ee/api/intercom/webhook/process/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/intercom/webhook/process/route.ts)
- [apps/web/lib/postback/postback-adapters.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts)
- [apps/web/app/ee/api/cron/cleanup/demo-embed-partners/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cron/cleanup/demo-embed-partners/route.ts)
- [apps/web/lib/webhook/signature.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/signature.ts)
- [apps/web/scripts/dev/simulate-shopify-conversion.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/scripts/dev/simulate-shopify-conversion.ts)
- [apps/web/app/api/resend/webhook/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/resend/webhook/route.ts)
- [apps/web/ui/postbacks/postback-secret-modal.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/postbacks/postback-secret-modal.tsx)
## Overview
Dub implements an event-driven webhook and postback architecture to synchronize state across external [partner programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs), payment processors, and notification systems [Workspace Subscriptions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/workspace-subscriptions), [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement). Inbound endpoints process incoming events from services like Stripe, PayPal, HubSpot, Intercom, Shopify, and Veriff while enforcing cryptographic verification through HMAC signatures and IP allowlist checks [Workspace Subscriptions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/workspace-subscriptions), [HubSpot & Intercom](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/hubspot-intercom), [Fraud Prevention](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/fraud-prevention), [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement), [Ad Conversion Sync](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/ad-conversion-sync). Outbound notifications and partner postbacks utilize asynchronous delivery pipelines routed through QStash with automatic retry tracking, status logging via Tinybird, and signature verification headers [Payout Settlement](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/payout-settlement).
Sources: [apps/web/app/api/dub/webhook/route.ts:8-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts#L8-L39), [apps/web/app/api/webhooks/callback/route.ts:22-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts#L22-L101), [apps/web/app/ee/api/appsflyer/webhook/route.ts:27-142](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/appsflyer/webhook/route.ts#L27-L142), [apps/web/app/ee/api/stripe/integration/webhook/route.ts:36-190](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L36-L190), [apps/web/app/ee/api/paypal/webhook/route.ts:21-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/paypal/webhook/route.ts#L21-L58), [apps/web/lib/postback/postback-adapters.ts:24-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L24-L68)
## Outbound Payload Signing and HMAC Construction
### HMAC Cryptographic Generation
Outbound postback dispatches authenticate payloads by generating a cryptographic HMAC-SHA256 signature using the Web Crypto API (`crypto.subtle`). When `createWebhookSignature` executes, it requires a signing secret; if no secret is present, it immediately throws an error stating that a secret must be provided.
```typescript
export const createWebhookSignature = async (secret: string, body: any) => {
if (!secret) {
throw new Error("A secret must be provided to create a webhook signature.");
}
const keyData = new TextEncoder().encode(secret);
const messageData = new TextEncoder().encode(JSON.stringify(body));
const cryptoKey = await crypto.subtle.importKey(
"raw",
keyData,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
```
Sources: [apps/web/lib/webhook/signature.ts:2-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/signature.ts#L2-L16)
The secret string and the JSON-serialized payload body are encoded into byte arrays using `TextEncoder`. The raw key data is imported into the Web Crypto runtime specifying the `HMAC` algorithm and `SHA-256` hash function with usage restricted strictly to signing (`["sign"]`). The resulting signature buffer is converted into an array of unsigned 8-bit integers (`Uint8Array`) and mapped to a hexadecimal string by padding each byte to two hex characters.
```typescript
const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
const signatureArray = Array.from(new Uint8Array(signature));
const hexSignature = signatureArray
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
return hexSignature;
};
```
Sources: [apps/web/lib/webhook/signature.ts:18-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/webhook/signature.ts#L18-L25)
> [!CAUTION]
> Omitting the postback secret will cause `createWebhookSignature` to throw an uncaught error and abort signature generation before any network request is dispatched.
### Transport and Header Injection
Once the cryptographic signature is derived from the transformed payload, `PostbackAdapter` injects the signature into the outbound transmission headers. The signature string is assigned to the `"Dub-Signature"` HTTP header alongside an `"Upstash-Hide-Headers"` configuration set to `"true"` to manage QStash transmission properties.
```typescript
const signature = await createWebhookSignature(
this.postback.secret,
transformedPayload,
);
const response = await qstash.publishJSON({
callback: callbackUrl.href,
failureCallback: callbackUrl.href,
url: this.postback.url,
body: transformedPayload,
headers: {
"Dub-Signature": signature,
"Upstash-Hide-Headers": "true",
},
});
```
Sources: [apps/web/lib/postback/postback-adapters.ts:42-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L42-L56)
## Postback Adapters and Transformation Pipeline
### Abstract Adapter Class and Event Execution
The `PostbackAdapter` abstract class serves as the core base engine for processing and dispatching event payloads to configured partner destinations. Subclasses instantiate with a Prisma `Postback` record and invoke `registerEventTransformers()` during construction to register specific payload translation rules via an internal `PostbackEventTransformers` instance.
```typescript
export interface PostbackPayload {
eventId: string;
event: PostbackTrigger;
createdAt: string;
data: unknown;
}
export abstract class PostbackAdapter {
protected eventTransformers = new PostbackEventTransformers();
constructor(protected postback: Postback) {
this.registerEventTransformers();
}
protected abstract registerEventTransformers(): void;
```
Sources: [apps/web/lib/postback/postback-adapters.ts:8-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L8-L23)
When the `execute` method runs on a `PostbackPayload` object containing an `eventId`, `event` trigger type, `createdAt` timestamp, and raw `data`, it first attempts to transform the payload. If the transformer returns a falsy result, execution terminates early and no network request is sent.
```typescript
async execute(payload: PostbackPayload) {
const transformedPayload = this.eventTransformers.transform(payload);
if (!transformedPayload) {
return;
}
```
Sources: [apps/web/lib/postback/postback-adapters.ts:24-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L24-L30)
> [!NOTE]
> If `eventTransformers.transform(payload)` yields a null or undefined payload, `execute` silently exits without throwing an error or creating delivery artifacts.
Sources: [apps/web/lib/postback/postback-adapters.ts:25-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L25-L29)
### Callback URL Construction and QStash Dispatch
Postback requests require tracking metadata embedded directly into callback query parameters before being handed off to the asynchronous message queue. The transformation pipeline constructs a search parameters object using the postback identifier, event identifier, and event trigger name, which is then serialized onto the callback destination URL via `buildCallbackUrl`.
```typescript
const searchParams = {
postbackId: this.postback.id,
eventId: payload.eventId,
event: payload.event,
};
const callbackUrl = buildCallbackUrl(
`${APP_DOMAIN_WITH_NGROK}/api/postbacks/callback`,
searchParams,
);
```
Sources: [apps/web/lib/postback/postback-adapters.ts:31-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L31-L41)
After computing the HMAC webhook signature using the target postback secret and transformed payload, `PostbackAdapter` publishes the JSON payload to QStash. The publication configuration specifies both the success and failure callback URLs, the destination URL configured on the postback record, and request headers including the signature.
```typescript
const signature = await createWebhookSignature(
this.postback.secret,
transformedPayload,
);
const response = await qstash.publishJSON({
callback: callbackUrl.href,
failureCallback: callbackUrl.href,
url: this.postback.url,
body: transformedPayload,
headers: {
"Dub-Signature": signature,
"Upstash-Hide-Headers": "true",
},
});
```
Sources: [apps/web/lib/postback/postback-adapters.ts:42-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L42-L56)
```mermaid
sequenceDiagram
participant Adapter as PostbackAdapter
participant Transformers as PostbackEventTransformers
participant Crypto as createWebhookSignature
participant QStash as qstash.publishJSON
Adapter->>Transformers: transform(payload)
alt Payload invalid / filtered out
Transformers-->>Adapter: null
Note over Adapter: Execution aborts early
else Payload valid
Transformers-->>Adapter: transformedPayload
Adapter->>Crypto: createWebhookSignature(secret, transformedPayload)
Crypto-->>Adapter: signature
Adapter->>QStash: publishJSON(callback, failureCallback, url, body, headers)
QStash-->>Adapter: response
end
```
Sources: [apps/web/lib/postback/postback-adapters.ts:24-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L24-L60)
Postback delivery attempts enforce runtime logging behavior based on the message response state and environment variables. If the response object lacks a `messageId`, an error is logged to the console, and development environments write a detailed debug log containing the full response and transformed payload.
```typescript
if (!response.messageId) {
console.error("Failed to publish postback event to QStash", response);
}
if (process.env.NODE_ENV === "development") {
console.debug("Published postback event to QStash", {
...response,
payload: transformedPayload,
});
}
}
```
Sources: [apps/web/lib/postback/postback-adapters.ts:58-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/postback/postback-adapters.ts#L58-L68)
## Partner Postback Management and Authentication
### Postback Configuration Endpoints
Partner postback configurations are managed via API routes protected by partner profile authentication, requiring the `postbacks` feature flag. The `GET /api/partner-profile/postbacks` route fetches all postback configurations associated with the authenticated partner identifier, ordered descending by their creation timestamp, and validates the output against `postbackSchema`.
```typescript
// GET /api/partner-profile/postbacks
export const GET = withPartnerProfile(
async ({ partner }) => {
const postbacks = await prisma.postback.findMany({
where: {
partnerId: partner.id,
},
orderBy: {
createdAt: "desc",
},
});
return NextResponse.json(z.array(postbackSchema).parse(postbacks));
},
{
requiredPermission: "postbacks.read",
featureFlag: "postbacks",
},
);
```
Sources: [apps/web/app/ee/api/partner-profile/postbacks/route.ts:21-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/route.ts#L21-L39)
The `POST /api/partner-profile/postbacks` endpoint parses input parameters via `createPostbackInputSchema`, enforces a maximum resource limit defined by `MAX_POSTBACKS`, and generates a secure authentication token for the postback secret using `POSTBACK_SECRET_PREFIX` and `POSTBACK_SECRET_LENGTH`. New postback records are initialized with an identifier prefixed by `pb_`, receiver channels identified via `identifyPostbackChannel`, and associated triggers.
```typescript
// POST /api/partner-profile/postbacks
export const POST = withPartnerProfile(
async ({ partner, req }) => {
const { name, url, triggers } = createPostbackInputSchema.parse(
await parseRequestBody(req),
);
const postbackCount = await prisma.postback.count({
where: {
partnerId: partner.id,
},
});
if (postbackCount >= MAX_POSTBACKS) {
throw new DubApiError({
code: "exceeded_limit",
message: `Maximum number of postbacks (${MAX_POSTBACKS}) reached.`,
});
}
const secret = createToken({
prefix: POSTBACK_SECRET_PREFIX,
length: POSTBACK_SECRET_LENGTH,
});
const postback = await prisma.postback.create({
data: {
id: createId({ prefix: "pb_" }),
partnerId: partner.id,
name,
url,
secret,
triggers,
receiver: identifyPostbackChannel(url),
},
});
return NextResponse.json(createPostbackOutputSchema.parse(postback), {
status: 201,
});
},
{
requiredPermission: "postbacks.write",
featureFlag: "postbacks",
},
);
```
Sources: [apps/web/app/ee/api/partner-profile/postbacks/route.ts:41-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/route.ts#L41-L86)
> [!WARNING]
> Attempting to create a postback when the existing count equals or exceeds `MAX_POSTBACKS` throws a `DubApiError` with the `exceeded_limit` error code, aborting the write operation before record creation.
Sources: [apps/web/app/ee/api/partner-profile/postbacks/route.ts:48-59](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/route.ts#L48-L59)
### Secret Rotation and Test Delivery
Secret rotation and test dispatch handlers provide ongoing management and diagnostic validation for existing postback configurations. The `POST /api/partner-profile/postbacks/[postbackId]/rotate-secret` endpoint validates the target postback using `getPostbackOrThrow`, generates a new cryptographic token with standard prefix and length constraints, updates the database record, and returns the updated secret value.
```typescript
// POST /api/partner-profile/postbacks/[postbackId]/rotate-secret
export const POST = withPartnerProfile(
async ({ partner, params }) => {
const { postbackId } = params;
await getPostbackOrThrow({
postbackId,
partnerId: partner.id,
});
const secret = createToken({
prefix: POSTBACK_SECRET_PREFIX,
length: POSTBACK_SECRET_LENGTH,
});
await prisma.postback.update({
where: {
id: postbackId,
},
data: {
secret,
},
});
return NextResponse.json({ secret });
},
{
requiredPermission: "postbacks.write",
featureFlag: "postbacks",
},
);
```
Sources: [apps/web/app/ee/api/partner-profile/postbacks/postbackId/rotate-secret/route.ts:11-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/%5BpostbackId%5D/rotate-secret/route.ts#L11-L41)
Diagnostic test events are dispatched via `POST /api/partner-profile/postbacks/[postbackId]/send-test`, which maps supported trigger types to predefined sample payloads.
| Trigger Type | Payload Source Module |
| :--- | :--- |
| `lead.created` | `leadCreated` (`@/lib/postback/sample-events/lead-created.json`) |
| `sale.created` | `saleCreated` (`@/lib/postback/sample-events/sale-created.json`) |
| `commission.created` | `commissionCreated` (`@/lib/postback/sample-events/commission-created.json`) |
Sources: [apps/web/app/ee/api/partner-profile/postbacks/postbackId/send-test/route.ts:5-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/%5BpostbackId%5D/send-test/route.ts#L5-L17)
Before triggering test deliveries, the endpoint verifies that the requested event type is included in the postback's configured triggers array, throwing a `bad_request` error if unconfigured. Test payloads are dispatched through `sendPartnerPostback` with `skipEnrichment` enabled.
```typescript
// POST /api/partner-profile/postbacks/[postbackId]/send-test
export const POST = withPartnerProfile(
async ({ partner, params, req }) => {
const { postbackId } = params;
const { event } = sendTestPostbackInputSchema.parse(
await parseRequestBody(req),
);
const postback = await getPostbackOrThrow({
postbackId,
partnerId: partner.id,
});
const triggers = postback.triggers as string[];
if (!triggers.includes(event)) {
throw new DubApiError({
code: "bad_request",
message: "The selected event is not configured for this postback.",
});
}
await sendPartnerPostback({
partnerId: partner.id,
event,
data: samplePayloads[event],
skipEnrichment: true,
});
return NextResponse.json({});
},
{
requiredPermission: "postbacks.write",
featureFlag: "postbacks",
},
);
```
Sources: [apps/web/app/ee/api/partner-profile/postbacks/postbackId/send-test/route.ts:19-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/partner-profile/postbacks/%5BpostbackId%5D/send-test/route.ts#L19-L55)
## Partner Postback Dashboard Interface
### Postback List and Detail Views
The partner portal provides dedicated React client components for inspecting and managing postbacks under the `/profile/postbacks` and `/profile/postbacks/[postbackId]` routes. The list view utilizes SWR to fetch all postback records from `/api/partner-profile/postbacks`, rendering either loading skeletons (`PostbackPlaceholder`), a list of `PostbackCard` components, or an empty state warning when no configurations exist.
```tsx
const {
data: postbacks,
error,
isLoading,
mutate,
} = useSWR("/api/partner-profile/postbacks", fetcher, {
keepPreviousData: true,
});
const { openPostbackSecretModal, PostbackSecretModal } =
usePostbackSecretModal();
const { openAddPostbackModal, AddEditPostbackModal } =
useAddEditPostbackModal(() => mutate(), openPostbackSecretModal);
return (
<>
}
>
{isLoading ? (
{Array.from({ length: 3 }).map((_, idx) => (
))}
) : error ? (
mutate()}
className="flex h-8 items-center justify-center gap-2 rounded-md border border-neutral-200 bg-white px-4 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50"
>
Try again
) : postbacks && postbacks.length > 0 ? (
{postbacks.map((postback) => (
))}
) : (
)}
```
Sources: [apps/web/app/ee/partners.dub.co/dashboard/profile/postbacks/page.tsx:18-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page.tsx#L18-L88)
When navigating to a specific configuration via `postbackId`, the detail page fetches endpoint metadata alongside logged delivery events from `/api/partner-profile/postbacks/[postbackId]/events` with previous data preservation enabled. If the endpoint returns a `404` error code, the client redirects the user back to the main postbacks index.
```tsx
export default function PostbackDetailPage() {
const router = useRouter();
const { postbackId } = useParams();
const [openPopover, setOpenPopover] = useState(false);
const {
data: postback,
error,
isLoading,
mutate,
} = useSWR
(
postbackId ? `/api/partner-profile/postbacks/${postbackId}` : null,
fetcher,
);
const {
data: events,
error: eventsError,
isLoading: isEventsLoading,
} = useSWR(
postbackId ? `/api/partner-profile/postbacks/${postbackId}/events` : null,
fetcher,
{ keepPreviousData: true },
);
const { postbackEventDetailsSheet, openWithEvent } =
usePostbackEventDetailsSheet();
const { openPostbackSecretModal, PostbackSecretModal } =
usePostbackSecretModal();
const { openEditPostbackModal, AddEditPostbackModal } =
useAddEditPostbackModal(() => mutate(), openPostbackSecretModal);
if (Boolean(error && (error as { status?: number }).status === 404)) {
redirect("/profile/postbacks");
}
```
Sources: [apps/web/app/ee/partners.dub.co/dashboard/profile/postbacks/postbackId/page.tsx:22-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/%5BpostbackId%5D/page.tsx#L22-L58)
> [!NOTE]
> The detail view renders a token avatar derived from the postback identifier, destination URL, status badge (`PostbackStatus`), and action popovers alongside an interactive event list supporting click-to-inspect drawers.
Sources: [apps/web/app/ee/partners.dub.co/dashboard/profile/postbacks/postbackId/page.tsx:92-150](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/%5BpostbackId%5D/page.tsx#L92-L150)
### Signing Secret Modal Management
The `usePostbackSecretModal` hook manages the state for displaying newly generated or rotated cryptographic secrets to partners. It exposes a helper function to open the modal with a specified secret string and returns a stable `PostbackSecretModal` element wrapper that prevents unnecessary remounts during parent re-renders.
```tsx
export function usePostbackSecretModal() {
const [state, setState] = useState<{ show: boolean; secret: string }>({
show: false,
secret: "",
});
function openPostbackSecretModal(secret: string) {
setState({ show: true, secret });
}
function closePostbackSecretModal() {
setState({ show: false, secret: "" });
}
return {
openPostbackSecretModal,
closePostbackSecretModal,
// Return an element (rendered as `{PostbackSecretModal}`) rather than a
// per-render component type, which would remount the modal – and reset its
// state – on every parent render
PostbackSecretModal: (
{
const next = typeof show === "function" ? show(state.show) : show;
if (!next) closePostbackSecretModal();
}}
secret={state.secret}
/>
),
isPostbackSecretModalOpen: state.show,
};
}
```
Sources: [apps/web/ui/postbacks/postback-secret-modal.tsx:74-106](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/postbacks/postback-secret-modal.tsx#L74-L106)
Inside the modal component, partners can view their monospace-formatted signing secret and utilize a clipboard copy button backed by `useCopyToClipboard` and sonner toast notifications.
```tsx
function PostbackSecretModal({
showModal,
setShowModal,
secret,
}: PostbackSecretModalProps) {
const [copied, copyToClipboard] = useCopyToClipboard();
return (
Signing secret
Copy it and store it somewhere safe. You will need it to verify
postback signatures.
Signing secret
{secret}
{
e.stopPropagation();
toast.promise(copyToClipboard(secret), {
success: "Secret copied to clipboard!",
});
}}
type="button"
className="flex h-7 shrink-0 items-center gap-2 rounded-md border border-neutral-200 bg-white px-2 py-1 text-xs font-medium text-neutral-900 hover:bg-neutral-50"
>
{copied ? (
) : (
)}
{copied ? "Copied" : "Copy"}
setShowModal(false)}
className="w-full"
/>
);
}
```
Sources: [apps/web/ui/postbacks/postback-secret-modal.tsx:13-72](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/postbacks/postback-secret-modal.tsx#L13-L72)
## QStash Delivery Callbacks and Failure Tracking
### QStash Callback Processing
Asynchronous webhook and postback delivery receipts dispatched by QStash are received at `/api/webhooks/callback` and `/api/postbacks/callback`. Incoming requests are authenticated using `verifyQstashSignature` against the raw request body. Query parameters are extracted and validated using Zod schemas to identify the associated resource, event type, and event identifier.
```typescript
const searchParamsSchema = z.object({
webhookId: z.string(),
eventId: z.string(),
event: z.enum(WEBHOOK_TRIGGERS),
failed: z.literal("true").optional(),
});
// POST /api/webhooks/callback – listen to webhooks status from QStash
export const POST = async (req: Request) => {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
const { url, status, body, sourceBody, sourceMessageId } =
webhookCallbackSchema.parse(JSON.parse(rawBody));
const {
webhookId,
eventId,
event,
failed: deliveryFailed, // failed after all the retries
} = searchParamsSchema.parse(getSearchParams(req.url));
```
Sources: [apps/web/app/api/webhooks/callback/route.ts:14-35](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts#L14-L35)
```typescript
export const POST = async (req: Request) => {
const rawBody = await req.text();
await verifyQstashSignature({
req,
rawBody,
});
const { status, url, sourceMessageId, body, sourceBody, retried } =
postbackCallbackBodySchema.parse(JSON.parse(rawBody));
const { postbackId, eventId, event } = postbackCallbackParamsSchema.parse(
getSearchParams(req.url),
);
```
Sources: [apps/web/app/api/postbacks/callback/route.ts:12-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/postbacks/callback/route.ts#L12-L25)
For webhooks, the system queries the database for the corresponding webhook configuration. If the record does not exist, an error response is returned. Base64-encoded source payloads and response bodies are decoded into UTF-8 strings. A status code of `-1` is normalized to `503` to represent connection timeouts or network failures.
```typescript
const webhook = await prisma.webhook.findUnique({
where: {
id: webhookId,
},
});
if (!webhook) {
console.error("Webhook not found", { webhookId });
return new Response("Webhook not found");
}
const request = Buffer.from(sourceBody, "base64").toString("utf-8");
const response = Buffer.from(body, "base64").toString("utf-8");
const isFailed = status >= 400 || status === -1;
```
Sources: [apps/web/app/api/webhooks/callback/route.ts:36-50](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts#L36-L50)
> [!NOTE]
> If a Zapier webhook returns an HTTP `410` Gone status, the webhook record is deleted automatically to clean up uninstalled integrations.
Sources: [apps/web/app/api/webhooks/callback/route.ts:51-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts#L51-L64)
### Failure Tracking and Tinybird Logging
Delivery outcomes are recorded asynchronously using `Promise.allSettled`. Webhook events are logged to Tinybird via `recordWebhookEvent`, storing the URL, event trigger, event ID, HTTP status, request body, response body, and message ID. Postback events are recorded via `recordPostbackEvent`, which checks for successful row insertions and returns a `400` error response if Tinybird ingestion fails.
```typescript
const tbResponse = await recordPostbackEvent({
event_id: eventId,
postback_id: postbackId,
message_id: sourceMessageId,
event,
url,
response_status: status === -1 ? 503 : status,
request_body: request,
response_body: response,
retry_attempt: retried,
});
if (tbResponse.successful_rows === 0) {
return logAndRespond(
`Failed to record event ${eventId} for postback ${postbackId}.`,
{
status: 400,
},
);
}
…
const tbResponse = await recordPostbackEvent({
event_id: eventId,
postback_id: postbackId,
message_id: sourceMessageId,
event,
url,
response_status: status === -1 ? 503 : status,
request_body: request,
response_body: response,
retry_attempt: retried,
});
if (tbResponse.successful_rows === 0) {
return logAndRespond(
`Failed to record event ${eventId} for postback ${postbackId}.`,
{
status: 400,
},
);
}
```
Sources: [apps/web/app/api/postbacks/callback/route.ts:43-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts#L68-L77), [apps/web/app/api/postbacks/callback/route.ts:43-62](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/postbacks/callback/route.ts#L43-L62)
The system evaluates delivery failures based on HTTP status codes where `status >= 400 || status === -1`. When a failure occurs on the final retry attempt, `handleWebhookFailure` is invoked. Conversely, if a delivery succeeds while consecutive failures exceed zero, `resetWebhookFailureCount` clears the failure counter. External payout events for `payout.confirmed` triggers are processed with a mapped status of `failure`, `temporary_failure`, or `success`.
```typescript
await Promise.allSettled([
// Record the webhook event
recordWebhookEvent({
url,
event,
event_id: eventId,
http_status: status === -1 ? 503 : status,
webhook_id: webhookId,
request_body: request,
response_body: response,
message_id: sourceMessageId,
}),
// Handle the webhook delivery failure if it's the last retry
...(isFailed ? [handleWebhookFailure(webhookId)] : []),
// Only reset if there were previous failures
...(webhook.consecutiveFailures > 0 && !isFailed
? [resetWebhookFailureCount(webhookId)]
: []),
// Handle payout events
...(event === "payout.confirmed"
? [
handleExternalPayoutEvent({
webhook,
payload: JSON.parse(request),
status: deliveryFailed
? "failure"
: isFailed
? "temporary_failure"
: "success",
}),
]
: []),
]);
```
Sources: [apps/web/app/api/webhooks/callback/route.ts:66-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/webhooks/callback/route.ts#L66-L101)
## Core Inbound System Webhook Handlers
### Internal System Webhook Endpoints and Distribution
The system manages inbound notifications through dedicated route handlers, including `/api/dub/webhook`, storage event forwarders, and integration receivers. Incoming requests extract cryptographic signatures and validate them using `timingSafeCompare` to prevent timing attacks against webhook secrets. For instance, the main Dub webhook route checks the `Dub-Signature` header against an HMAC-SHA256 hash computed over the request body using `process.env.DUB_WEBHOOK_SECRET`.
```typescript
import { withAxiom } from "@/lib/axiom/server";
import { webhookPayloadSchema } from "@/lib/webhook/schemas";
import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";
import crypto from "crypto";
import { leadCreated } from "./lead-created";
import { saleCreated } from "./sale-created";
// POST /api/dub/webhook - receive webhooks for Dub
export const POST = withAxiom(async (req: Request) => {
const body = await req.json();
const { event, data } = webhookPayloadSchema.parse(body);
const webhookSignature = req.headers.get("Dub-Signature");
if (!webhookSignature) {
return new Response("No signature provided", { status: 401 });
}
const computedSignature = crypto
.createHmac("sha256", `${process.env.DUB_WEBHOOK_SECRET}`)
.update(JSON.stringify(body))
.digest("hex");
if (!timingSafeCompare(webhookSignature, computedSignature)) {
return new Response("Invalid signature", { status: 400 });
}
```
Sources: [apps/web/app/api/dub/webhook/route.ts:1-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts#L1-L26)
Once validated, incoming payloads are parsed against Zod schemas and distributed according to their event types. The main webhook handler processes referral and conversion triggers using a switch statement over the event payload property.
```typescript
let response = "OK";
switch (event) {
case "lead.created": // new signup via referral link (lead event)
response = await leadCreated(data);
break;
case "sale.created": // new sale via referral link (sale event)
response = await saleCreated(data);
break;
}
return new Response(response);
});
```
Sources: [apps/web/app/api/dub/webhook/route.ts:28-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts#L28-L40)
> [!WARNING]
> Requests lacking a valid signature header return an immediate `401` unauthorized response before any JSON body parsing occurs.
Sources: [apps/web/app/api/dub/webhook/route.ts:13-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/dub/webhook/route.ts#L13-L17)
### Third-Party Integration and Cloudflare Webhook Handlers
Third-party integrations process inbound notifications from external platforms such as Stripe, HubSpot, Intercom, PayPal, and Cloudflare R2 storage workers. Each integration utilizes distinct signature validation mechanisms: Cloudflare worker requests verify bearer tokens using `verifyWorkerSecret`, while PayPal webhooks validate transmission headers and certificates against an allowlist.
```typescript
const r2ObjectCreatedWebhookBodySchema = z.object({
notification: r2ObjectCreatedNotificationSchema,
});
function verifyWorkerSecret(req: Request) {
const webhookSecret = assertEnv("CLOUDFLARE_WORKER_WEBHOOK_SECRET");
const auth = req.headers.get("authorization") || "";
const token = auth.startsWith("Bearer ") ? auth.slice("Bearer ".length) : "";
return timingSafeCompare(token, webhookSecret);
}
// POST /api/cloudflare/webhook/r2-object-created
// Called by the Cloudflare queue consumer Worker (thin forwarder).
export async function POST(req: Request) {
try {
if (!verifyWorkerSecret(req)) {
return NextResponse.json(
{
error: "Unauthorized",
},
{
status: 401,
},
);
}
```
Sources: [apps/web/app/ee/api/cloudflare/webhook/r2-object-created/route.ts:15-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/cloudflare/webhook/r2-object-created/route.ts#L15-L41)
```typescript
export async function verifySignature({
event,
headers,
}: {
event: string; // raw event data as string
headers: Headers;
}) {
const transmissionId = headers.get("paypal-transmission-id");
const transmissionSig = headers.get("paypal-transmission-sig");
const timeStamp = headers.get("paypal-transmission-time");
const certUrl = headers.get("paypal-cert-url");
if (!transmissionId || !transmissionSig || !timeStamp || !certUrl) {
console.error(
"[PayPal] Missing required headers for signature verification",
);
return false;
}
if (!isValidPayPalCertUrl(certUrl)) {
console.error(`[PayPal] Rejected non-PayPal certificate URL: ${certUrl}`);
return false;
}
const certPem = await downloadAndCache(certUrl);
if (!certPem) {
console.error("[PayPal] Failed to download or cache PayPal certificate");
return false;
}
const crc = parseInt("0x" + crc32(event).toString("hex"));
const message = `${transmissionId}|${timeStamp}|${paypalEnv.PAYPAL_WEBHOOK_ID}|${crc}`;
const signatureBuffer = Buffer.from(transmissionSig, "base64");
const verifier = crypto.createVerify("SHA256");
verifier.update(message);
return verifier.verify(certPem, new Uint8Array(signatureBuffer));
}
```
Sources: [apps/web/app/ee/api/paypal/webhook/verify-signature.ts:62-101](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/paypal/webhook/verify-signature.ts#L62-L101)
Stripe integration and connect webhooks construct events using `stripe.webhooks.constructEvent` with `Stripe-Signature` verification against environment secrets. Relevant Stripe events are filtered before dispatching to specific workflow functions.
| Event Type | Target Handler / Action | Sources |
| :--- | :--- | :--- |
| `account.application.deauthorized` | `accountApplicationDeauthorized` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:23-138](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L23-L138) |
| `charge.refunded` | `chargeRefunded` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:24-145](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L24-L145) |
| `checkout.session.completed` | `checkoutSessionCompleted` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:25-152](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L25-L152) |
| `coupon.deleted` | `couponDeleted` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:26-157](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L26-L157) |
| `customer.created` / `customer.updated` | `syncCustomer` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:27-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L27-L164) |
| `customer.subscription.created` | `customerSubscriptionCreated` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:29-171](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L29-L171) |
| `customer.subscription.deleted` | `customerSubscriptionDeleted` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:30-175](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L30-L175) |
| `invoice.paid` | `invoicePaid` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:31-181](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L31-L181) |
| `promotion_code.updated` | `promotionCodeUpdated` | [apps/web/app/(ee)/api/stripe/integration/webhook/route.ts:32-187](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L32-L187) |
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:22-190](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L22-L190)
> [!TIP]
> When Stripe rate limit or lock timeout errors occur during webhook execution, handlers catch the error and return an HTTP `429` status code, prompting Stripe to retry the event instead of treating it as an internal server error.
Sources: [apps/web/app/ee/api/stripe/integration/webhook/route.ts:191-204](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts#L191-L204)
## Related
- [Queue Workers](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/background-processing/queue-workers)
- [Conversion Tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking)
---
## Technical docs: GET Get marketplace programs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminprograms
## Responses
## Try It
---
## Technical docs: Admin Dashboard
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/admin-dashboard
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/admin.dub.co/dashboard/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/components/impersonate-user.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx)
- [apps/web/app/ee/api/admin/impersonate/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/impersonate/route.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/trusted/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/trusted/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/domains/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/domains/page.tsx)
- [apps/web/ui/domains/domain-card.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/domains/domain-card.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/page-client.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/network/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/links/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx)
- [apps/web/lib/auth/admin-access-guard.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin-access-guard.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/layout-nav-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx)
- [apps/web/lib/auth/admin-impersonation.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin-impersonation.ts)
- [apps/web/lib/middleware/admin.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/admin.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/partners/network/network-partner-application-sheet.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/analytics/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/analytics/page.tsx)
- [apps/web/app/ee/api/admin/links/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/links/route.ts)
- [apps/web/app/ee/api/admin/partners/trusted/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/trusted/route.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/events/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/events/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/links/links-nav-tabs.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/links-nav-tabs.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/layout.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/page.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/default/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/default/page-client.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/links/components/disable-restore-workspace.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/disable-restore-workspace.tsx)
- [apps/web/lib/auth/admin.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin.ts)
- [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/default/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/default/page.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/links/list/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/list/page.tsx)
- [apps/web/app/domain/browser-graphic.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/%5Bdomain%5D/browser-graphic.tsx)
- [apps/web/app/ee/api/admin/fraud-alerts/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/fraud-alerts/route.ts)
## Overview
The admin dashboard provides a centralized management and moderation portal for Dub administrators and enterprise staff. It operates as an internal interface hosted under the `admin.dub.co` domain, restricted to authorized users belonging to the core Dub workspace. By integrating role-based access guards, session impersonation tools, global link and workspace controls, partner oversight workflows, and custom registrar management tools, the dashboard equips operators with the capabilities needed to supervise platform traffic, review affiliate applications, and handle security incidents.
Sources: [apps/web/lib/auth/admin.ts:22-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin.ts#L22-L39), [apps/web/lib/middleware/admin.ts:8-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/admin.ts#L8-L37)
## Admin Authentication and Role Guards
### Role Verification and Workspace Validation
Dub implements a multi-layered security model to verify internal administrative roles, enforce route guards across edge middleware and API endpoints, and filter UI navigation tabs based on user-specific access rules.
The administrative access architecture relies on membership within the primary Dub workspace (`DUB_WORKSPACE_ID`). The function `getDubAdminRole` queries `prisma.projectUsers` using the user ID and the fixed workspace identifier to retrieve the user's assigned `WorkspaceRole`.
```typescript
export const getDubAdminRole = async (userId: string) => {
const response = await prisma.projectUsers.findUnique({
where: {
userId_projectId: {
userId,
projectId: DUB_WORKSPACE_ID,
},
},
select: {
role: true,
},
});
if (!response) {
return null;
}
return response.role;
};
```
Sources: [apps/web/lib/auth/admin.ts:22-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin.ts#L22-L39)
API routes intended for administrative use are wrapped with the `withAdmin` higher-order function. This handler enforces a strict sequence of checks before executing the underlying controller logic:
1. Validates that an active session and user object exist, returning a `401 Unauthorized` response otherwise.
2. Resolves the user's admin role via `getDubAdminRole`; if no role is found, it returns a `401 Unauthorized` response.
3. If `requiredRoles` are specified, it verifies that the user's role is included in the permitted list, returning a `403 Forbidden` response if validation fails.
4. Validates API path access using `canAccessAdminApiPath`.
```typescript
export const withAdmin =
(
handler: WithAdminHandler,
{ requiredRoles = [] }: { requiredRoles?: WorkspaceRole[] } = {},
) =>
async (
req: Request,
{ params: initialParams }: { params: Promise> },
) => {
const params = (await initialParams) || {};
const session = await getSession();
if (!session?.user) {
return new Response("Unauthorized: Login required.", { status: 401 });
}
const adminRole = await getDubAdminRole(session.user.id);
if (!adminRole) {
return new Response("Unauthorized: Not an admin.", { status: 401 });
}
if (requiredRoles.length > 0 && !requiredRoles.includes(adminRole)) {
return new Response(
`Unauthorized: Missing required admin role(s): ${requiredRoles.join(", ")}.`,
{ status: 403 },
);
}
if (
!canAccessAdminApiPath({
userId: session.user.id,
pathname: new URL(req.url).pathname,
})
) {
return new Response("Unauthorized: You don't have access to this page.", {
status: 403,
});
}
```
Sources: [apps/web/lib/auth/admin.ts:41-78](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin.ts#L41-L78)
> [!IMPORTANT]
> Administrative API endpoints check both workspace project membership and path-specific blocklists. A valid workspace role alone does not grant access to restricted API paths if the user's identifier appears in the admin access blocklist.
### Edge Middleware Guards
Incoming requests to the `admin.dub.co` domain are intercepted by `AdminMiddleware`. The middleware inspects the user token, checks project membership against `DUB_WORKSPACE_ID` using `prismaEdge.projectUsers.findUnique`, and enforces navigation rules before rewriting or redirecting the request.
```typescript
export async function AdminMiddleware(req: NextRequest) {
const { path } = parse(req);
const user = await getUserViaToken(req);
if (!user && path !== "/login") {
return NextResponse.redirect(new URL("/login", req.url));
} else if (user) {
const isAdminUser = await prismaEdge.projectUsers.findUnique({
where: {
userId_projectId: {
userId: user.id,
projectId: DUB_WORKSPACE_ID,
},
},
});
if (!isAdminUser) {
return NextResponse.next(); // throw 404 page
} else if (
path === "/login" ||
!canAccessAdminPath({ userId: user.id, pathname: path })
) {
return NextResponse.redirect(new URL("/", req.url));
}
}
return NextResponse.rewrite(
new URL(`/admin.dub.co${path === "/" ? "" : path}`, req.url),
);
```
Sources: [apps/web/lib/middleware/admin.ts:8-37](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/admin.ts#L8-L37)
### Access Blocklists and Restricted Paths
Certain administrative user IDs can be restricted from accessing specific sensitive dashboard sections and API namespaces through `ADMIN_ACCESS_BLOCKLIST`.
| Guard Constant | Value / Path Array | Purpose |
| --- | --- | --- |
| `ADMIN_ACCESS_BLOCKLIST` | `["user_1M3YFDDQ97AGTKWQ9NCSRQTYB"]` | Identifies user IDs excluded from restricted administrative paths. |
| `ADMIN_RESTRICTED_PATHS` | `["/links", "/revenue", "/domains"]` | Dashboard frontend paths blocked for blocklisted users. |
| `ADMIN_RESTRICTED_API_PATHS` | `["/api/admin/links", "/api/admin/workspaces", "/api/admin/revenue", "/api/admin/domains"]` | API routes blocked for blocklisted users. |
Sources: [apps/web/lib/auth/admin-access-guard.ts:3-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin-access-guard.ts#L3-L14)
Path matching is handled by `canAccessAdminPath` and `canAccessAdminApiPath`, which evaluate whether a given pathname matches or starts with any entry in the restricted path arrays for blocklisted users.
```typescript
const matchesPath = (pathname: string, paths: string[]) =>
paths.some((p) => pathname === p || pathname.startsWith(`${p}/`));
export const isAdminAccessRestricted = (userId?: string | null): boolean =>
!!userId && ADMIN_ACCESS_BLOCKLIST.includes(userId);
export const canAccessAdminPath = ({
userId,
pathname,
}: {
userId?: string | null;
pathname: string;
}): boolean =>
!isAdminAccessRestricted(userId) ||
!matchesPath(pathname, ADMIN_RESTRICTED_PATHS);
export const canAccessAdminApiPath = ({
userId,
pathname,
}: {
userId?: string | null;
pathname: string;
}): boolean =>
!isAdminAccessRestricted(userId) ||
!matchesPath(pathname, ADMIN_RESTRICTED_API_PATHS);
```
Sources: [apps/web/lib/auth/admin-access-guard.ts:16-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin-access-guard.ts#L16-L40)
### UI Navigation Filtering
The admin dashboard layout client utilizes session state and `canAccessAdminPath` to dynamically filter navigation tabs rendered in `AdminNav`. Tabs such as links, revenue, and domains are hidden or omitted for users subject to access restrictions.
```tsx
const visibleTabs = useMemo(
() =>
status === "loading"
? []
: tabs.filter((tab) =>
canAccessAdminPath({
userId: session?.user?.id,
pathname: tab.href,
}),
),
[status, session?.user?.id],
);
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/layout-nav-client.tsx:57-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx#L57-L68)
## User Impersonation Flow
### Identifier Parsing and Query Resolution
The user impersonation system allows administrators to look up accounts by email, workspace slug, custom domain, or Stripe customer ID, view linked projects and partner metrics, and generate secure impersonation links. The client interface handles input parsing, clipboard paste normalization, and user ban actions.
```tsx
export function ImpersonateUser() {
const [data, setData] = useState(null);
const [blockEmailDomain, setBlockEmailDomain] = useState(false);
return (
);
}
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/components/impersonate-user.tsx:10-86](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx#L10-L86)
When an administrator inputs a search query into the form, clipboard paste events are intercepted to clean prefixes such as `mailto:` and extract Stripe customer identifiers matching `cus_[a-zA-Z0-9]+`. The backend API processes this input through `parseImpersonateQuery` to categorize the target into one of four specific identifier types.
| Identifier Type | Matching Pattern / Condition | Resolution Rule |
| --- | --- | --- |
| `email` | Contains `@` | Validated against `emailSchema` using Zod. |
| `stripeCustomerId` | Starts with `cus_` or contains `stripe.com` | Matched using `STRIPE_CUSTOMER_ID_REGEX`. |
| `slug` | Hostname matches app domain with a valid path segment, or raw input matches `validSlugRegex` | Lowercased and checked against slug regex. |
| `domain` | Normalized input matches `validDomainRegex` | Normalized via `normalizeDomainInput`. |
Sources: [apps/web/app/ee/api/admin/impersonate/route.ts:105-180](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/impersonate/route.ts#L105-L180), [apps/web/app/ee/admin.dub.co/dashboard/components/impersonate-user.tsx:104-118](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx#L104-L118)
> [!NOTE]
> If a query string contains a URL pointing to the primary application hostname, the parser extracts the first path segment as a workspace slug, provided it satisfies `validSlugRegex`. Otherwise, it falls back to domain or slug validation on the raw string.
### Usage Metrics and Serialization
Once a user is located, their associated projects and partner configurations are serialized. Projects are selected with fields including plan tiers, trial expiration dates, partner usage statistics, total clicks, total links, and associated programs. If a user belongs to two or fewer projects, the system queries the last 30 days of workspace statistics using `getLast30DayWorkspaceStats`. Additionally, program commissions are grouped and aggregated by `programId`.
```typescript
const userSelect = {
email: true,
projects: {
select: {
project: {
select: {
id: true,
name: true,
slug: true,
plan: true,
planPeriod: true,
trialEndsAt: true,
defaultProgramId: true,
partnersUsage: true,
totalClicks: true,
totalLinks: true,
programs: {
select: {
id: true,
slug: true,
url: true,
},
},
},
},
},
orderBy: {
project: {
totalClicks: "desc",
},
},
},
partners: {
select: {
partner: {
select: {
programs: {
select: {
program: {
select: {
id: true,
name: true,
slug: true,
},
},
status: true,
totalClicks: true,
totalLeads: true,
totalConversions: true,
totalSaleAmount: true,
totalCommissions: true,
},
orderBy: {
totalCommissions: "desc",
},
},
},
},
},
},
} satisfies Prisma.UserSelect;
```
Sources: [apps/web/app/ee/api/admin/impersonate/route.ts:19-79](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/impersonate/route.ts#L19-L79), [apps/web/app/ee/api/admin/impersonate/route.ts:227-245](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/impersonate/route.ts#L227-L245)
### Session Tracking and Impersonation Tokens
Tracking of active administrative impersonation sessions is managed through an in-memory tracking structure in `admin-impersonation.ts`. When an administrator initiates an impersonation session, the target user's email is marked as a pending impersonation event.
```typescript
// Tracks emails signing in via admin impersonation links. Populated in
// CustomPrismaAdapter.useVerificationToken before the token is deleted.
const pendingAdminImpersonations = new Set();
export const markAdminImpersonation = (email: string) => {
pendingAdminImpersonations.add(email.toLowerCase());
};
export const consumeAdminImpersonation = (email: string) => {
const isAdminImpersonation = pendingAdminImpersonations.has(
email.toLowerCase(),
);
if (isAdminImpersonation) {
pendingAdminImpersonations.delete(email.toLowerCase());
}
return isAdminImpersonation;
};
```
Sources: [apps/web/lib/auth/admin-impersonation.ts:1-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin-impersonation.ts#L1-L19)
> [!CAUTION]
> The `pendingAdminImpersonations` set tracks emails signing in via admin impersonation links and is populated within `CustomPrismaAdapter.useVerificationToken` immediately before the verification token is consumed and deleted.
## Link and Workspace Moderation
### Link Search and Filtering
Administrators can moderate platform links through administrative search and filtering endpoints and the links dashboard. The backend API handles queries with sorting and pagination.
```typescript
// GET /api/admin/links
export const GET = withAdmin(async ({ searchParams }) => {
const {
domain,
search,
sort = "createdAt",
page,
} = searchParams as {
domain?: string;
search?: string;
sort?: "createdAt" | "clicks" | "lastClicked";
page?: string;
};
```
Sources: [apps/web/app/ee/api/admin/links/route.ts:7-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/links/route.ts#L7-L20)
| Parameter | Type / Options | Description |
| --- | --- | --- |
| `domain` | `string` | Filter links by specific custom domain. |
| `search` | `string` | Search query for short links or destination URLs. |
| `sort` | `"createdAt" \| "clicks" \| "lastClicked"` | Ordering field for query results (default: `createdAt`). |
| `page` | `string` | Pagination offset index (100 items per page). |
Sources: [apps/web/app/ee/api/admin/links/route.ts:9-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/links/route.ts#L9-L19), [apps/web/app/ee/api/admin/links/route.ts:71-77](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/links/route.ts#L71-L77)
> [!NOTE]
> When no search query is provided, the API automatically restricts queries to domains defined in `DUB_DOMAINS_ARRAY` created within the last 30 days, while excluding legal user accounts (`LEGAL_USER_ID`) or unassigned links.
Sources: [apps/web/app/ee/api/admin/links/route.ts:21-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/links/route.ts#L21-L40)
If a search query begins with `https://`, the query matches the `shortLink` field precisely. Otherwise, it performs an OR-match searching partial substrings across both `shortLink` and destination `url` fields.
Sources: [apps/web/app/ee/api/admin/links/route.ts:41-55](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/links/route.ts#L41-L55)
### Workspace Disabling and Restoration
Administrative moderation includes tools to disable or restore all links associated with a workspace slug. The interface requires entering a workspace slug (prefixed with `app.dub.co/`) and executing actions via POST requests to workspace moderation endpoints.
```tsx
const handleAction = async (action: "disable" | "restore", slug: string) => {
const message =
action === "disable"
? `Are you sure you want to disable all links for workspace "${slug}"? This will also downgrade owners to billing and members to viewer, and notify workspace owners by email.`
: `Are you sure you want to restore all links for workspace "${slug}"? This will also revert billing users to owner and viewers to member.`;
if (!window.confirm(message)) return;
setPending(action);
try {
const res = await fetch(`/api/admin/workspaces/${action}`, {
method: "POST",
body: JSON.stringify({ slug }),
});
if (res.ok) {
toast.success(
action === "disable"
? "Workspace links disabled"
: "Workspace links restored",
);
} else {
const error = await res.text();
toast.error(error || "Something went wrong. Please try again.");
}
} catch {
toast.error("Network error. Please check your connection and try again.");
} finally {
setPending(null);
}
};
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/links/components/disable-restore-workspace.tsx:12-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/disable-restore-workspace.tsx#L12-L42), [apps/web/app/ee/admin.dub.co/dashboard/links/page.tsx:12-20](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx#L12-L20)
> [!CAUTION]
> Disabling workspace links automatically downgrades owners to billing and members to viewer roles, and dispatches email notifications to workspace owners. Restoring workspace links reverses these role changes, promoting billing users back to owners and viewers back to members.
Sources: [apps/web/app/ee/admin.dub.co/dashboard/links/page.tsx:13-18](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx#L13-L18), [apps/web/app/ee/admin.dub.co/dashboard/links/components/disable-restore-workspace.tsx:12-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/disable-restore-workspace.tsx#L12-L17)
## Partner Network Oversight
### Network Partner Applications and Metadata
Administrators review incoming partner applications through the network oversight dashboard at `/partners/network`. The application listing supports filtering by network status and country, and dynamically selects date columns based on the active status query parameter.
| Status Value | Date Column Identifier | Header Label |
| --- | --- | --- |
| `submitted` | `submittedAt` | Submitted |
| `approved` | `reviewedAt` | Approved |
| `rejected` | `reviewedAt` | Rejected |
| *Other/Default* | `createdAt` | Joined |
Sources: [apps/web/app/ee/admin.dub.co/dashboard/partners/network/page.tsx:44-66](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx#L44-L66)
The application detail sheet provides tabs for inspecting profile metadata, associated affiliate programs, and duplicate account flags. Duplicate partner accounts are automatically flagged when applicants share matching email addresses or profile details.
```tsx
return (
Duplicate partner accounts
These accounts likely match this applicant by email or profile details.
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/partners/network/network-partner-application-sheet.tsx:495-502](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx#L495-L502), [apps/web/app/ee/admin.dub.co/dashboard/partners/network/network-partner-application-sheet.tsx:395-442](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx#L395-L442)
> [!WARNING]
> Administrators cannot approve a partner whose current network status is already `approved` or `trusted`.
Sources: [apps/web/app/ee/admin.dub.co/dashboard/partners/network/network-partner-application-sheet.tsx:382-386](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx#L382-L386)
### Trusted Partner Management
The trusted partners interface allows administrators with the `owner` role to promote partners to trusted status or revoke their trusted badge. Partners can be added by their unique identifier (prefixed with `pn_`) or email address via `/api/admin/partners/trusted`.
```typescript
// POST /api/admin/partners/trusted
export const POST = withAdmin(
async ({ req }) => {
const { partnerIdOrEmail } = z
.object({
partnerIdOrEmail: z.string().trim().min(1),
})
.parse(await req.json());
if (
!partnerIdOrEmail.startsWith("pn_") &&
!partnerIdOrEmail.includes("@")
) {
return new Response("Invalid partner ID or email.", { status: 400 });
}
```
Sources: [apps/web/app/ee/api/admin/partners/trusted/route.ts:49-64](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/trusted/route.ts#L49-L64), [apps/web/app/ee/admin.dub.co/dashboard/partners/trusted/page.tsx:105-129](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/trusted/page.tsx#L105-L129)
> [!NOTE]
> Every status transition updates the partner's change history log (`changeHistoryLog`) with audit metadata recording the field change from its previous state to either `trusted` or `approved`.
Sources: [apps/web/app/ee/api/admin/partners/trusted/route.ts:87-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/trusted/route.ts#L87-L97), [apps/web/app/ee/api/admin/partners/trusted/route.ts:147-156](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/admin/partners/trusted/route.ts#L147-L156)
## Program and Operational Tools
### Affiliate Program Management and Partner Account Deletions
Administrators manage affiliate programs directly from the admin dashboard, including listing marketplace programs, updating categories and descriptions via dedicated modals, and reordering display ranks with drag-and-drop controls. Programs can be added via `POST /api/admin/programs` by providing a program slug, or removed permanently via `DELETE /api/admin/programs/[id]`, which deletes associated commissions, payouts, rewards, discounts, links, customers, partner groups, and enrollments.
```tsx
{
if (!newProgramSlug.trim()) return;
setIsAddingProgram(true);
const res = await fetch("/api/admin/programs", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
programSlug: newProgramSlug.trim(),
}),
});
if (!res.ok) {
setIsAddingProgram(false);
toast.error((await res.text()) || "Failed to add program.");
return;
}
await mutate();
setIsAddingProgram(false);
setShowAddProgramModal(false);
setNewProgramSlug("");
toast.success("Program added to marketplace.");
}}
/>
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx:311-343](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx#L311-L343), [apps/web/app/ee/admin.dub.co/dashboard/programs/page.tsx:240-253](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/page.tsx#L240-L253), [apps/web/app/ee/admin.dub.co/dashboard/page.tsx:34-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx#L34-L41)
> [!CAUTION]
> Deleting a partner's Stripe Express account will fail to remove the account if the partner has already received payouts via Stripe, and will leave the partner account intact if they have already accumulated commissions or leads on Dub.
Sources: [apps/web/app/ee/admin.dub.co/dashboard/page.tsx:20-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx#L20-L32)
### Authentication Reset and Support Invites
Operational tools also handle account security recovery and customer engagement. Administrators can reset a user's `invalidLoginAttempts` counter and clear their `lockedAt` timestamp when accounts become locked due to failed authentication thresholds. Additionally, administrators can manually dispatch priority Slack Connect invites to users for a specific workspace via the Slack Support Invite tool, bypassing normal plan checks.
```tsx
Reset Login Attempts
Reset a user's invalidLoginAttempts and lockedAt fields
Slack Support Invite
Manually send a priority Slack Connect invite to a user for a given
workspace (bypasses the plan check).
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/page.tsx:43-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx#L43-L56)
API endpoints handling administrative actions are secured by the `withAdmin` authorization wrapper, which validates that the requesting session belongs to an authenticated user with a registered admin role in the core project workspace (`DUB_WORKSPACE_ID`).
```typescript
export const withAdmin =
(
handler: WithAdminHandler,
{ requiredRoles = [] }: { requiredRoles?: WorkspaceRole[] } = {},
) =>
async (
req: Request,
{ params: initialParams }: { params: Promise> },
) => {
const params = (await initialParams) || {};
const session = await getSession();
if (!session?.user) {
return new Response("Unauthorized: Login required.", { status: 401 });
}
const adminRole = await getDubAdminRole(session.user.id);
if (!adminRole) {
return new Response("Unauthorized: Not an admin.", { status: 401 });
}
if (requiredRoles.length > 0 && !requiredRoles.includes(adminRole)) {
return new Response(
`Unauthorized: Missing required admin role(s): ${requiredRoles.join(", ")}.`,
{ status: 403 },
);
}
```
Sources: [apps/web/lib/auth/admin.ts:41-66](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin.ts#L41-L66), [apps/web/lib/auth/admin.ts:22-39](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/admin.ts#L22-L39)
## Domain and System Analytics Monitoring
### Registrar Operations and Domain Management
Workspace settings allow administrators and workspace members to manage custom domains, configure default Dub domains, and handle registrar provisioning actions. Workspaces can add custom domains, toggle auto-renewal for Dub-provisioned domains, transfer domains, and archive or delete non-provisioned domains.
```tsx
{isDubProvisioned && (
{
setOpenPopover(false);
openDomainRenewalModal(!autoRenew);
}}
icon={
}
className="h-9 justify-start px-2 font-medium"
/>
)}
{!primary && (
{
setOpenPopover(false);
setShowPrimaryDomainModal(true);
}}
icon={ }
className="h-9 justify-start px-2 font-medium"
/>
)}
{canSetAsProgramDomain && (
{
setOpenPopover(false);
setShowChangeDomainModal(true);
}}
icon={ }
className="h-9 justify-start px-2 font-medium"
/>
)}
{!isDubProvisioned && (
{
setOpenPopover(false);
setShowTransferDomainModal(true);
}}
icon={ }
className="h-9 justify-start px-2 font-medium"
disabledTooltip={
primary && activeDomainsCount > 1
? "You cannot transfer your workspace's primary domain. Set another domain as primary to transfer this domain."
: undefined
}
/>
)}
{
setOpenPopover(false);
setShowArchiveDomainModal(true);
}}
icon={ }
className="h-9 justify-start px-2 font-medium"
disabledTooltip={permissionsError || undefined}
/>
{!isDubProvisioned && (
{
setOpenPopover(false);
```
Sources: [apps/web/ui/domains/domain-card.tsx:557-643](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/ui/domains/domain-card.tsx#L557-L643), [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/page-client.tsx:171-221](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/page-client.tsx#L171-L221)
> [!NOTE]
> When Domain Connect callbacks return to the custom domains settings page, the client inspects search parameters for errors or success states, automatically triggering immediate domain verification revalidations followed by delayed revalidation checks at 4 and 10 seconds.
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/page-client.tsx:78-111](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/page-client.tsx#L78-L111)
Workspaces can also enable or disable default Dub branded domains for specific links by making `PATCH` requests to `/api/domains/default`.
```tsx
fetch(`/api/domains/default?workspaceId=${id}`, {
method: "PATCH",
body: JSON.stringify({
defaultDomains: newDefaultDomains.filter(
(d) => d !== null,
),
}),
})
.then(async (res) => {
```
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/default/page-client.tsx:102-110](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/default/page-client.tsx#L102-L110)
| Domain Slug | Mapped Icon Component | Description / Association |
| :--- | :--- | :--- |
| `chatg.pt` | `ChatGPT` | OpenAI ChatGPT branded short links |
| `git.new` | `GitHubEnhanced` | GitHub repository short links |
| `spti.fi` | `Spotify` | Spotify track and album links |
| `cal.link` | `CalendarDays` | Calendar scheduling links |
| `amzn.id` | `Amazon` | Amazon product and affiliate links |
| `ggl.link` | `GoogleEnhanced` | Google service links |
| `fig.page` | `Figma` | Figma design file links |
Sources: [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/default/page-client.tsx:23-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/default/page-client.tsx#L23-L42), [apps/web/app/app.dub.co/dashboard/slug/ee/settings/domains/default/page-client.tsx:78-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/(ee)/settings/domains/default/page-client.tsx#L78-L88)
### Platform Analytics and Event Interfaces
The administrative portal provides system-wide analytics and event monitoring interfaces. Administrators access traffic analytics and event logs through dedicated dashboard pages wrapped in suspense boundaries with layout loaders.
```tsx
export default function AdminAnalytics() {
return (
}>
);
```
Sources: [apps/web/app/ee/admin.dub.co/dashboard/analytics/page.tsx:5-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/analytics/page.tsx#L5-L12), [apps/web/app/ee/admin.dub.co/dashboard/events/page.tsx:7-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/events/page.tsx#L7-L16)
> [!TIP]
> The admin events view wraps the core `EventsProvider` and `AnalyticsClient` components with the `adminPage` flag enabled, allowing administrative inspection of platform-wide event streams.
Sources: [apps/web/app/ee/admin.dub.co/dashboard/events/page.tsx:7-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/events/page.tsx#L7-L16)
## Related
- [Fraud Prevention](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/billing-and-payouts/fraud-prevention)
- [Audit Logs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/audit-logs)
---
## Technical docs: REST API
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/api/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/route.ts)
- [apps/web/lib/openapi/links/get-links.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links.ts)
- [apps/web/lib/openapi/tags/get-tags.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/tags/get-tags.ts)
- [apps/web/lib/openapi/analytics/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/analytics/index.ts)
- [apps/web/app/api/oauth/userinfo/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/oauth/userinfo/route.ts)
- [apps/web/lib/openapi/customers/get-customers.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customers.ts)
- [apps/web/lib/openapi/folders/list-folders.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/folders/list-folders.ts)
- [apps/web/lib/openapi/links/get-link-info.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-link-info.ts)
- [apps/web/lib/openapi/qr/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/qr/index.ts)
- [apps/web/lib/auth/workspace.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts)
- [apps/web/lib/openapi/embed-tokens/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/embed-tokens/index.ts)
- [apps/web/lib/openapi/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/index.ts)
- [apps/web/lib/auth/publishable-key.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts)
- [apps/web/lib/openapi/domains/list-domains.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/domains/list-domains.ts)
- [apps/web/app/api/logs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/logs/route.ts)
- [apps/web/lib/openapi/discount-codes/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/discount-codes/index.ts)
- [apps/web/app/ee/api/programs/programId/resources/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/programs/%5BprogramId%5D/resources/route.ts)
- [apps/web/app/ee/api/marketplace/programs/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/marketplace/programs/route.ts)
- [apps/web/lib/openapi/partners/retrieve-partner-links.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/partners/retrieve-partner-links.ts)
- [apps/web/app/ee/api/network/programs/summary/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/network/programs/summary/route.ts)
- [apps/web/lib/openapi/customers/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/index.ts)
- [apps/web/lib/openapi/discount-codes/list-discount-codes.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/discount-codes/list-discount-codes.ts)
- [apps/web/lib/openapi/customers/get-customer.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customer.ts)
- [apps/web/lib/openapi/tags/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/tags/index.ts)
- [apps/web/app/api/integrations/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/integrations/route.ts)
- [apps/web/lib/openapi/links/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/index.ts)
- [apps/web/lib/openapi/links/get-links-count.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links-count.ts)
- [apps/web/lib/openapi/partners/retrieve-analytics.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/partners/retrieve-analytics.ts)
- [apps/web/lib/openapi/events/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/events/index.ts)
- [apps/web/lib/openapi/program-applications/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/program-applications/index.ts)
## Overview
Dub exposes a comprehensive programmatic interface centered around a robust OpenAPI specification, designed to power integrations, developer tooling, and automated link attribution workflows. The REST API is structured using Zod-backed schemas and Next.js route handlers that serve the complete OpenAPI definition at `/api` with long-term Vercel CDN caching.
Sources: [apps/web/app/api/route.ts:1-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/route.ts#L1-L13), [apps/web/lib/openapi/index.ts:26-89](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/index.ts#L26-L89)
## OpenAPI Specification Generation
### Document Composition and Zod Integration
The public OpenAPI document is assembled using `createDocument` from the `zod-openapi` package, defining metadata for the Dub API. The document sets the OpenAPI version to `3.0.3` and includes metadata fields under `info`, such as title, description (`"Dub is the modern link attribution platform for short links, conversion tracking, and affiliate programs."`), version (`"0.0.1"`), contact information (`support@dub.co`), and the AGPL-3.0 license. The production server is configured with the base URL `https://api.dub.co`.
```typescript
export const document = createDocument({
openapi: "3.0.3",
info: {
title: "Dub API",
description:
"Dub is the modern link attribution platform for short links, conversion tracking, and affiliate programs.",
version: "0.0.1",
contact: {
name: "Dub Support",
email: "support@dub.co",
url: "https://dub.co/support",
},
license: {
name: "AGPL-3.0 license",
url: "https://github.com/dubinc/dub/blob/main/LICENSE.md",
},
},
servers: [
{
url: "https://api.dub.co",
description: "Production API",
},
],
```
Sources: [apps/web/lib/openapi/index.ts:26-48](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/index.ts#L26-L48)
The schema paths aggregate individual path modules covering link operations, analytics, events, tags, folders, domains, tracking, customers, partners, program applications, discount codes, commissions, payouts, embed tokens, QR codes, and bounties.
| Path Module Variable | Description / Source Import |
| :--- | :--- |
| `linksPaths` | Link CRUD and management paths |
| `analyticsPath` | Analytics telemetry paths |
| `eventsPath` | Event stream query paths |
| `tagsPaths` | Link tag management paths |
| `foldersPaths` | Folder grouping paths |
| `domainsPaths` | Custom domain configuration paths |
| `trackPaths` | [Conversion tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking) paths |
| `customersPaths` | Customer entity paths |
| `partnersPaths` | Partner program discovery paths |
| `programApplicationsPaths` | Affiliate application paths |
| `discountCodesPaths` | Discount code management paths |
| `commissionsPaths` | Commission tracking paths |
| `payoutsPaths` | Partner payout paths |
| `embedTokensPaths` | Embeddable dashboard token paths |
| `qrCodePaths` | [QR Code Generator](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/link-attribution/qr-code-generator) paths |
| `bountiesPaths` | Partner bounty paths |
```typescript
import { analyticsPath } from "./analytics";
import { bountiesPaths } from "./bounties";
import { commissionsPaths } from "./commissions";
import { customersPaths } from "./customers";
import { discountCodesPaths } from "./discount-codes";
import { domainsPaths } from "./domains";
import { embedTokensPaths } from "./embed-tokens";
import { eventsPath } from "./events";
import { foldersPaths } from "./folders";
import { linksPaths } from "./links";
import { partnersPaths } from "./partners";
import { payoutsPaths } from "./payouts";
import { programApplicationsPaths } from "./program-applications";
import { qrCodePaths } from "./qr";
import { openApiErrorResponsesComponents } from "./responses";
import { tagsPaths } from "./tags";
import { trackPaths } from "./track";
```
Sources: [apps/web/lib/openapi/index.ts:8-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/index.ts#L8-L24), [apps/web/lib/openapi/index.ts:49-66](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/index.ts#L49-L66)
Components registered within the OpenAPI specification define core data schemas, security schemes, and reusable error responses. The schema registry incorporates `LinkSchema`, `LinkTagSchema`, `FolderSchema`, `DomainSchema`, `DiscountCodeSchema`, `webhookEventSchema`, and `LinkErrorSchema`. Security is established via a bearer HTTP scheme named `token` with a Speakeasy example value of `DUB_API_KEY`. Reusable error responses are spread from `openApiErrorResponsesComponents`.
```typescript
components: {
schemas: {
LinkSchema,
LinkTagSchema,
FolderSchema,
DomainSchema,
DiscountCodeSchema,
webhookEventSchema,
LinkErrorSchema,
},
securitySchemes: {
token: {
type: "http",
description: "Default authentication mechanism",
scheme: "bearer",
"x-speakeasy-example": "DUB_API_KEY",
},
},
responses: {
...openApiErrorResponsesComponents,
},
},
```
Sources: [apps/web/lib/openapi/index.ts:67-88](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/index.ts#L67-L88)
> [!NOTE]
> The OpenAPI route handler exports a `dynamic = "force-static"` configuration directive, indicating that the specification is statically generated at build time rather than dynamically computed on each individual request.
> Sources: [apps/web/app/api/route.ts:4-4](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/route.ts#L4-L4)
### Route Handler and Caching
The generated OpenAPI document object is served via a Next.js GET route handler located in `apps/web/app/api/route.ts`. The handler returns the document as a JSON response using `NextResponse.json(document)`, applying cache-control headers designed for long-term edge caching.
```typescript
export function GET() {
return NextResponse.json(document, {
headers: {
// cache indefinitely till next deployment
"Vercel-CDN-Cache-Control": "s-maxage=31536000",
"Cache-Control": "public, max-age=31536000",
},
});
```
Sources: [apps/web/app/api/route.ts:6-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/route.ts#L6-L13)
The response explicitly assigns cache headers to cache the specification at the edge until the next deployment:
- `Vercel-CDN-Cache-Control`: `s-maxage=31536000`
- `Cache-Control`: `public, max-age=31536000`
Sources: [apps/web/app/api/route.ts:8-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/route.ts#L8-L12)
## Workspace Authentication and Authorization
### Request Authentication and Token Resolution
API requests targeting workspace resources are intercepted and authenticated by the `withWorkspace` wrapper middleware. The middleware inspects incoming HTTP requests for an `Authorization` header, enforcing that it carries the `Bearer ` prefix before extracting the raw credential. When an authorization header is present but lacks the expected prefix, it raises a `DubApiError` with the `bad_request` code. Requests containing an API key starting with the `dub_` prefix are classified as restricted tokens, whereas legacy or standard tokens are looked up against the database or verified via the local token cache using a hashed key representation.
```typescript
const authorizationHeader = requestHeaders.get("Authorization");
if (authorizationHeader) {
if (!authorizationHeader.startsWith("Bearer ")) {
throw new DubApiError({
code: "bad_request",
message:
"Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
});
}
apiKey = authorizationHeader.replace("Bearer ", "");
}
let workspaceId: string | undefined;
let workspaceSlug: string | undefined;
let permissions: PermissionAction[] = [];
const isRestrictedToken = apiKey?.startsWith("dub_");
```
Sources: [apps/web/lib/auth/workspace.ts:98-114](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L98-L114)
```typescript
if (apiKey) {
const hashedKey = await hashToken(apiKey);
const cachedToken = await tokenCache.get({
hashedKey,
});
if (!cachedToken) {
const prismaArgs = {
where: {
hashedKey,
},
select: {
id: true,
expires: true,
...(isRestrictedToken && {
scopes: true,
projectId: true,
installationId: true,
project: {
select: {
plan: true,
trialEndsAt: true,
},
},
}),
user: true,
},
};
if (isRestrictedToken) {
token = await prisma.restrictedToken.findUnique(prismaArgs);
} else {
token = await prisma.token.findUnique(prismaArgs);
}
}
```
Sources: [apps/web/lib/auth/workspace.ts:168-203](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L168-L203)
If an API key is omitted, the middleware attempts to resolve an authenticated user session. Requests failing both token verification and session lookup trigger an `unauthorized` error response. Additionally, tokens that have passed their expiration timestamp are rejected with an access token expired message.
```typescript
if (!token || !token.user) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized: Invalid API key.",
});
}
if (token.expires && token.expires < new Date()) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized: Access token expired.",
});
}
```
Sources: [apps/web/lib/auth/workspace.ts:207-219](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L207-L219), [apps/web/lib/auth/workspace.ts:303-311](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L303-L311)
> [!WARNING]
> Omitting both an authorization header and a valid workspace identifier on non-anonymous routes will cause the middleware to throw either an `unauthorized` or `not_found` error, prompting clients to verify their `workspaceId` query parameters or upgrade from personal API keys.
> Sources: [apps/web/lib/auth/workspace.ts:127-154](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L127-L154)
### Workspace Resolution and Membership
Workspace targets are resolved from route parameters (`params.idOrSlug`, `params.slug`), query parameters (`searchParams.workspaceId`, `searchParams.projectSlug`), or directly from restricted token project associations (`token.projectId`). The identifier is inspected to determine whether it represents a workspace ID prefixed with `ws_` or a standard workspace slug.
```typescript
const idOrSlug =
params?.idOrSlug ||
searchParams.workspaceId ||
params?.slug ||
searchParams.projectSlug;
/*
if there's no workspace ID or slug and it's not a restricted token:
- special case for anonymous link creation
- missing authorization header
- user is still using personal API keys
*/
if (!idOrSlug && !isRestrictedToken) {
// special case for anonymous link creation
if (
requestHeaders.has("dub-anonymous-link-creation") &&
["/links", "/api/links"].includes(req.nextUrl.pathname)
) {
// @ts-expect-error
return await handler({
req: clonedReq,
params,
searchParams,
headers: responseHeaders,
});
// missing authorization header
} else if (!authorizationHeader) {
throw new DubApiError({
code: "unauthorized",
message: "Missing Authorization header.",
});
// in case user is still using personal API keys
} else {
throw new DubApiError({
code: "not_found",
message:
"Workspace ID not found. Did you forget to include a `workspaceId` query parameter? It looks like you might be using personal API keys, we also recommend refactoring to workspace API keys: https://d.to/keys",
});
}
}
if (idOrSlug) {
if (idOrSlug.startsWith("ws_")) {
workspaceId = normalizeWorkspaceId(idOrSlug);
} else {
workspaceSlug = idOrSlug;
}
}
```
Sources: [apps/web/lib/auth/workspace.ts:115-162](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L115-L162), [apps/web/lib/auth/workspace.ts:261-263](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L261-L263)
Once the workspace record is queried, the middleware verifies whether the authenticated user belongs to the workspace by checking the associated user relation and role assignments. Endpoints like `GET /api/integrations` can specify explicit permission requirements (such as `workspaces.read`) through options passed to `withWorkspace`. If the target workspace does not exist, or if the user holds no active membership, the system evaluates pending project invites by email lookup to return precise error codes.
```typescript
export const GET = withWorkspace(
async ({ workspace }) => {
const integrations = await prisma.integration.findMany({
where: {
installations: {
some: {
project: {
slug: workspace.slug,
},
},
},
},
orderBy: {
createdAt: "desc",
},
});
return NextResponse.json(
integrations.map((integration) =>
installedIntegrationSchema.parse(integration),
),
);
},
{
requiredPermissions: ["workspaces.read"],
},
```
Sources: [apps/web/app/api/integrations/route.ts:7-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/integrations/route.ts#L7-L32), [apps/web/lib/auth/workspace.ts:335-363](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L335-L363)
| Error Code | Trigger Condition |
| :--- | :--- |
| `not_found` | Workspace ID or slug does not match any existing project record |
| `invite_expired` | User is not a direct workspace member, but holds an expired project invite |
| `invite_pending` | User is not a direct workspace member, but holds a valid pending project invite |
```typescript
// workspace exists but user is not part of it
if (workspace.users.length === 0) {
const pendingInvites = await prisma.projectInvite.findUnique({
where: {
email_projectId: {
email: session.user.email,
projectId: workspace.id,
},
},
select: {
expires: true,
},
});
// Clear so non-member denials are not attributed to this workspace
// in API logs or Axiom error context.
workspace = undefined;
if (!pendingInvites) {
throw new DubApiError({
code: "not_found",
message: "Workspace not found.",
});
} else if (pendingInvites.expires < new Date()) {
throw new DubApiError({
code: "invite_expired",
message: "Workspace invite expired.",
});
} else {
throw new DubApiError({
code: "invite_pending",
message: "Workspace invite pending.",
});
}
}
```
Sources: [apps/web/lib/auth/workspace.ts:365-399](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L365-L399)
> [!NOTE]
> When a user lacks direct membership but holds a valid pending invitation, the middleware clears the partial workspace reference before throwing the `invite_pending` error to prevent misattributing access denials in Axiom logs.
> Sources: [apps/web/lib/auth/workspace.ts:379-398](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L379-L398)
### Rate Limiting and Telemetry
Rate limits are enforced on every authenticated request based on the caller's plan tier or active session. Analytics and event endpoints evaluate request limits over a 1-second interval (`1 s`), whereas standard API operations evaluate limits over a 1-minute interval (`1 m`). Plan limits are retrieved dynamically using `getRatelimitForPlan`, incorporating trial period boundaries where applicable.
```typescript
// Rate limit checks for API keys
let limit = 0;
let interval: `${number} s` | `${number} m` = isAnalytics
? "1 s"
: "1 m";
const planLimit = getRatelimitForPlan(token.project?.plan || "free", {
trialEndsAt: token.project?.trialEndsAt ?? null,
});
limit = planLimit.limits[isAnalytics ? "analyticsApi" : "api"];
const { success, headers } = await rateLimitRequest({
identifier: `workspace:ratelimit:${hashedKey}`,
requests: limit,
interval,
});
```
Sources: [apps/web/lib/auth/workspace.ts:230-245](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L230-L245), [apps/web/lib/auth/workspace.ts:313-322](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L313-L322)
When rate limits are exhausted, `rateLimitRequest` returns an unsuccessful status, causing the middleware to throw a `rate_limit_exceeded` error. Successful requests propagate rate limit metadata headers back to the client and asynchronously record token last-used timestamps throttled to once per minute.
```typescript
const { success, headers } = await rateLimitRequest({
identifier: `workspace:ratelimit:${hashedKey}`,
requests: limit,
interval,
});
if (headers) {
for (const [key, value] of Object.entries(headers)) {
responseHeaders.set(key, value);
}
}
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
});
}
// Find workspaceId if it's a restricted token
if (isRestrictedToken && token?.projectId) {
workspaceId = token.projectId;
}
waitUntil(
// update last used time for the token (only once every minute)
(async () => {
try {
const { success } = await ratelimit(1, "1 m").limit(
`last-used-${hashedKey}`,
);
if (success) {
const prismaArgs = {
where: {
hashedKey,
},
data: {
lastUsed: new Date(),
},
};
if (isRestrictedToken) {
await prisma.restrictedToken.update(prismaArgs);
} else {
await prisma.token.update(prismaArgs);
}
}
} catch (error) {
console.error(error);
}
})(),
);
```
Sources: [apps/web/lib/auth/workspace.ts:241-293](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L241-L293), [apps/web/lib/auth/workspace.ts:323-332](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/workspace.ts#L323-L332)
## Client Publishable Key Authentication
### Publishable Key Validation and Request Flow
Public client routes authenticate incoming requests using the `withPublishableKey` wrapper function. The middleware extracts the `Authorization` header from the request, verifying that it starts with the `Bearer ` prefix and contains a token beginning with the required `dub_pk_` prefix. If either validation check fails, the handler throws a `DubApiError` with the `bad_request` code and a message indicating an invalid or missing publishable key.
```typescript
const authorizationHeader = requestHeaders.get("Authorization");
if (authorizationHeader) {
if (!authorizationHeader.startsWith("Bearer ")) {
throw new DubApiError({
code: "bad_request",
message: "Invalid or missing publishable key.",
});
}
const publishableKey = authorizationHeader.replace("Bearer ", "");
if (!publishableKey.startsWith("dub_pk_")) {
throw new DubApiError({
code: "bad_request",
message: "Invalid or missing publishable key.",
});
}
```
Sources: [apps/web/lib/auth/publishable-key.ts:45-60](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L45-L60)
Once the key format is verified, the system enforces rate limiting using Upstash with a limit of 600 requests per minute (`1 m`) keyed directly by the publishable key string. Rate limit metadata headers (`Retry-After`, `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset`) are injected into the response headers. If the rate limit is exceeded, the request is rejected with a `rate_limit_exceeded` error code.
```typescript
const { success, limit, reset, remaining } = await ratelimit(
600,
"1 m",
).limit(publishableKey);
responseHeaders.set("Retry-After", reset.toString());
responseHeaders.set("X-RateLimit-Limit", limit.toString());
responseHeaders.set("X-RateLimit-Remaining", remaining.toString());
responseHeaders.set("X-RateLimit-Reset", reset.toString());
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
});
}
```
Sources: [apps/web/lib/auth/publishable-key.ts:62-77](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L62-L77)
After rate limit evaluation, the workspace record is retrieved from the database by querying the `publishableKey` field. If no matching project is found, an `unauthorized` error is thrown. The workspace plan is normalized for business tiers before checking against the `requiredPlan` configuration.
```typescript
workspace = await prisma.project.findUnique({
where: {
publishableKey,
},
});
if (!workspace) {
throw new DubApiError({
code: "unauthorized",
message: "Invalid publishable key.",
});
}
const normalizedWorkspacePlan = [
"business plus",
"business max",
"business extra",
].includes(workspace.plan)
? "business"
: workspace.plan;
if (!requiredPlan.includes(normalizedWorkspacePlan)) {
throw new DubApiError({
code: "forbidden",
message: "Unauthorized: Need higher plan.",
});
}
```
Sources: [apps/web/lib/auth/publishable-key.ts:79-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L79-L105)
> [!NOTE]
> Workspace plans matching `business plus`, `business max`, or `business extra` are automatically normalized to `business` before validating against the endpoint's `requiredPlan` array.
> Sources: [apps/web/lib/auth/publishable-key.ts:92-99](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L92-L99)
### Error Handling and Telemetry Capture
When request handlers execute successfully or encounter errors, the middleware records request logs asynchronously using Vercel's `waitUntil` combined with `captureRequestLog` and Axiom integration.
```typescript
waitUntil(
captureRequestLog({
req: reqForLog,
response,
workspace,
session: undefined,
token: null,
url,
requestHeaders,
startTime,
}),
);
```
Sources: [apps/web/lib/auth/publishable-key.ts:115-126](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L115-L126)
| Error Code | Trigger Condition |
| :--- | :--- |
| `bad_request` | Authorization header is missing, does not start with `Bearer `, or the token does not start with `dub_pk_` |
| `rate_limit_exceeded` | Request volume exceeds 600 requests per minute for the given publishable key |
| `unauthorized` | Authorization header is completely absent, or no workspace matches the provided publishable key |
| `forbidden` | The normalized workspace plan is not included in the endpoint's `requiredPlan` array |
```typescript
const authorizationHeader = requestHeaders.get("Authorization");
if (authorizationHeader) {
if (!authorizationHeader.startsWith("Bearer ")) {
throw new DubApiError({
code: "bad_request",
message: "Invalid or missing publishable key.",
});
}
const publishableKey = authorizationHeader.replace("Bearer ", "");
if (!publishableKey.startsWith("dub_pk_")) {
throw new DubApiError({
code: "bad_request",
message: "Invalid or missing publishable key.",
});
}
const { success, limit, reset, remaining } = await ratelimit(
600,
"1 m",
).limit(publishableKey);
responseHeaders.set("Retry-After", reset.toString());
responseHeaders.set("X-RateLimit-Limit", limit.toString());
responseHeaders.set("X-RateLimit-Remaining", remaining.toString());
responseHeaders.set("X-RateLimit-Reset", reset.toString());
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
});
}
workspace = await prisma.project.findUnique({
where: {
publishableKey,
},
});
if (!workspace) {
throw new DubApiError({
code: "unauthorized",
message: "Invalid publishable key.",
});
}
const normalizedWorkspacePlan = [
"business plus",
"business max",
"business extra",
].includes(workspace.plan)
? "business"
: workspace.plan;
if (!requiredPlan.includes(normalizedWorkspacePlan)) {
throw new DubApiError({
code: "forbidden",
message: "Unauthorized: Need higher plan.",
});
}
```
Sources: [apps/web/lib/auth/publishable-key.ts:45-105](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L45-L105), [apps/web/lib/auth/publishable-key.ts:130-134](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L130-L134)
> [!WARNING]
> If an exception occurs during request processing after a workspace has been successfully resolved, the error response is still captured in the telemetry logs alongside the valid workspace reference.
> Sources: [apps/web/lib/auth/publishable-key.ts:135-154](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/auth/publishable-key.ts#L135-L154)
## Link Operations and Schemas
### Route Definitions and Query Operations
Link routing operations are structured under the `/links` path tree using `ZodOpenApiPathsObject` definitions. The resource map covers individual link mutations, bulk procedures, and counting endpoints alongside standard query retrieval.
```typescript
export const linksPaths: ZodOpenApiPathsObject = {
"/links": {
post: createLink,
get: getLinks,
},
"/links/count": {
get: getLinksCount,
},
"/links/info": {
get: getLinkInfo,
},
"/links/{linkId}": {
patch: updateLink,
delete: deleteLink,
},
"/links/bulk": {
post: bulkCreateLinks,
patch: bulkUpdateLinks,
delete: bulkDeleteLinks,
},
"/links/upsert": {
put: upsertLink,
},
};
```
Sources: [apps/web/lib/openapi/links/index.ts:13-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/index.ts#L13-L36)
The `getLinks` operation defines an OpenAPI object with `operationId` set to `getLinks`, a Speakeasy name override of `list`, and offset-limit pagination mapping parameters `page` and `pageSize` to input parameters while outputting results directly from root. It validates incoming request query parameters using `getLinksQuerySchemaBase` and responds with a 200 array of `LinkSchema` items.
```typescript
export const getLinks: ZodOpenApiOperationObject = {
operationId: "getLinks",
"x-speakeasy-name-override": "list",
"x-speakeasy-pagination": {
type: "offsetLimit",
inputs: [
{
name: "page",
in: "parameters",
type: "page",
},
{
name: "pageSize",
in: "parameters",
type: "limit",
},
],
outputs: {
results: "$",
},
},
summary: "List all links",
description:
"Retrieve a paginated list of links for the authenticated workspace.",
requestParams: {
query: getLinksQuerySchemaBase,
},
responses: {
"200": {
description: "A list of links",
content: {
"application/json": {
schema: z.array(LinkSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Links"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/links/get-links.ts:6-46](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links.ts#L6-L46)
Metadata retrieval for single links is handled by `getLinkInfo`, exposing the `getLinkInfo` operation ID and `get` name override. It accepts query parameters validated via `getLinkInfoQuerySchema` and returns a single `LinkSchema` object under a 200 status code response.
```typescript
export const getLinkInfo: ZodOpenApiOperationObject = {
operationId: "getLinkInfo",
"x-speakeasy-name-override": "get",
summary: "Retrieve a link",
description: "Retrieve the info for a link.",
requestParams: {
query: getLinkInfoQuerySchema,
},
responses: {
"200": {
description: "The retrieved link",
content: {
"application/json": {
schema: LinkSchema,
},
},
},
...openApiErrorResponses,
},
tags: ["Links"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/links/get-link-info.ts:5-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-link-info.ts#L5-L26)
Count aggregation is handled through the `getLinksCount` operation defined at `/links/count`. It utilizes `getLinksCountQuerySchema` for query validation and returns a numerical Zod schema carrying metadata describing the matching record count.
```typescript
export const getLinksCount: ZodOpenApiOperationObject = {
operationId: "getLinksCount",
"x-speakeasy-name-override": "count",
summary: "Retrieve links count",
description: "Retrieve the number of links for the authenticated workspace.",
requestParams: {
query: getLinksCountQuerySchema,
},
responses: {
"200": {
description: "A list of links",
content: {
"application/json": {
schema: z.number().meta({
description: "The number of links matching the query.",
}),
},
},
},
...openApiErrorResponses,
},
tags: ["Links"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/links/get-links-count.ts:6-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links-count.ts#L6-L29)
| Operation ID | Method & Path | Speakeasy Override | Request Query Schema | Response Schema |
| :--- | :--- | :--- | :--- | :--- |
| `getLinks` | `GET /links` | `list` | `getLinksQuerySchemaBase` | `z.array(LinkSchema)` |
| `getLinkInfo` | `GET /links/info` | `get` | `getLinkInfoQuerySchema` | `LinkSchema` |
| `getLinksCount` | `GET /links/count` | `count` | `getLinksCountQuerySchema` | `z.number()` |
```typescript
"/links/count": {
get: getLinksCount,
},
"/links/info": {
get: getLinkInfo,
},
```
Sources: [apps/web/lib/openapi/links/index.ts:18-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/index.ts#L18-L23), [apps/web/lib/openapi/links/get-links.ts:30-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links.ts#L30-L41), [apps/web/lib/openapi/links/get-link-info.ts:10-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-link-info.ts#L10-L21), [apps/web/lib/openapi/links/get-links-count.ts:11-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links-count.ts#L11-L24)
> [!NOTE]
> All link query operations require token security credentials and inherit standard OpenAPI error responses via `openApiErrorResponses`.
> Sources: [apps/web/lib/openapi/links/get-links.ts:41-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links.ts#L41-L45), [apps/web/lib/openapi/links/get-link-info.ts:22-25](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-link-info.ts#L22-L25), [apps/web/lib/openapi/links/get-links-count.ts:25-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/links/get-links-count.ts#L25-L28)
## Analytics and Event Telemetry
### Analytics Endpoint and Response Schema
The analytics API is mounted under the `/analytics` route path and handles retrieval for links, domains, or workspaces based on query configuration. The `retrieveAnalytics` operation defines its query parameters using `analyticsQuerySchema` and uses a Speakeasy name override of `retrieve`.
```typescript
const retrieveAnalytics: ZodOpenApiOperationObject = {
operationId: "retrieveAnalytics",
"x-speakeasy-name-override": "retrieve",
summary:
"Retrieve analytics for a link, a domain, or the authenticated workspace.",
description:
"Retrieve analytics for a link, a domain, or the authenticated workspace. The response type depends on the `event` and `type` query parameters.",
requestParams: {
query: analyticsQuerySchema,
},
```
Sources: [apps/web/lib/openapi/analytics/index.ts:7-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/analytics/index.ts#L7-L16)
The response schema for `retrieveAnalytics` accepts a union of types depending on the requested dimension, validating outputs against specific metric definitions. Success responses return application JSON formatted as either an analytics count or an array of dimension objects.
| OpenAPI ID | Zod Schema Binding | Target Metric Dimension |
| :--- | :--- | :--- |
| `AnalyticsCount` | `analyticsResponse.count` | Aggregate count metrics |
| `AnalyticsTimeseries` | `analyticsResponse.timeseries` | Timeseries datapoints |
| `AnalyticsContinents` | `analyticsResponse.continents` | Continents breakdown |
| `AnalyticsCountries` | `analyticsResponse.countries` | Countries breakdown |
| `AnalyticsRegions` | `analyticsResponse.regions` | Regions breakdown |
| `AnalyticsCities` | `analyticsResponse.cities` | Cities breakdown |
| `AnalyticsDevices` | `analyticsResponse.devices` | Device types |
| `AnalyticsBrowsers` | `analyticsResponse.browsers` | Browsers breakdown |
| `AnalyticsOS` | `analyticsResponse.os` | Operating systems |
| `AnalyticsTriggers` | `analyticsResponse.triggers` | Click triggers |
| `AnalyticsEventNames` | `analyticsResponse.event_names` | Event names |
| `AnalyticsReferers` | `analyticsResponse.referers` | Referers breakdown |
| `AnalyticsRefererUrls` | `analyticsResponse.referer_urls` | Referer URLs |
| `AnalyticsTopLinks` | `analyticsResponse.top_links` | Top performing links |
| `AnalyticsTopUrls` | `analyticsResponse.top_urls` | Top target URLs |
```typescript
"200": {
description: "Analytics data",
content: {
"application/json": {
schema: z.union([
analyticsResponse.count.meta({
id: "AnalyticsCount",
}),
z.array(
analyticsResponse.timeseries.meta({
id: "AnalyticsTimeseries",
}),
),
z.array(
analyticsResponse.continents.meta({
id: "AnalyticsContinents",
}),
),
z.array(
analyticsResponse.countries.meta({
id: "AnalyticsCountries",
}),
),
z.array(
analyticsResponse.regions.meta({
id: "AnalyticsRegions",
}),
),
z.array(
analyticsResponse.cities.meta({
id: "AnalyticsCities",
}),
),
z.array(
analyticsResponse.devices.meta({
id: "AnalyticsDevices",
}),
),
z.array(
analyticsResponse.browsers.meta({
id: "AnalyticsBrowsers",
}),
),
z.array(
analyticsResponse.os.meta({
id: "AnalyticsOS",
}),
),
z.array(
analyticsResponse.triggers.meta({
id: "AnalyticsTriggers",
}),
),
z.array(
analyticsResponse.event_names.meta({
id: "AnalyticsEventNames",
}),
),
z.array(
analyticsResponse.referers.meta({
id: "AnalyticsReferers",
}),
),
z.array(
analyticsResponse.referer_urls.meta({
id: "AnalyticsRefererUrls",
}),
),
z.array(
analyticsResponse.top_links.meta({
id: "AnalyticsTopLinks",
}),
),
z.array(
analyticsResponse.top_urls.meta({
id: "AnalyticsTopUrls",
}),
),
]),
},
```
Sources: [apps/web/lib/openapi/analytics/index.ts:18-97](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/analytics/index.ts#L18-L97)
> [!NOTE]
> The `retrieveAnalytics` operation is tagged under `Analytics`, requires bearer token security credentials via `[{ token: [] }]`, and inherits standard OpenAPI error responses.
> Sources: [apps/web/lib/openapi/analytics/index.ts:100-104](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/analytics/index.ts#L100-L104)
### Raw Event Streaming and Schemas
Event telemetry retrieval is exposed via the `/events` endpoint through the `listEvents` operation. It accepts paginated query parameters defined by `eventsQuerySchema` and returns a list of telemetry events for the authenticated workspace.
```typescript
export const listEvents: ZodOpenApiOperationObject = {
operationId: "listEvents",
"x-speakeasy-name-override": "list",
summary: "List all events",
description:
"Retrieve a paginated list of events for the authenticated workspace.",
requestParams: {
query: eventsQuerySchema,
},
```
Sources: [apps/web/lib/openapi/events/index.ts:9-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/events/index.ts#L9-L17)
The response content for `listEvents` validates items against a discriminated union keyed on the `event` property. This union supports click, lead, and sale event response schemas.
```typescript
responses: {
"200": {
description: "A list of events",
content: {
"application/json": {
schema: z.array(
z.discriminatedUnion("event", [
clickEventResponseSchema,
leadEventResponseSchema,
saleEventResponseSchema,
]),
),
},
},
},
```
Sources: [apps/web/lib/openapi/events/index.ts:18-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/events/index.ts#L18-L32)
| Schema Constant | Response Type | Discriminator Value |
| :--- | :--- | :--- |
| `clickEventResponseSchema` | Click telemetry event | `click` |
| `leadEventResponseSchema` | Lead conversion event | `lead` |
| `saleEventResponseSchema` | Sale conversion event | `sale` |
```typescript
schema: z.array(
z.discriminatedUnion("event", [
clickEventResponseSchema,
leadEventResponseSchema,
saleEventResponseSchema,
]),
```
Sources: [apps/web/lib/openapi/events/index.ts:23-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/events/index.ts#L23-L28)
> [!WARNING]
> Omitting the discriminator `event` parameter during event payload consumption will cause Zod validation failures against the discriminated union schema.
> Sources: [apps/web/lib/openapi/events/index.ts:23-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/events/index.ts#L23-L28)
## Domain and Organization Resource Management
### Workspace Domain and Entity Query Operations
The OpenAPI specification defines resource endpoints to query and manage organization-level assets including domains, tags, and folders. The `listDomains` operation is exposed under the `Domains` tag with operation ID `listDomains` and utilizes an offset-limit pagination schema.
```typescript
export const listDomains: ZodOpenApiOperationObject = {
operationId: "listDomains",
"x-speakeasy-name-override": "list",
"x-speakeasy-pagination": {
type: "offsetLimit",
inputs: [
{
name: "page",
in: "parameters",
type: "page",
},
{
name: "pageSize",
in: "parameters",
type: "limit",
},
],
outputs: {
results: "$",
},
},
```
Sources: [apps/web/lib/openapi/domains/list-domains.ts:6-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/domains/list-domains.ts#L6-L26)
Query inputs accept `page` and `pageSize` parameters mapped to parameters input type, returning an array of `DomainSchema` objects with standard error responses and token security requirements.
```typescript
summary: "List all domains",
description:
"Retrieve a paginated list of domains for the authenticated workspace.",
requestParams: {
query: getDomainsQuerySchema,
},
responses: {
"200": {
description: "The domains were retrieved.",
content: {
"application/json": {
schema: z.array(DomainSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Domains"],
security: [{ token: [] }],
```
Sources: [apps/web/lib/openapi/domains/list-domains.ts:27-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/domains/list-domains.ts#L27-L45)
> [!NOTE]
> The Speakeasy configuration for `listDomains` defines pagination outputs using the root path output `$`.
> Sources: [apps/web/lib/openapi/domains/list-domains.ts:23-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/domains/list-domains.ts#L23-L26)
### Tags and Folders Management Schemas
Organization categorization assets are handled through dedicated resource definitions. The `getTags` operation retrieves paginated tags for the authenticated workspace using `getTagsQuerySchema` and validates response items against `LinkTagSchema`.
```typescript
export const getTags: ZodOpenApiOperationObject = {
operationId: "getTags",
"x-speakeasy-name-override": "list",
summary: "List all tags",
description:
"Retrieve a paginated list of tags for the authenticated workspace.",
requestParams: {
query: getTagsQuerySchema,
},
responses: {
"200": {
description: "A list of tags",
content: {
"application/json": {
schema: z.array(LinkTagSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Tags"],
security: [{ token: [] }],
```
Sources: [apps/web/lib/openapi/tags/get-tags.ts:6-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/tags/get-tags.ts#L6-L27)
Tag mutation paths are grouped under `/tags` and `/tags/{id}` routes, combining creation, listing, updating, and deletion behaviors.
```typescript
export const tagsPaths: ZodOpenApiPathsObject = {
"/tags": {
post: createTag,
get: getTags,
},
"/tags/{id}": {
patch: updateTag,
delete: deleteTag,
},
};
```
Sources: [apps/web/lib/openapi/tags/index.ts:8-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/tags/index.ts#L8-L17)
Similarly, folder retrieval is exposed via the `listFolders` operation under the `Folders` tag, validating query parameters with `listFoldersQuerySchema` and returning arrays matching `FolderSchema`.
```typescript
export const listFolders: ZodOpenApiOperationObject = {
operationId: "listFolders",
"x-speakeasy-name-override": "list",
summary: "List all folders",
description:
"Retrieve a paginated list of folders for the authenticated workspace.",
requestParams: {
query: listFoldersQuerySchema,
},
responses: {
"200": {
description: "A list of folders",
content: {
"application/json": {
schema: z.array(FolderSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Folders"],
security: [{ token: [] }],
```
Sources: [apps/web/lib/openapi/folders/list-folders.ts:9-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/folders/list-folders.ts#L9-L30)
| Operation ID | HTTP Method & Path | Query Schema Binding | Response Schema | Tag |
| :--- | :--- | :--- | :--- | :--- |
| `listDomains` | `GET /domains` | `getDomainsQuerySchema` | `z.array(DomainSchema)` | `Domains` |
| `getTags` | `GET /tags` | `getTagsQuerySchema` | `z.array(LinkTagSchema)` | `Tags` |
| `listFolders` | `GET /folders` | `listFoldersQuerySchema` | `z.array(FolderSchema)` | `Folders` |
```typescript
requestParams: {
query: getDomainsQuerySchema,
},
responses: {
"200": {
description: "The domains were retrieved.",
content: {
"application/json": {
schema: z.array(DomainSchema),
},
},
},
…
requestParams: {
query: getTagsQuerySchema,
},
responses: {
"200": {
description: "A list of tags",
content: {
"application/json": {
schema: z.array(LinkTagSchema),
},
…
requestParams: {
query: listFoldersQuerySchema,
},
responses: {
"200": {
description: "A list of folders",
content: {
"application/json": {
schema: z.array(FolderSchema),
},
```
Sources: [apps/web/lib/openapi/domains/list-domains.ts:30-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/domains/list-domains.ts#L30-L41), [apps/web/lib/openapi/tags/get-tags.ts:12-21](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/tags/get-tags.ts#L12-L21), [apps/web/lib/openapi/folders/list-folders.ts:15-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/folders/list-folders.ts#L15-L24)
> [!WARNING]
> All resource listing endpoints require bearer token workspace authorization (`security: [{ token: [] }]`) and will return OpenAPI error responses if credentials are omitted or invalid.
> Sources: [apps/web/lib/openapi/domains/list-domains.ts:42-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/domains/list-domains.ts#L42-L45), [apps/web/lib/openapi/tags/get-tags.ts:24-27](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/tags/get-tags.ts#L24-L27), [apps/web/lib/openapi/folders/list-folders.ts:27-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/folders/list-folders.ts#L27-L30)
## Partner and Commerce Resource Endpoints
### Customer Entity Endpoints
Customer management operations are exposed via paths under `/customers` and `/customers/{id}`. The `getCustomers` operation retrieves a paginated list of customers for the authenticated workspace, utilizing cursor pagination via Speakeasy annotations with the `startingAfter` cursor input parameter and returning an array of `CustomerEnrichedSchema` objects.
```typescript
export const getCustomers: ZodOpenApiOperationObject = {
operationId: "getCustomers",
"x-speakeasy-name-override": "list",
"x-speakeasy-pagination": {
type: "cursor",
inputs: [
{
name: "startingAfter",
in: "parameters",
type: "cursor",
},
],
outputs: {
nextCursor: "$[-1].id",
},
},
summary: "List all customers",
description:
"Retrieve a paginated list of customers for the authenticated workspace.",
requestParams: {
query: getCustomersQuerySchema,
},
responses: {
"200": {
description: "The list of customers.",
content: {
"application/json": {
schema: z.array(CustomerEnrichedSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Customers"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/customers/get-customers.ts:9-44](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customers.ts#L9-L44)
Individual customer retrieval is handled by `getCustomer`, which maps path parameters to `CustomerEnrichedSchema.pick({ id: true })` and query parameters to expanded fields selection. To retrieve a customer by an external ID, callers must prefix the identifier value with `ext_`.
```typescript
export const getCustomer: ZodOpenApiOperationObject = {
operationId: "getCustomer",
"x-speakeasy-name-override": "get",
summary: "Retrieve a customer",
description:
"Retrieve a customer by ID for the authenticated workspace. To retrieve a customer by external ID, prefix the ID with `ext_`.",
requestParams: {
path: CustomerEnrichedSchema.pick({ id: true }),
query: getCustomersQuerySchema.pick({ includeExpandedFields: true }),
},
responses: {
"200": {
description: "The customer object.",
content: {
"application/json": {
schema: CustomerEnrichedSchema,
},
},
},
...openApiErrorResponses,
},
tags: ["Customers"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/customers/get-customer.ts:8-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customer.ts#L8-L31)
> [!NOTE]
> The `getCustomer` operation overrides Speakeasy's method naming to `get` while `getCustomers` maps to `list`, supporting distinct SDK client generation names across the `Customers` tag group.
> Sources: [apps/web/lib/openapi/customers/get-customers.ts:10-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customers.ts#L10-L11), [apps/web/lib/openapi/customers/get-customer.ts:9-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customer.ts#L9-L10)
### Discount Code Schemas and Paths
Discount codes are defined under `/discount-codes` and `/discount-codes/{idOrCode}` endpoints. The `listDiscountCodes` operation permits querying discount codes within a program or filtered by specific attributes using `getDiscountCodesQuerySchema`, returning an array matching `DiscountCodeSchema`.
```typescript
export const listDiscountCodes: ZodOpenApiOperationObject = {
operationId: "listDiscountCodes",
"x-speakeasy-name-override": "list",
summary: "List discount codes",
description:
"Retrieve a paginated list of discount codes in a program or filtered by partner, discount, or code.",
requestParams: {
query: getDiscountCodesQuerySchema,
},
responses: {
"200": {
description: "The list of discount codes.",
content: {
"application/json": {
schema: z.array(DiscountCodeSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Discount Codes"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/discount-codes/list-discount-codes.ts:9-31](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/discount-codes/list-discount-codes.ts#L9-L31)
The discount code router aggregates listing, creation, and deletion routes into a single `discountCodesPaths` object configuration.
```typescript
export const discountCodesPaths: ZodOpenApiPathsObject = {
"/discount-codes": {
get: listDiscountCodes,
post: createDiscountCode,
},
"/discount-codes/{idOrCode}": {
delete: deleteDiscountCode,
},
};
```
Sources: [apps/web/lib/openapi/discount-codes/index.ts:6-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/discount-codes/index.ts#L6-L14)
| Operation ID | HTTP Method & Path | Primary Schema | Tag |
| :--- | :--- | :--- | :--- |
| `getCustomers` | `GET /customers` | `CustomerEnrichedSchema` | `Customers` |
| `getCustomer` | `GET /customers/{id}` | `CustomerEnrichedSchema` | `Customers` |
| `listDiscountCodes` | `GET /discount-codes` | `DiscountCodeSchema` | `Discount Codes` |
| `retrievePartnerLinks` | `GET /partners/links` | `ProgramPartnerLinkSchema` | `Partners` |
```typescript
summary: "List all customers",
description:
"Retrieve a paginated list of customers for the authenticated workspace.",
requestParams: {
query: getCustomersQuerySchema,
},
responses: {
"200": {
description: "The list of customers.",
content: {
"application/json": {
schema: z.array(CustomerEnrichedSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Customers"],
…
summary: "Retrieve a customer",
description:
"Retrieve a customer by ID for the authenticated workspace. To retrieve a customer by external ID, prefix the ID with `ext_`.",
requestParams: {
path: CustomerEnrichedSchema.pick({ id: true }),
query: getCustomersQuerySchema.pick({ includeExpandedFields: true }),
},
responses: {
"200": {
description: "The customer object.",
content: {
"application/json": {
schema: CustomerEnrichedSchema,
},
},
},
...openApiErrorResponses,
},
tags: ["Customers"],
…
summary: "List discount codes",
description:
"Retrieve a paginated list of discount codes in a program or filtered by partner, discount, or code.",
requestParams: {
query: getDiscountCodesQuerySchema,
},
responses: {
"200": {
description: "The list of discount codes.",
content: {
"application/json": {
schema: z.array(DiscountCodeSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Discount Codes"],
…
summary: "Retrieve a partner's links.",
description: "Retrieve a partner's links by their partner ID or tenant ID.",
requestParams: {
query: retrievePartnerLinksSchema,
},
responses: {
"200": {
description: "The retrieved partner links.",
content: {
"application/json": {
schema: z.array(ProgramPartnerLinkSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Partners"],
```
Sources: [apps/web/lib/openapi/customers/get-customers.ts:25-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customers.ts#L25-L42), [apps/web/lib/openapi/customers/get-customer.ts:11-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/customers/get-customer.ts#L11-L29), [apps/web/lib/openapi/discount-codes/list-discount-codes.ts:12-29](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/discount-codes/list-discount-codes.ts#L12-L29), [apps/web/lib/openapi/partners/retrieve-partner-links.ts:10-26](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/partners/retrieve-partner-links.ts#L10-L26)
### Partner Program Telemetry and Analytics
Partner program telemetry encompasses partner link retrieval, analytics, and program applications. The `retrievePartnerLinks` operation queries partner links by partner ID or tenant ID using `retrievePartnerLinksSchema` and returns a list of `ProgramPartnerLinkSchema` items.
```typescript
export const retrievePartnerLinks: ZodOpenApiOperationObject = {
operationId: "retrievePartnerLinks",
"x-speakeasy-name-override": "retrieveLinks",
summary: "Retrieve a partner's links.",
description: "Retrieve a partner's links by their partner ID or tenant ID.",
requestParams: {
query: retrievePartnerLinksSchema,
},
responses: {
"200": {
description: "The retrieved partner links.",
content: {
"application/json": {
schema: z.array(ProgramPartnerLinkSchema),
},
},
},
...openApiErrorResponses,
},
tags: ["Partners"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/partners/retrieve-partner-links.ts:7-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/partners/retrieve-partner-links.ts#L7-L28)
Analytics for partners within a program are retrieved via `retrievePartnerAnalytics`, which validates query parameters against `partnerAnalyticsQuerySchema`. The response schema varies via a Zod union supporting count metadata, timeseries arrays, and top-links metrics based on the `groupBy` query parameter.
```typescript
export const retrievePartnerAnalytics: ZodOpenApiOperationObject = {
operationId: "retrievePartnerAnalytics",
"x-speakeasy-name-override": "analytics",
summary: "Retrieve analytics for a partner",
description:
"Retrieve analytics for a partner within a program. The response type vary based on the `groupBy` query parameter.",
requestParams: {
query: partnerAnalyticsQuerySchema,
},
responses: {
"200": {
description: "Partner analytics data",
content: {
"application/json": {
schema: z.union([
partnerAnalyticsResponseSchema.count.meta({
id: "PartnerAnalyticsCount",
}),
z.array(
partnerAnalyticsResponseSchema.timeseries.meta({
id: "PartnerAnalyticsTimeseries",
}),
),
z.array(
partnerAnalyticsResponseSchema.top_links.meta({
id: "PartnerAnalyticsTopLinks",
}),
),
]),
},
},
},
...openApiErrorResponses,
},
tags: ["Partners"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/partners/retrieve-analytics.ts:9-45](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/partners/retrieve-analytics.ts#L9-L45)
Program applications route handles listing applications alongside approval and rejection endpoints under `/program-applications`, `/program-applications/approve`, and `/program-applications/reject`.
```typescript
export const programApplicationsPaths: ZodOpenApiPathsObject = {
"/program-applications": {
get: listProgramApplications,
},
"/program-applications/approve": {
post: approveProgramApplication,
},
"/program-applications/reject": {
post: rejectProgramApplication,
},
};
```
Sources: [apps/web/lib/openapi/program-applications/index.ts:6-16](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/program-applications/index.ts#L6-L16)
> [!WARNING]
> Partner program summary route handlers are protected with `withPartnerProfile` middleware to ensure authenticated partner context is injected before marketplace telemetry fetchers execute.
> Sources: [apps/web/app/(ee)/api/network/programs/summary/route.ts:1-10](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/network/programs/summary/route.ts#L1-L10)
## Related
- [OAuth Apps](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/integrations-subsystem/oauth-apps)
- [Link Dispatch](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/link-attribution/link-dispatch)
---
## Technical docs: POST Add program to marketplace
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/createadminprogram
## Request Body
Program slug
## Responses
## Try It
---
## Technical docs: PATCH Reorder marketplace programs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/updatemarketplacerankings
## Request Body
Ranking updates
## Responses
## Try It
---
## Technical docs: Embeddable Referrals
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/embeddable-referrals
Relevant source files
The following files were used as context for generating this wiki page:
- [apps/web/app/ee/app.dub.co/embed/referrals/token.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/token.tsx)
- [apps/web/app/ee/api/embed/referrals/token/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/token/route.ts)
- [apps/web/app/api/tokens/embed/referrals/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/tokens/embed/referrals/route.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx)
- [apps/web/app/api/user/referrals-token/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/user/referrals-token/route.ts)
- [apps/web/lib/embed/referrals/auth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/auth.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx)
- [apps/web/app/ee/app.dub.co/embed/referrals/quickstart.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx)
- [apps/web/lib/openapi/embed-tokens/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/embed-tokens/index.ts)
- [apps/web/app/ee/api/embed/referrals/links/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/links/route.ts)
- [apps/web/app/app.dub.co/dashboard/account/settings/referrals/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page-client.tsx)
- [apps/web/app/ee/api/embed/referrals/events/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/events/route.ts)
- [apps/web/app/ee/api/embed/referrals/earnings/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/earnings/route.ts)
- [apps/web/lib/embed/referrals/token-class.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/token-class.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts)
- [apps/web/app/ee/api/embed/referrals/earnings/timeseries/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/earnings/timeseries/route.ts)
- [apps/web/app/ee/api/embed/referrals/bounties/bountyId/submissions/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/bounties/%5BbountyId%5D/submissions/route.ts)
- [apps/web/app/ee/api/embed/referrals/analytics/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts)
- [apps/web/lib/openapi/embed-tokens/create-referrals-embed-token.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/embed-tokens/create-referrals-embed-token.ts)
- [apps/web/app/ee/api/embed/referrals/bounties/bountyId/upload/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/bounties/%5BbountyId%5D/upload/route.ts)
- [packages/embeds/react/src/embed.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/embeds/react/src/embed.tsx)
- [apps/web/lib/middleware/embed.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/embed.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/leaderboard.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx)
- [apps/web/app/ee/partners.dub.co/dashboard/programs/programSlug/enrolled/referrals/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/%5BprogramSlug%5D/(enrolled)/referrals/page.tsx)
- [apps/web/app/ee/app.dub.co/embed/referrals/links.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/links.tsx)
- [apps/web/app/ee/app.dub.co/embed/use-embed-token.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/use-embed-token.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/activity.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/activity.tsx)
- [packages/embeds/react/src/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/embeds/react/src/index.ts)
- [apps/web/app/ee/app.dub.co/embed/referrals/earnings.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings.tsx)
- [apps/web/app/app.dub.co/dashboard/account/settings/referrals/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page.tsx)
## Overview
Embeddable Referrals provide a secure mechanism for integrating white-labeled partner and affiliate program dashboards directly into external web applications via iframe wrappers and React components. By minting cryptographically bound tokens backed by Redis storage, platforms can authorize external tenants to track link performance, view earnings, manage referral links, and submit bounties without exposing internal credentials.
> [!NOTE]
> Embedding requires a valid public embed token passed through the authorization header or query parameters to authenticate embedded partner contexts against backend API routes.
Sources: [apps/web/lib/embed/referrals/token-class.ts:13-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/token-class.ts#L13-L33), [packages/embeds/react/src/embed.tsx:8-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/embeds/react/src/embed.tsx#L8-L12), [apps/web/lib/embed/referrals/auth.ts:33-128](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/auth.ts#L33-L128)
## Embed Token Minting
### Token Generation and Storage
The token minting process is coordinated through the `ReferralsEmbedToken` class, which uses Upstash Redis storage to persist session properties mapped to a unique public identifier. When `create()` is invoked with a `programId` and `partnerId`, a secure identifier is generated using `createId()` prefixed with `EMBED_PUBLIC_TOKEN_PREFIX`. This token is stored in Redis containing the JSON-serialized payload along with an expiration configured by `EMBED_PUBLIC_TOKEN_EXPIRY`, enforcing non-collision requirements via the `nx` option.
```typescript
class ReferralsEmbedToken {
async create(props: ReferralsEmbedTokenProps) {
const publicToken = createId({
prefix: EMBED_PUBLIC_TOKEN_PREFIX,
});
await redis.set(publicToken, JSON.stringify(props), {
ex: EMBED_PUBLIC_TOKEN_EXPIRY,
nx: true,
});
return {
publicToken,
expires: new Date(Date.now() + EMBED_PUBLIC_TOKEN_EXPIRY * 1000),
};
}
async get(token: string) {
return await redis.get(token);
}
}
```
Sources: [apps/web/lib/embed/referrals/token-class.ts:13-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/token-class.ts#L13-L33)
> [!WARNING]
> Stored embed tokens rely entirely on `EMBED_PUBLIC_TOKEN_EXPIRY` for time-to-live management in Redis. If the Redis key expires, subsequent token resolution calls will fail to retrieve the underlying `programId` and `partnerId` mapping.
### Server Endpoints and Upsert Workflows
Two primary API routes handle token generation depending on the execution context. The workspace-level endpoint at `/tokens/embed/referrals` validates requests using `withWorkspace` requiring `links.write` permissions and an `advanced` or `enterprise` plan. It attempts to locate an existing `ProgramEnrollment` by `partnerId` or `tenantId`. If no enrollment exists but partner properties are provided, it resolves or creates the partner record and enrolls them into the default program before minting the token.
```typescript
// POST /api/tokens/embed/referrals - create a new embed token for the given partner/tenant
export const POST = withWorkspace(
async ({ workspace, req, session }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
const {
partnerId,
tenantId,
partner: partnerProps,
} = createReferralsEmbedTokenSchema.parse(await parseRequestBody(req));
const finalTenantId =
tenantId || partnerProps?.tenantId || partnerProps?.linkProps?.tenantId;
let programEnrollment: Pick | null = null;
// find the program enrollment for the given partnerId or tenantId
if (partnerId || finalTenantId) {
programEnrollment = await prisma.programEnrollment.findUnique({
where: partnerId
? { partnerId_programId: { partnerId, programId } }
: { tenantId_programId: { tenantId: finalTenantId!, programId } },
select: {
partnerId: true,
},
});
}
// if there is no programEnrollment associated with the partnerId or tenantId, and partnerProps are provided
// check if the partner exists based on the email – if not, create them, if yes, enroll them
if (!programEnrollment && partnerProps) {
const program = await prisma.program.findUniqueOrThrow({
where: {
id: programId,
},
select: {
id: true,
workspaceId: true,
defaultFolderId: true,
domain: true,
url: true,
defaultGroupId: true,
},
});
const partner = await prisma.partner.findUnique({
where: {
email: partnerProps.email,
},
include: {
programs: {
where: {
programId,
},
},
},
});
// partner does not exist, we need to create them OR
// partner exists but is not enrolled in the program, we need to enroll them
if (!partner || partner.programs.length === 0) {
const { linkProps: link, ...partner } = partnerProps;
const enrolledPartner = await createAndEnrollPartner({
workspace,
program,
partner: {
...partner,
...(finalTenantId && { tenantId: finalTenantId }),
},
link: {
...link,
...(finalTenantId && { tenantId: finalTenantId }),
},
userId: session.user.id,
});
programEnrollment = {
partnerId: enrolledPartner.id,
};
```
Sources: [apps/web/app/api/tokens/embed/referrals/route.ts:15-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/tokens/embed/referrals/route.ts#L15-L122)
The user-level route at `/api/user/referrals-token` evaluates session state, checking paid workspace allocations, reputation criteria such as earned commissions and ban status via `partnerHasEarnedCommissions` and `partnerIsNotBanned`, and account age thresholds before issuing a public token for the user tenant.
```typescript
export const GET = withSession(async ({ session }) => {
const user = await prisma.user.findUniqueOrThrow({
where: {
id: session.user.id,
},
include: {
partners: {
include: {
partner: {
include: {
programs: true,
},
},
},
},
projects: {
where: {
project: {
plan: {
not: "free",
},
},
},
},
},
});
const paidWorkspaces = user.projects.map((project) => project);
// for free users, need to do some extra checks
if (paidWorkspaces.length === 0) {
// for partners with free workspaces, they are only eligible if they have a good reputation
const programEnrollments = user.partners[0]
? user.partners[0].partner.programs
: [];
if (
programEnrollments.length > 0 &&
!(
partnerHasEarnedCommissions(
programEnrollments as ProgramEnrollmentsForDiscoverability,
) && partnerIsNotBanned(programEnrollments)
)
) {
return NextResponse.json({ publicToken: null });
}
// for regular free users, don't allow them to join the referral program if they've just joined (within the last 30 days)
if (user.createdAt > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)) {
return NextResponse.json({ publicToken: null });
}
}
const { publicToken } = await dub.embedTokens.referrals({
tenantId: session.user.id,
partner: {
name: session.user.name || session.user.email,
email: session.user.email,
image: session.user.image || null,
tenantId: session.user.id,
groupId: "grp_1K2QJWRQ917XX2YR5VHQ1RRC5", // User Referrals group
},
});
return NextResponse.json({ publicToken });
});
```
Sources: [apps/web/app/api/user/referrals-token/route.ts:11-74](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/user/referrals-token/route.ts#L11-L74)
### OpenAPI Specification and Operations
The public API specification for embed token creation is defined using `zod-openapi`. The route registers under `/tokens/embed/referrals` with the `createReferralsEmbedToken` operation object, specifying request body validation schemas and response structures.
| Operation Property | Value / Schema | Description |
| :--- | :--- | :--- |
| `operationId` | `createReferralsEmbedToken` | Unique identifier for SDK generation |
| `x-speakeasy-name-override` | `referrals` | Speakeasy client naming override |
| `summary` | "Create a referrals embed token" | Short description of endpoint purpose |
| `requestBody` | `createReferralsEmbedTokenSchema` | JSON schema validating partner and tenant payload |
| `responses` | `201`, `...openApiErrorResponses` | Returns `ReferralsEmbedTokenSchema` on success |
| `tags` | `["Embed Tokens"]` | OpenAPI categorization tag |
| `security` | `[{ token: [] }]` | API key security requirement |
```typescript
export const createReferralsEmbedToken: ZodOpenApiOperationObject = {
operationId: "createReferralsEmbedToken",
"x-speakeasy-name-override": "referrals",
summary: "Create a referrals embed token",
description:
"Create a referrals embed token for the given partner/tenant. The endpoint first attempts to locate an existing enrollment using the provided tenantId. If no enrollment is found, it resolves the partner by email and creates a new enrollment as needed. This results in an upsert-style flow that guarantees a valid enrollment and returns a usable embed token.",
requestBody: {
content: {
"application/json": {
schema: createReferralsEmbedTokenSchema,
},
},
},
responses: {
"201": {
description: "The created public embed token.",
content: {
"application/json": {
schema: ReferralsEmbedTokenSchema,
},
},
},
...openApiErrorResponses,
},
tags: ["Embed Tokens"],
security: [{ token: [] }],
};
```
Sources: [apps/web/lib/openapi/embed-tokens/create-referrals-embed-token.ts:8-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/embed-tokens/create-referrals-embed-token.ts#L8-L34), [apps/web/lib/openapi/embed-tokens/index.ts:1-7](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/openapi/embed-tokens/index.ts#L1-L7)
## Token Verification Middleware
### Authentication Wrappers and Route Handling
```typescript
export const withReferralsEmbedToken = (
handler: WithReferralsEmbedTokenHandler,
) => {
return withAxiom(
async (
req,
{ params: initialParams }: { params: Promise> },
) => {
const params = (await initialParams) || {};
const requestHeaders = await headers();
let responseHeaders = new Headers();
try {
const rateLimit = 60;
const searchParams = getSearchParams(req.url);
const embedToken = requestHeaders.get("Authorization")?.split(" ")[1];
if (!embedToken) {
throw new DubApiError({
code: "unauthorized",
message: "Embed public token not found in the request.",
});
}
const { programId, partnerId } =
(await referralsEmbedToken.get(embedToken)) ?? {};
if (!programId || !partnerId) {
throw new DubApiError({
code: "unauthorized",
message: "Invalid embed public token.",
});
}
```
Sources: [apps/web/lib/embed/referrals/auth.ts:33-65](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/auth.ts#L33-L65)
The `withReferralsEmbedToken` function acts as a higher-order wrapper securing referral embed API routes. It intercepts incoming requests to extract the public token from the `Authorization` request header using a Bearer scheme split. When the token is missing, it throws a `DubApiError` with the unauthorized code and a specific message. If the token is successfully extracted, it queries the underlying storage via `referralsEmbedToken.get(embedToken)` to retrieve the associated `programId` and `partnerId`.
> [!WARNING]
> If a request provides an invalid or expired embed token where `programId` or `partnerId` cannot be resolved from storage, the wrapper immediately halts execution and returns an unauthorized response.
```typescript
const { success, limit, reset, remaining } = await ratelimit(
rateLimit,
"1 m",
).limit(embedToken);
responseHeaders.set("Retry-After", reset.toString());
responseHeaders.set("X-RateLimit-Limit", limit.toString());
responseHeaders.set("X-RateLimit-Remaining", remaining.toString());
responseHeaders.set("X-RateLimit-Reset", reset.toString());
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
});
}
```
Sources: [apps/web/lib/embed/referrals/auth.ts:67-83](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/auth.ts#L67-L83)
Rate limiting is enforced on every verified token using Upstash Redis with a fixed window of 60 requests per minute. Standard rate-limit metadata headers are injected into the response collection, including `Retry-After`, `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset`. If the limit is exceeded, a `rate_limit_exceeded` error is thrown.
### Database Resolution and Context Injection
```typescript
const { program, links, partnerGroup, ...programEnrollment } =
await prisma.programEnrollment.findUniqueOrThrow({
where: {
partnerId_programId: {
partnerId,
programId,
},
},
include: {
links: {
orderBy: [
{
saleAmount: "desc",
},
{
leads: "desc",
},
{
clicks: "desc",
},
],
},
program: true,
partnerGroup: true,
},
});
if (!partnerGroup) {
throw new DubApiError({
code: "forbidden",
message:
"You’re not part of any group yet. Please reach out to the program owner to be added.",
});
}
return await handler({
req,
params,
searchParams,
program,
programEnrollment,
group: partnerGroup as PartnerGroupProps,
links,
embedToken,
});
```
Sources: [apps/web/lib/embed/referrals/auth.ts:84-128](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/embed/referrals/auth.ts#L84-L128)
Once rate limits and token validity are confirmed, the middleware queries Prisma to locate the corresponding `ProgramEnrollment` record using a composite unique identifier combining `partnerId` and `programId`. The query includes relations for `links` (ordered descending by sale amount, leads, then clicks), `program`, and `partnerGroup`.
| Relation Included | Order Criteria / Fields | Purpose |
| :--- | :--- | :--- |
| `links` | `saleAmount: desc`, `leads: desc`, `clicks: desc` | Retrieves partner referral links sorted by performance |
| `program` | Full relation | Attaches parent referral program configuration |
| `partnerGroup` | Full relation | Validates group assignment and partner tier settings |
> [!CAUTION]
> If the `partnerGroup` relation resolves to null on the enrollment record, the wrapper throws a `forbidden` error stating that the user is not part of any group yet and must reach out to the program owner.
```typescript
// GET /api/embed/referrals/token - get the referrals embed token
export const GET = withReferralsEmbedToken(async ({ embedToken }) => {
return NextResponse.json(embedToken);
});
```
Sources: [apps/web/app/ee/api/embed/referrals/token/route.ts:4-7](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/token/route.ts#L4-L7)
Target handlers such as the GET route at `/api/embed/referrals/token` receive the fully populated context object containing `req`, `params`, `searchParams`, `program`, `programEnrollment`, `group`, `links`, and `embedToken`.
### Edge Request Path Rewriting
```typescript
import { NextRequest, NextResponse } from "next/server";
import { parse } from "./utils/parse";
export function EmbedMiddleware(req: NextRequest) {
const { path, searchParamsObj, fullPath } = parse(req);
if (path.startsWith("/embed/support-chat")) {
return NextResponse.rewrite(new URL(`/app.dub.co${fullPath}`, req.url));
}
if (searchParamsObj.token) {
return NextResponse.rewrite(new URL(`/app.dub.co${fullPath}`, req.url));
}
// TODO: Show token expiry page
return NextResponse.redirect(new URL("/", req.url));
}
```
Sources: [apps/web/lib/middleware/embed.ts:1-17](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/embed.ts#L1-L17)
At the edge network layer, `EmbedMiddleware` inspects incoming `NextRequest` paths and parameters. If the path starts with `/embed/support-chat` or if a query parameter `token` is present on the request, it rewrites the destination URL to point to `app.dub.co` combined with the full requested path. Otherwise, requests fall through to a default redirect to the root URL.
## Client Embedding Library
### React Integration and Component Architecture
```tsx
"use client";
import { DubEmbedOptions, init } from "@dub/embed-core";
import { HTMLProps, memo, useEffect, useId, useRef } from "react";
type Options = Omit;
type DubEmbedProps = {
token: DubEmbedOptions["token"];
data: DubEmbedOptions["data"];
options?: Options;
} & HTMLProps;
export const DubEmbed = memo(
({ token, data, options, ...rest }: DubEmbedProps) => (
),
);
```
Sources: [packages/embeds/react/src/embed.tsx:1-18](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/embeds/react/src/embed.tsx#L1-L18)
The `@dub/embed-react` package exposes the `DubEmbed` component, which wraps client-side embedding initialization for React parent applications. The component accepts `token`, `data`, and optional configuration properties alongside standard `HTMLDivElement` HTML attributes. It utilizes `React.memo` to prevent unnecessary re-renders when parent states change without modifying embed parameters.
| Prop Name | Type | Purpose |
| :--- | :--- | :--- |
| `token` | `DubEmbedOptions["token"]` | Public authentication token minted for the embed session |
| `data` | `DubEmbedOptions["data"]` | Dataset identifier (e.g., `"referrals"`) loaded by the widget |
| `options` | `Options` | Optional overrides excluding the token property |
> [!NOTE]
> `DubEmbed` components must be rendered inside client-side components designated with the `"use client"` directive, as they rely on React hooks and DOM ref attachments.
### Lifecycle and DOM Initialization
```tsx
function DubEmbedInner({
options,
...rest
}: { options: DubEmbedOptions } & HTMLProps) {
const id = useId();
const rootRef = useRef(null);
useEffect(() => {
if (!rootRef.current) return;
const { destroy } =
init({
root: rootRef.current,
...options,
}) || {};
return () => destroy?.();
}, [id, JSON.stringify(options)]);
return
;
}
```
Sources: [packages/embeds/react/src/embed.tsx:20-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/embeds/react/src/embed.tsx#L20-L40)
The inner component `DubEmbedInner` manages the lifecycle of the underlying core embedding script via a local `useRef` pointing to a container `div`. It invokes the `init` method imported from `@dub/embed-core`, passing the root DOM element and merged options.
```mermaid
sequenceDiagram
participant Parent as Parent App
participant Embed as DubEmbedInner
participant Core as @dub/embed-core
Parent->>Embed: Mount component with token & data
Embed->>Embed: Generate unique id & attach useRef
Embed->>Core: init({ root: rootRef.current, ...options })
Core-->>Embed: Return destroy function
Note over Embed,Core: Component unmounts or options change
Embed->>Core: destroy() cleanup
```
Sources: [packages/embeds/react/src/embed.tsx:20-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/embeds/react/src/embed.tsx#L20-L40)
> [!WARNING]
> The `useEffect` hook depends on `JSON.stringify(options)` and `id`. Modifying configuration objects inline without memoization in the parent application can trigger repeated destruction and re-initialization cycles of the core embed instance.
### Parent Application Consumption
```tsx
"use client";
import LayoutLoader from "@/ui/layout/layout-loader";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { DubEmbed } from "@dub/embed-react";
import { CursorRays, Hyperlink, InvoiceDollar, UserCheck } from "@dub/ui/icons";
import { fetcher } from "@dub/utils";
import { useSession } from "next-auth/react";
import useSWRImmutable from "swr/immutable";
export function ReferralsPageClient() {
const { data: session, status } = useSession();
const { data: { publicToken } = {}, isLoading } = useSWRImmutable<{
publicToken: string;
}>(session && "/api/user/referrals-token", fetcher, {
keepPreviousData: true,
});
if (status === "loading" || isLoading) {
return ;
}
if (!publicToken) {
return (
>
}
pillContent="Coming soon"
/>
);
}
return ;
}
```
Sources: [apps/web/app/app.dub.co/dashboard/account/settings/referrals/page-client.tsx:1-49](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page-client.tsx#L1-L49)
In dashboard pages such as the referrals settings view, client implementations fetch user session data and retrieve public embed tokens asynchronously using SWR immutable hooks against `/api/user/referrals-token`. While loading, components render layout loaders. If no token is provisioned, they present an empty state UI. Once the token resolves, `DubEmbed` renders with `data="referrals"` and the active `publicToken`.
## Embedded Dashboard Data Resolution
### Server-Side Data Retrieval and Enrollment Resolution
```typescript
export const getReferralsEmbedData = async (token: string) => {
const { programId, partnerId } = (await referralsEmbedToken.get(token)) ?? {};
if (!programId || !partnerId) {
notFound();
}
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts:14-19](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts#L14-L19)
The server action `getReferralsEmbedData` initiates embedded page initialization by extracting the token and retrieving associated metadata from storage via `referralsEmbedToken.get(token)`. If either `programId` or `partnerId` is missing from the stored record, the function immediately triggers a `notFound()` response.
```typescript
const programEnrollment = await getProgramEnrollmentOrThrow({
partnerId,
programId,
include: {
partner: {
select: {
id: true,
name: true,
email: true,
username: true,
country: true,
tremendousEmail: true,
defaultPayoutMethod: true,
platforms: {
select: {
type: true,
identifier: true,
verifiedAt: true,
},
},
},
},
program: {
select: {
id: true,
name: true,
slug: true,
domain: true,
defaultGroupId: true,
minPayoutAmount: true,
termsUrl: true,
embedData: true,
resources: true,
},
},
links: {
include: {
linkReward: {
include: {
clickReward: true,
leadReward: true,
saleReward: true,
discount: true,
},
},
},
},
partnerGroup: true,
clickReward: true,
leadReward: true,
saleReward: true,
referralReward: true,
customReward: true,
discount: true,
programPartnerTags: {
select: {
partnerTagId: true,
},
},
},
});
if (!programEnrollment || !programEnrollment.partnerGroup) {
notFound();
}
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts:21-85](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts#L21-L85)
Once the identifiers are resolved, `getProgramEnrollmentOrThrow` queries the database for the active partner program enrollment. The Prisma query requests a selection of partner properties, program definitions, partner groups, reward configurations, and associated links. If the enrollment record or its assigned `partnerGroup` cannot be located, a `notFound()` exception is thrown.
| Relation / Field | Selected Subfields | Purpose |
| :--- | :--- | :--- |
| `partner` | `id`, `name`, `email`, `username`, `country`, `tremendousEmail`, `defaultPayoutMethod`, `platforms` | Identifies affiliate profile and payout preferences |
| `program` | `id`, `name`, `slug`, `domain`, `defaultGroupId`, `minPayoutAmount`, `termsUrl`, `embedData`, `resources` | Configures affiliate program rules and branding resources |
| `links` | `linkReward` (with `clickReward`, `leadReward`, `saleReward`, `discount`) | Resolves custom link-level commission structures |
| `partnerGroup` | All fields (`partnerGroup: true`) | Applies tier-specific group settings and limits |
| `commissions` | `status`, `earnings` (grouped) | Aggregates earnings statistics by commission lifecycle status |
> [!IMPORTANT]
> The database query explicitly includes `clickReward`, `leadReward`, `saleReward`, `referralReward`, `customReward`, and `discount` on the enrollment object to resolve fallback rewards for links lacking individual overrides.
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts:21-85](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts#L21-L85)
### Aggregation and Parallelized Prisma Queries
```typescript
const { totalClicks, totalLeads, totalConversions } =
aggregatePartnerLinksStats(links);
const [commissions, bounties] = await Promise.all([
prisma.commission.groupBy({
by: ["status"],
_sum: {
earnings: true,
},
_count: {
id: true,
},
where: {
earnings: {
gt: 0,
},
programId,
partnerId,
},
}),
getBountiesForPartner(programEnrollment),
]);
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts:100-122](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts#L100-L122)
Following program enrollment retrieval, link statistics are aggregated using `aggregatePartnerLinksStats(links)`. Simultaneously, `Promise.all` executes two parallel database requests: a Prisma `groupBy` query on the `commission` table filtered by `programId` and `partnerId` where `earnings > 0`, and a call to `getBountiesForPartner(programEnrollment)`.
```typescript
earnings: {
upcoming: commissions.reduce((acc, c) => {
if (c.status === "pending" || c.status === "processed") {
return acc + (c._sum.earnings ?? 0);
}
return acc;
}, 0),
paid: commissions.find((c) => c.status === "paid")?._sum.earnings ?? 0,
totalCount: commissions.reduce((acc, c) => acc + c._count.id, 0),
},
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts:155-164](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts#L155-L164)
The raw commission groups are reduced into summary totals for the dashboard UI. Upcoming earnings accumulate sums where status is either `"pending"` or `"processed"`, paid earnings resolve from records matching the `"paid"` status, and total count aggregates all commission record IDs across groups.
> [!WARNING]
> Commission filtering requires `earnings: { gt: 0 }`. Zero-amount or negative commission entries are omitted from partner earnings totals during aggregation.
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/get-referrals-embed-data.ts:103-119](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts#L103-L119)
### Page Routing and Suspense Fallback Rendering
```tsx
export default async function ReferralsEmbedPage(props: {
searchParams: Promise<{
token: string;
themeOptions?: string;
dynamicHeight?: string;
}>;
}) {
const searchParams = await props.searchParams;
const {
token,
themeOptions: themeOptionsRaw,
dynamicHeight: dynamicHeightRaw,
} = searchParams;
const themeOptions = parseThemeOptions(themeOptionsRaw);
const dynamicHeight = !!dynamicHeightRaw && dynamicHeightRaw !== "false";
return (
<>
}>
{dynamicHeight && }
>
);
}
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/page.tsx:9-38](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx#L9-L38)
The top-level Next.js Server Component `ReferralsEmbedPage` extracts search parameters (`token`, `themeOptions`, and `dynamicHeight`) asynchronously. It parses theme configurations using `parseThemeOptions` and normalizes the dynamic height boolean flag. It then renders the asynchronous server component `ReferralsEmbedRSC` wrapped inside a `Suspense` boundary with an `EmbedInlineLoading` fallback, alongside a `DynamicHeightMessenger` if enabled.
```tsx
async function ReferralsEmbedRSC({
token,
themeOptions,
dynamicHeight,
}: {
token: string;
themeOptions: ThemeOptions;
dynamicHeight: boolean;
}) {
const embedData = await getReferralsEmbedData(token);
return (
);
}
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/page.tsx:40-58](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx#L40-L58)
`ReferralsEmbedRSC` awaits `getReferralsEmbedData(token)` to resolve the complete dataset before passing it down to `ReferralsEmbedPageClient`, combining the aggregated payload with client theme options and height constraints.
> [!NOTE]
> The `EmbedInlineLoading` component constructs an inline skeleton matching the dimensions of the referral link widget and reward cards, utilizing the background color specified in the theme options.
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/page.tsx:60-96](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx#L60-L96)
## Partner Referral Interactivity
### Link Creation and Validation Endpoint
```typescript
// POST /api/embed/referrals/links – create links for a partner
export const POST = withReferralsEmbedToken(
async ({ req, programEnrollment, program, links, group }) => {
if (!ACTIVE_ENROLLMENT_STATUSES.includes(programEnrollment.status)) {
throw new DubApiError({
code: "forbidden",
message:
"You cannot create links in this program because your enrollment is not active.",
});
}
const { url, key } = createPartnerLinkSchema
.pick({ url: true, key: true })
.parse(await parseRequestBody(req));
if (!program.domain || !program.url) {
throw new DubApiError({
code: "bad_request",
message:
"This program needs a domain and URL set before creating a link.",
});
}
if (links.length >= group.maxPartnerLinks) {
throw new DubApiError({
code: "bad_request",
message: `You have reached the limit of ${group.maxPartnerLinks} program links.`,
});
}
validatePartnerLinkUrl({ group, url });
```
Sources: [apps/web/app/ee/api/embed/referrals/links/route.ts:25-56](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/links/route.ts#L25-L56)
The embedded partner link route processes link generation requests through the `POST` handler wrapped with `withReferralsEmbedToken`. It first validates that `programEnrollment.status` is included in `ACTIVE_ENROLLMENT_STATUSES`. The handler parses the request body for `url` and `key` using `createPartnerLinkSchema`, confirms that the program has both a `domain` and a `url` configured, and verifies that the existing link count does not exceed `group.maxPartnerLinks`. Finally, it invokes `validatePartnerLinkUrl` to check destination validity against group rules.
```typescript
const [workspaceOwner, partnerGroup, partner] = await Promise.all([
prisma.projectUsers.findFirst({
where: {
projectId: program.workspaceId,
role: "owner",
},
orderBy: {
createdAt: "desc",
},
include: {
project: {
select: {
id: true,
webhookEnabled: true,
},
},
},
}),
prisma.partnerGroup.findUnique({
where: {
id: group.id,
},
include: {
partnerGroupDefaultLinks: true,
utmTemplate: true,
},
}),
prisma.partner.findUnique({
where: {
id: programEnrollment.partnerId,
},
select: {
name: true,
},
}),
]);
// shouldn't happen but just in case
if (!partnerGroup) {
throw new DubApiError({
code: "not_found",
message: "This partner is not part of a partner group.",
});
}
const linkUrl = url || partnerGroup.partnerGroupDefaultLinks[0].url;
const { link, error, code } = await processLink({
payload: {
key: key || undefined,
url: linkUrl,
domain: program.domain,
programId: program.id,
folderId: program.defaultFolderId,
tenantId: programEnrollment.tenantId,
partnerId: programEnrollment.partnerId,
trackConversion: true,
},
workspace: {
id: program.workspaceId,
plan: "business",
users: [{ role: "owner" }],
},
userId: workspaceOwner?.userId,
skipFolderChecks: true, // can't be changed by the partner
skipProgramChecks: true, // can't be changed by the partner
skipExternalIdChecks: true, // can't be changed by the partner
});
```
Sources: [apps/web/app/ee/api/embed/referrals/links/route.ts:57-126](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/links/route.ts#L57-L126)
Once validated, the route queries the workspace owner user, partner group details including default links and UTM templates, and the partner name in parallel. It selects a default destination URL if none is supplied by falling back to `partnerGroup.partnerGroupDefaultLinks[0].url`. It then calls `processLink` with flags set to skip folder, program, and external ID checks, associating [conversion tracking](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/analytics-pipeline/conversion-tracking) and tenancy identifiers.
> [!WARNING]
> If a partner's program enrollment status is inactive or if they exceed their tier's `maxPartnerLinks` limit, the API immediately throws a `DubApiError` with code `forbidden` or `bad_request`.
Sources: [apps/web/app/ee/api/embed/referrals/links/route.ts:28-53](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/links/route.ts#L28-L53)
### Leaderboard Presentation and Data SWR
```tsx
export function ReferralsEmbedLeaderboard() {
const token = useEmbedToken();
const { data: partners, isLoading } = useSWR<
z.infer[]
>(
"/api/embed/referrals/leaderboard",
(url) =>
fetcher(url, {
headers: {
Authorization: `Bearer ${token}`,
},
}),
{
keepPreviousData: true,
},
);
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/leaderboard.tsx:20-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx#L20-L36)
The `ReferralsEmbedLeaderboard` component fetches ranked partner performance via SWR from the `/api/embed/referrals/leaderboard` endpoint using an authorization bearer token. It maintains previous data during revalidation and parses rows against `LeaderboardPartnerSchema`.
```tsx
const { table, ...tableProps } = useTable({
data: partners || [],
loading: isLoading,
columns: [
{
id: "rank",
header: "Rank",
size: 40,
minSize: 40,
cell: ({ row }) => {
return (
{row.index + 1}
{row.index <= 2 && (
)}
);
},
},
{
id: "name",
header: "Partner",
cell: ({ row }) => {
return (
{generateRandomName(row.original.id)}
);
},
},
{
id: "totalCommissions",
header: "Earnings",
cell: ({ row }) => {
return currencyFormatter(row.original.totalCommissions);
},
},
],
emptyState: (
(
<>
>
)}
className="border-none md:min-h-fit"
/>
),
thClassName: "border-l-0",
tdClassName: "border-l-0",
resourceName: (plural) => `partner${plural ? "s" : ""}`,
});
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/leaderboard.tsx:38-104](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx#L38-L104)
The table UI configures three explicit columns: rank, partner name, and total commissions earnings. The rank cell displays numeric ranking alongside a `Crown` icon styled in amber, neutral, or yellow-brown for the top three positions. The partner column renders a `PartnerAvatar` alongside an anonymized partner name generated via `generateRandomName(row.original.id)` wrapped in a privacy tooltip. Earnings are formatted using `currencyFormatter`.
> [!NOTE]
> When no partners populate the leaderboard, the table renders an `AnimatedEmptyState` component featuring a users icon and placeholder indicator lines.
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/leaderboard.tsx:88-100](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx#L88-L100)
## Performance and Earnings Telemetry
### Activity Metrics and Timeseries Telemetry
```typescript
const querySchema = partnerProfileAnalyticsQuerySchema.pick({
event: true,
start: true,
end: true,
groupBy: true,
saleType: true,
interval: true,
});
// GET /api/embed/referrals/analytics – get analytics for a partner
export const GET = withReferralsEmbedToken(
async ({ links, program, searchParams }) => {
if (links.length === 0) {
return NextResponse.json([]);
}
const parsedQuery = querySchema.parse(searchParams);
const analytics = await getAnalytics({
...parsedQuery,
workspaceId: program.workspaceId,
linkId: parseFilterValue(links.map((link) => link.id)),
dataAvailableFrom: program.startedAt ?? program.createdAt,
});
return NextResponse.json(analytics);
},
```
Sources: [apps/web/app/ee/api/embed/referrals/analytics/route.ts:7-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts#L7-L33)
The embedded analytics route handles retrieval of performance metrics via the `GET` method wrapped in `withReferralsEmbedToken`. It parses query parameters using `partnerProfileAnalyticsQuerySchema` restricted to `event`, `start`, `end`, `groupBy`, `saleType`, and `interval`. If the partner has no associated links, the endpoint returns an empty array. Otherwise, it calls `getAnalytics` with the workspace identifier, parsed filter values, and data availability boundaries derived from `program.startedAt` or `program.createdAt`.
```tsx
export function ReferralsEmbedActivity() {
const {
group: { brandColor: color },
stats: { clicks, leads, conversions },
} = useReferralsEmbedData();
const token = useEmbedToken();
const isEmpty = clicks === 0 && leads === 0 && conversions === 0;
const analyticsSearchParams = new URLSearchParams({
event: "composite",
groupBy: "timeseries",
interval: "1y",
saleType: "new",
});
const { data: analytics } = useSWR(
!isEmpty &&
`/api/embed/referrals/analytics?${analyticsSearchParams.toString()}`,
(url) =>
fetcher(url, {
headers: {
Authorization: `Bearer ${token}`,
},
}),
{
keepPreviousData: true,
dedupingInterval: 60000,
},
);
```
Sources: [apps/web/app/ee/app.dub.co/embed/referrals/activity.tsx:10-40](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/app.dub.co/embed/referrals/activity.tsx#L10-L40)
The `ReferralsEmbedActivity` component renders performance cards for clicks, leads, and conversions. It queries `/api/embed/referrals/analytics` using SWR with a composite event type, yearly interval, and new sale type. When click, lead, and conversion counts are all zero, it renders an `EmptyState` component featuring a `CursorRays` icon and a decorative SVG background gradient.
> [!NOTE]
> Customer email addresses returned by event endpoints are dynamically obfuscated via `obfuscateCustomerEmail` unless `customerDataSharingEnabledAt` is configured on the program enrollment.
Sources: [apps/web/app/ee/api/embed/referrals/events/route.ts:39-68](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/api/embed/referrals/events/route.ts#L39-L68)
### Commission Earnings and Payout Data
```typescript
const querySchema = getPartnerEarningsQuerySchema
.pick({
start: true,
end: true,
page: true,
pageSize: true,
interval: true,
timezone: true,
})
.extend({
withTotal: z
.string()
.optional()
.transform((v) => v?.toLowerCase() === "true")
.default(false),
});
// GET /api/embed/referrals/earnings – get commissions for a partner from an embed token
export const GET = withReferralsEmbedToken(
async ({ programEnrollment, searchParams }) => {
const { withTotal, start, end, pageSize, page, interval, timezone } =
querySchema.parse(searchParams);
const [earnings, total] = await Promise.all([
getEarningsForPartner({
page,
```
## Related
- [Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/partner-programs/partner-programs)
- [REST API](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api)
---
## Technical docs: GET Get top programs by sales
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/gettopprogramsbysalesendpoint
## Parameters
## Responses
## Try It
---
## Technical docs: CLI Tool
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/cli-tool
Relevant source files
The following files were used as context for generating this wiki page:
- [packages/cli/src/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/index.ts)
- [packages/cli/src/commands/login.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts)
- [packages/cli/src/commands/links.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/links.ts)
- [packages/cli/src/api/links.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/links.ts)
- [apps/web/app/api/links/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/links/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/route.ts)
- [packages/cli/package.json](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/package.json)
- [apps/web/lib/integrations/slack/commands.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/integrations/slack/commands.ts)
- [packages/cli/src/utils/oauth.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/oauth.ts)
- [apps/web/app/api/callback/bitly/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/callback/bitly/route.ts)
- [apps/web/app/api/workspaces/idOrSlug/import/short/route.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/api/workspaces/%5BidOrSlug%5D/import/short/route.ts)
- [apps/web/lib/middleware/link.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/middleware/link.ts)
- [packages/cli/src/types/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/types/index.ts)
- [apps/web/app/app.dub.co/dashboard/slug/links/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/links/page-client.tsx)
- [apps/web/app/app.dub.co/dashboard/slug/links/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/links/page.tsx)
- [apps/web/middleware.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/middleware.ts)
- [apps/web/app/app.dub.co/onboarding/workspaces/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(onboarding)/workspaces/page.tsx)
- [packages/cli/src/api/callback.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/links/components/disable-restore-workspace.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/disable-restore-workspace.tsx)
- [apps/web/app/app.dub.co/onboarding/onboarding/steps/success/page-client.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/success/page-client.tsx)
- [apps/web/app/ee/admin.dub.co/dashboard/links/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx)
- [packages/cli/src/commands/shorten.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/shorten.ts)
- [packages/utils/src/constants/dub-domains.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/utils/src/constants/dub-domains.ts)
- [apps/web/lib/dub.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/lib/dub.ts)
- [apps/web/app/ee/admin.dub.co/dashboard/domains/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/(ee)/admin.dub.co/(dashboard)/domains/page.tsx)
- [packages/stripe-app/src/views/AppSettings.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/stripe-app/src/views/AppSettings.tsx)
- [packages/cli/src/utils/config.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/config.ts)
- [packages/utils/src/constants/main.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/utils/src/constants/main.ts)
- [packages/cli/src/api/domains.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/domains.ts)
- [apps/web/app/app.dub.co/dashboard/slug/links/...link/page.tsx](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/apps/web/app/app.dub.co/(dashboard)/%5Bslug%5D/links/%5B...link%5D/page.tsx)
## Overview
The Dub command-line interface (`dub-cli`) provides a lightweight terminal workflow for interacting with the Dub API, allowing developers to manage short links, authentication credentials, and workspace domains directly from their shell. Built using Node.js and the Commander framework, the tool bootstraps an executable command registry that coordinates local state persistence, OAuth2 authorization flows, and remote link generation. By integrating the core Dub SDK with automated configuration storage and interactive prompts, the CLI simplifies administrative tasks and URL shortening operations across developer environments.
Sources: [packages/cli/src/index.ts:8-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/index.ts#L8-L34), [packages/cli/package.json:4-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/package.json#L4-L13), [packages/cli/src/utils/config.ts:5-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/config.ts#L5-L32)
## Entry Point and Command Registry
### CLI Executable Bootstrap and Signal Handlers
The CLI binary initializes via a Node.js environment bootstrap specified by the shebang `#!/usr/bin/env node` and maps to `./dist/index.js` under the `"bin"` field in `package.json`. Process lifecycle management is handled by explicit signal listeners for `SIGINT` and `SIGTERM`, both of which immediately terminate the process with a zero status code.
```typescript
process.on("SIGINT", () => process.exit(0));
process.on("SIGTERM", () => process.exit(0));
```
Sources: [packages/cli/src/index.ts:1-12](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/index.ts#L1-L12), [packages/cli/package.json:12-14](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/package.json#L12-L14)
The asynchronous `main()` function fetches runtime package metadata via `getPackageInfo()` to populate the root Commander program configuration, defining the binary name as `dub`, assigning its description, and attaching version handling flags.
```typescript
const packageInfo = await getPackageInfo();
const program = new Command()
.name("dub")
.description("A CLI for shortening links with the Dub API.")
.version(
packageInfo.version || "1.0.0",
"-v, --version",
"display the version number",
);
```
Sources: [packages/cli/src/index.ts:14-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/index.ts#L14-L24)
> [!NOTE]
> If `getPackageInfo()` fails to resolve a valid version string, the root command falls back to `"1.0.0"` while parsing version flag inputs `-v` or `--version`.
> Sources: [packages/cli/src/index.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/index.ts#L15-L24)
### Command Registration and Package Configuration
Subcommands imported from local command modules are registered sequentially onto the root Commander instance before executing `program.parse()`. The registered subcommand suite consists of `login`, `config`, `domains`, `shorten`, and `links`.
```typescript
program
.addCommand(login)
.addCommand(config)
.addCommand(domains)
.addCommand(shorten)
.addCommand(links);
program.parse();
```
Sources: [packages/cli/src/index.ts:26-33](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/index.ts#L26-L33)
The package configuration establishes `dub-cli` as an ESM module (`"type": "module"`) with global installation preference (`"preferGlobal": true`). TypeScript compilation and bundling are driven by `tsup`, utilizing `rimraf` for cleaning build artifacts and `tsc` for type checking.
| Script Name | Command | Purpose |
| :--- | :--- | :--- |
| `dev` | `tsup --watch` | Runs the bundler in watch mode for development. |
| `build` | `tsup` | Builds distribution files for production release. |
| `typecheck` | `tsc --noEmit` | Performs TypeScript type verification without emitting outputs. |
| `clean` | `rimraf dist` | Removes the `dist` build directory. |
| `start` | `node dist/index.js ` | Executes the compiled bundle directly. |
Sources: [packages/cli/package.json:8-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/package.json#L8-L15), [packages/cli/package.json:35-41](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/package.json#L35-L41)
## Authentication and OAuth Callback Flow
### OAuth2 Client Initiation and Authorization Request
The `login` command initializes the authentication workflow by generating a 64-character code verifier using `getNanoid(64)` and establishing a local redirect target at `http://localhost:4587/callback`. It utilizes an `OAuth2Client` instance configured with client ID `dub_app_39527dcc11b452f38bb54a3a1664fd044d7158dfea8abcde`, authorization endpoint `https://app.dub.co/oauth/authorize`, and token endpoint `https://api.dub.co/oauth/token`.
```typescript
export const oauthClient = new OAuth2Client({
clientId: "dub_app_39527dcc11b452f38bb54a3a1664fd044d7158dfea8abcde",
authorizationEndpoint: "https://app.dub.co/oauth/authorize",
tokenEndpoint: "https://api.dub.co/oauth/token",
});
```
Sources: [packages/cli/src/utils/oauth.ts:3-8](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/oauth.ts#L3-L8)
The command requests authorization by passing the `redirectUri`, `codeVerifier`, and required scopes to `oauthClient.authorizationCode.getAuthorizeUri()`. The requested permission scopes are `links.read`, `links.write`, and `domains.read`. Once the authorization URI is generated, an interactive spinner starts via `ora`, and the user's default browser opens via `open(authUrl)` to complete authentication on the Dub platform.
```typescript
const codeVerifier = getNanoid(64);
const redirectUri = "http://localhost:4587/callback";
const authUrl = await oauthClient.authorizationCode.getAuthorizeUri({
redirectUri,
codeVerifier,
scope: ["links.read", "links.write", "domains.read"],
});
const spinner = ora("Opening browser for authentication").start();
await open(authUrl);
spinner.text = "Waiting for authentication";
oauthCallbackServer({
oauthClient,
redirectUri,
codeVerifier,
spinner,
});
```
Sources: [packages/cli/src/commands/login.ts:14-34](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts#L14-L34)
> [!NOTE]
> The local redirect URI explicitly binds to port `4587` on `localhost` (`http://localhost:4587/callback`), requiring that port to remain available during the login sequence.
> Sources: [packages/cli/src/commands/login.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/login.ts#L15)
### Local Callback Server and Credential Exchange
The local HTTP server spawned by `oauthCallbackServer` listens on port `4587` to intercept the redirect callback from the authorization provider. Incoming requests are parsed via `url.parse()`. If a request targets any path other than `/callback` or uses a method other than `GET`, the server responds with a `404` status code and terminates the request handling.
```typescript
const server = http.createServer(async (req, res) => {
const reqUrl = url.parse(req.url || "", true);
if (reqUrl.pathname !== "/callback" || req.method !== "GET") {
res.writeHead(404);
res.end("Not found");
return;
}
```
Sources: [packages/cli/src/api/callback.ts:23-30](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L23-L30)
Upon receiving a valid `GET /callback` request containing an authorization `code` query parameter, the server transitions the CLI spinner state to `"Verifying"` and exchanges the authorization code for tokens by invoking `oauthClient.authorizationCode.getToken()`.
```typescript
const code = reqUrl.query.code as string;
if (!code) {
res.writeHead(400);
res.end(
"Authorization code not found. Please start the login process again.",
);
return;
}
try {
spinner.text = "Verifying";
const { accessToken, refreshToken, expiresAt } =
await oauthClient.authorizationCode.getToken({
code,
redirectUri,
codeVerifier,
});
```
Sources: [packages/cli/src/api/callback.ts:32-51](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L32-L51)
After acquiring the token bundle, the spinner updates to `"Configuring"`, and a configuration object is constructed containing the trimmed `access_token`, `refresh_token`, `expires_at`, and the default workspace domain `dub.sh`. This configuration is saved via `setConfig(configInfo)`. Upon successful persistence, the server outputs confirmation messages, responds to the browser with an HTML success message, closes the HTTP server, and exits the process with code `0`.
```typescript
spinner.text = "Configuring";
const configInfo: DubConfig = {
access_token: accessToken.trim(),
refresh_token: refreshToken,
expires_at: expiresAt,
domain: "dub.sh",
};
await setConfig(configInfo);
spinner.succeed("Configuration completed");
logger.info("");
logger.info(chalk.green("Logged in successfully!"));
logger.info("");
res.writeHead(200, { "Content-Type": "text/html" });
res.end("Authentication successful! You can close this window.");
} catch (error) {
res.writeHead(500, { "Content-Type": "text/html" });
res.end("An error occurred during authentication. Please try again.");
} finally {
server.close();
process.exit(0);
}
```
Sources: [packages/cli/src/api/callback.ts:53-77](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L53-L77)
> [!WARNING]
> The callback server enforces a strict inactivity timeout of 300,000 milliseconds (5 minutes) via `setTimeout`, after which the server automatically closes and terminates the process with exit code `0` if authentication has not completed.
> Sources: [packages/cli/src/api/callback.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/callback.ts#L80-L83)
## Configuration Persistence and State Management
### Schema Types and Configstore Backend
The CLI configuration layer relies on the `Configstore` package initialized with the identifier `"dub-cli"` to persist authentication state and user preferences on the local filesystem. The core data structure is defined by the `DubConfig` interface, which tracks credentials and contextual options. API error payloads are handled through the separate `APIError` interface.
```typescript
export interface DubConfig {
access_token: string;
refresh_token: string | null;
expires_at: number | null;
domain?: string;
}
export interface APIError {
error: {
code: string;
message: string;
doc_url: string;
};
}
```
Sources: [packages/cli/src/types/index.ts:1-13](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/types/index.ts#L1-L13)
| Property | Type | Description |
| :--- | :--- | :--- |
| `access_token` | `string` | The active OAuth access token for authenticating API requests |
| `refresh_token` | `string \| null` | The token used to obtain a new access token upon expiration |
| `expires_at` | `number \| null` | Unix timestamp in milliseconds indicating when the access token expires |
| `domain` | `string` (optional) | The active workspace custom or default domain (e.g., `dub.sh`) |
Sources: [packages/cli/src/types/index.ts:1-6](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/types/index.ts#L1-L6)
### Token Retrieval and Automated Refresh Logic
Configuration retrieval is handled by `getConfig()`, which inspects the local `dub-cli` store. If the store is empty, an error is thrown instructing the user to authenticate. If `expires_at` is present and the current timestamp (`Date.now()`) has reached or exceeded that expiration threshold, `getConfig()` automatically invokes `oauthClient.refreshToken()` using the stored credentials before updating the configuration store and returning the refreshed state.
```typescript
export async function getConfig(): Promise {
const configStore = new Configstore("dub-cli");
if (!configStore.size) {
throw new Error(
"Access token not found. Please run `dub login` to authenticate with Dub.",
);
}
const config = configStore.all as DubConfig;
if (config.expires_at && Date.now() >= config.expires_at) {
const { accessToken, refreshToken, expiresAt } =
await oauthClient.refreshToken({
accessToken: config.access_token,
refreshToken: config.refresh_token,
expiresAt: config.expires_at,
});
return await setConfig({
access_token: accessToken,
refresh_token: refreshToken,
expires_at: expiresAt,
});
}
return await configStore.all;
}
```
Sources: [packages/cli/src/utils/config.ts:5-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/config.ts#L5-L32)
> [!WARNING]
> If `configStore.path` is falsy after attempting to write updates via `setConfig()`, the utility immediately throws an error stating `"Failed to create or update config file"`.
> Sources: [packages/cli/src/utils/config.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/config.ts#L47-L49)
Updates to configuration state are handled by `setConfig()`, which merges partial configuration objects into the existing stored state and writes them back to disk.
```typescript
export async function setConfig(
newConfig: Partial,
): Promise {
const configStore = new Configstore("dub-cli");
const existingConfig: DubConfig = configStore.all;
const updatedConfig: DubConfig = {
...existingConfig,
...newConfig,
};
configStore.set(updatedConfig);
if (!configStore.path) {
throw new Error("Failed to create or update config file");
}
return updatedConfig;
}
```
Sources: [packages/cli/src/utils/config.ts:34-52](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/utils/config.ts#L34-L52)
## Short Link Creation and Management
### Command Definition and Interactive Prompts
The `shorten` command is built with `commander` and accepts an optional destination URL argument and an optional short key argument that defaults to a nanoid generated by `getNanoid()`. If the user invokes the command without passing a destination URL, `prompts` is used to interactively request both the destination URL and the short key, initializing the key prompt with a fresh nanoid value.
```typescript
export const shorten = new Command()
.name("shorten")
.description("Create a short link")
.argument("[url]", "Destination URL")
.argument("[key]", "Short key", getNanoid())
.action(async (url, key) => {
try {
await getConfig();
let linkData = { url, key };
if (!url) {
linkData = await prompts(
[
{
type: "text",
name: "url",
message: "Enter your Destination URL:",
},
{
type: "text",
name: "key",
message: "Enter your Short link:",
initial: getNanoid(),
},
],
```
Sources: [packages/cli/src/commands/shorten.ts:11-36](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/shorten.ts#L11-L36)
> [!WARNING]
> If the user cancels the interactive prompt via keyboard interrupt or abort, the `onCancel` handler prints an empty line followed by `"You canceled the prompt."` and immediately terminates the process with `process.exit(0)`.
> Sources: [packages/cli/src/commands/shorten.ts](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/shorten.ts#L38-L44)
### API Integration and Output Formatting
The API wrapper function `createLink` retrieves local configuration via `getConfig()`, instantiates the `Dub` SDK client with the stored `access_token`, and calls `dub.links.create()` with the workspace domain, destination URL, and short key.
```typescript
export async function createLink({ url, key }: { url: string; key: string }) {
const config = await getConfig();
const dub = new Dub({
token: config.access_token,
});
return await dub.links.create({
domain: config.domain,
url: url,
key: key,
});
```
Sources: [packages/cli/src/api/links.ts:4-15](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/links.ts#L4-L15)
During execution, `shorten` displays an `ora` spinner with the text `"Creating new short link"`. Upon success, the spinner reports `"New short link created!"` and logs the resulting short link URL styled with `chalk.green`. If link creation fails, the spinner reports `"Failed to create link"`, stops, and re-throws the error to be caught by `handleError`.
```typescript
const spinner = ora("Creating new short link").start();
try {
const generatedShortLink = await createLink(linkData);
spinner.succeed("New short link created!");
logger.info("");
logger.info(chalk.green(generatedShortLink.shortLink));
logger.info("");
} catch (error) {
spinner.fail("Failed to create link");
spinner.stop();
logger.info("");
throw error;
}
```
Sources: [packages/cli/src/commands/shorten.ts:48-63](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/shorten.ts#L48-L63)
Separately, the `links` command queries workspace links using `dub.links.list()`, accepting optional search and limit options where `pageSize` defaults to `10` when no limit is provided. The resulting links are mapped into tabular objects displaying their short link, destination URL, click count, and a formatted creation date string before being output via `console.table`.
```typescript
export const links = new Command()
.command("links")
.description("Search for links in your Dub workspace")
.option("-s, --search [search]", "Search term to filter links by")
.option("-l, --limit [limit]", "Number of links to fetch")
.action(async ({ search, limit }) => {
try {
const config = await getConfig();
const spinner = ora("Fetching links").start();
const dub = new Dub({
token: config.access_token,
});
const links = await dub.links.list({
search,
pageSize: limit ? parseInt(limit) : 10,
});
spinner.stop();
const formattedLinks = links.result.map((link) => ({
"Short Link": link.shortLink,
"Destination URL": link.url,
Clicks: link.clicks,
"Created At": new Date(link.createdAt).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
}),
}));
console.table(formattedLinks);
```
Sources: [packages/cli/src/commands/links.ts:7-42](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/links.ts#L7-L42)
| Command Option | Flag | Description | Default |
| :--- | :--- | :--- | :--- |
| Search | `-s, --search [search]` | Search term to filter links by | `undefined` |
| Limit | `-l, --limit [limit]` | Number of links to fetch | `10` |
Sources: [packages/cli/src/commands/links.ts:10-24](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/commands/links.ts#L10-L24)
## Workspace Domain Discovery
### Querying Workspace Domains
The CLI domain discovery utility `getDomains()` retrieves custom domains associated with the authenticated user's workspace by combining resources from the official SDK and the public API. It initializes the `Dub` SDK client using the stored `access_token` retrieved via `getConfig()`.
```typescript
export async function getDomains() {
const config = await getConfig();
const dub = new Dub({
token: config.access_token,
});
```
Sources: [packages/cli/src/api/domains.ts:6-11](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/domains.ts#L6-L11)
To compile the complete list of available domain slugs, `getDomains()` executes a concurrent request using `Promise.all` that calls `dub.domains.list()` and performs an HTTP `GET` request against the `https://api.dub.co/domains/default` endpoint, passing the bearer token and application/json headers.
```typescript
const [{ result: domainsResponse }, defaultDomainsResponse] =
await Promise.all([
dub.domains.list(),
fetch("https://api.dub.co/domains/default", {
method: "GET",
headers: {
Authorization: `Bearer ${config.access_token}`,
"Content-Type": "application/json",
},
}),
]);
```
Sources: [packages/cli/src/api/domains.ts:13-23](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/domains.ts#L13-L23)
> [!NOTE]
> The default domains response is parsed into an array of strings using `parseApiResponse()`, whereas the SDK domain list response yields domain objects whose `slug` properties are extracted.
> Sources: [packages/cli/src/api/domains.ts:25-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/domains.ts#L25-L28)
### Response Formatting and Deduplication
Once both asynchronous requests resolve, the domain slugs from the workspace and the default system domains are concatenated into a single array. The combined collection is then passed into a `Set` to eliminate duplicate entries and converted back into a standard array using `Array.from()`.
```typescript
const allSlugs = [...domains.map((domain) => domain.slug), ...defaultDomains];
return Array.from(new Set(allSlugs));
```
Sources: [packages/cli/src/api/domains.ts:30-32](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/domains.ts#L30-L32)
| Data Source | Retrieval Method | Target Type | Processing |
| :--- | :--- | :--- | :--- |
| Workspace Domains | `dub.domains.list()` | Domain Object Array | Mapped to `.slug` property |
| Default Domains | `fetch("https://api.dub.co/domains/default")` | `string[]` | Parsed via `parseApiResponse` |
Sources: [packages/cli/src/api/domains.ts:13-28](https://github.com/blade47/dub/blob/7c93d97abf0ecd37fb669c6a68a1f7ef9109daea/packages/cli/src/api/domains.ts#L13-L28)
## Related
- [REST API](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/administration-and-api/rest-api)
- [Quick Start](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/technical/getting-started/quick-start)
---
## Technical docs: POST Reset user login attempts
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/resetloginattempts
## Request Body
User email
## Responses
## Try It
---
## Technical docs: GET Get admin revenue timeseries
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/getadminrevenue
## Parameters
## Responses
## Try It
---
## Technical docs: POST Send Slack Connect invite
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/sendslacksupportinvite
## Request Body
Invite payload containing emails, workspaceSlug, and optional channelId
## Responses
## Try It
---
## Technical docs: POST Disable a workspace
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/disableworkspace
## Request Body
Workspace slug to disable
## Responses
## Try It
---
## Technical docs: POST Restore a workspace
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/admin/restoreworkspace
## Request Body
Workspace slug to restore
## Responses
## Try It
---
## Technical docs: GET AppsFlyer Webhook Handler (GET)
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/webhooks/appsflyerwebhookget
## Parameters
## Responses
## Try It
---
## Technical docs: HEAD AppsFlyer Webhook Handler (HEAD)
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/webhooks/appsflyerwebhookhead
## Responses
## Try It
---
## Technical docs: POST Export audit logs to CSV
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/audit-logs/exportauditlogs
## Request Body
Start and end dates for the export
## Responses
## Try It
---
## Technical docs: GET SAML Authorize (GET)
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/auth/samlauthorizeget
## Responses
## Try It
---
## Technical docs: POST SAML Authorize (POST)
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/auth/samlauthorizepost
## Request Body
Authorization request parameters
## Responses
## Try It
---
## Technical docs: POST SAML Callback
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/auth/samlcallbackpost
## Request Body
SAML response and RelayState form data
## Responses
## Try It
---
## Technical docs: POST SAML Token
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/auth/samltokenpost
## Request Body
Form data containing authorization credentials
## Responses
## Try It
---
## Technical docs: GET SAML User Info
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/auth/samluserinfoget
## Parameters
## Responses
## Try It
---
## Technical docs: POST Verify SAML connection for workspace
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/auth/samlverifypost
## Request Body
Workspace slug
## Responses
## Try It
---
## Technical docs: GET Get a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/getbounty
## Parameters
## Responses
## Try It
---
## Technical docs: PATCH Update a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/updatebounty
## Parameters
## Request Body
Bounty update data
## Responses
## Try It
---
## Technical docs: DELETE Delete a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/deletebounty
## Parameters
## Responses
## Try It
---
## Technical docs: POST Approve a submission
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/approvebountysubmission
## Parameters
## Request Body
Approval payload
## Responses
## Try It
---
## Technical docs: POST Reject a submission
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/rejectbountysubmission
## Parameters
## Request Body
Rejection payload
## Responses
## Try It
---
## Technical docs: GET Get all submissions for a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/getbountysubmissions
## Parameters
## Responses
## Try It
---
## Technical docs: POST Sync social metrics for a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/syncsocialmetrics
## Parameters
## Request Body
Sync social metrics parameters
## Responses
## Try It
---
## Technical docs: GET Get total bounty submissions count
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/getbountiessubmissionscount
## Responses
## Try It
---
## Technical docs: GET Get all bounties for a program
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/getbounties
## Parameters
## Responses
## Try It
---
## Technical docs: POST Create a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/bounties/createbounty
## Request Body
Bounty creation payload
## Responses
## Try It
---
## Technical docs: POST Duplicate an existing campaign
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/duplicatecampaign
## Parameters
## Responses
## Try It
---
## Technical docs: GET Get campaign events count
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/getcampaigneventscount
## Parameters
## Responses
## Try It
---
## Technical docs: GET Get campaign events
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/getcampaignevents
## Parameters
## Responses
## Try It
---
## Technical docs: POST Send preview email for a campaign
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/sendcampaignpreview
## Parameters
## Request Body
Preview email request body containing email addresses and campaign details
## Responses
## Try It
---
## Technical docs: GET Get an email campaign
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/getcampaign
## Parameters
## Responses
## Try It
---
## Technical docs: PATCH Update an email campaign
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/updatecampaign
## Parameters
## Request Body
Campaign update payload
## Responses
## Try It
---
## Technical docs: DELETE Delete a campaign
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/deletecampaign
## Parameters
## Responses
## Try It
---
## Technical docs: GET Get campaign summary
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/getcampaignsummary
## Parameters
## Responses
## Try It
---
## Technical docs: GET Get campaigns count
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/getcampaignscount
## Responses
## Try It
---
## Technical docs: GET Get all campaigns
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/getcampaigns
## Responses
## Try It
---
## Technical docs: POST Create campaign
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/campaigns/createcampaign
## Request Body
Campaign creation payload
## Responses
## Try It
---
## Technical docs: POST R2 Object Created Webhook
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cloudflare/r2objectcreatedwebhook
## Request Body
Webhook payload
## Responses
## Try It
---
## Technical docs: GET Get commission by ID
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/getcommissionbyid
## Parameters
## Responses
## Try It
---
## Technical docs: PATCH Update commission
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/updatecommission
## Parameters
## Request Body
Commission update payload
## Responses
## Try It
---
## Technical docs: GET Get commission analytics
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/getcommissionanalytics
## Responses
## Try It
---
## Technical docs: PATCH Bulk update commission status
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/patchapicommissionsbulk
## Request Body
Commission IDs and new status
## Responses
## Try It
---
## Technical docs: GET Get commissions count
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/getapicommissionscount
## Responses
## Try It
---
## Technical docs: GET Export commissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/getapicommissionsexport
## Responses
## Try It
---
## Technical docs: GET Get all commissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/getapicommissions
## Responses
## Try It
---
## Technical docs: POST Create manual commission
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/commissions/postapicommissions
## Request Body
Manual commission details
## Responses
## Try It
---
## Technical docs: POST Aggregate click events
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postapicronaggregateclicks
## Responses
## Try It
---
## Technical docs: POST Notify partners about new bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postapicronbountiesnotifypartners
## Request Body
Notification details including bountyId
## Responses
## Try It
---
## Technical docs: GET Queue social metrics sync
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/getapicronbountiesqueuesyncsocialmetrics
## Responses
## Try It
---
## Technical docs: POST Sync social metrics for a bounty
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postapicronbountiessyncsocialmetrics
## Request Body
Sync request body containing bountyId
## Responses
## Try It
---
## Technical docs: POST Upsert draft bounty submissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/upsertdraftbountysubmissions
## Request Body
Bounty ID and pagination details
## Responses
## Try It
---
## Technical docs: POST Broadcast campaigns
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/broadcastcampaigns
## Request Body
Campaign broadcast payload
## Responses
## Try It
---
## Technical docs: GET Queue scheduled campaigns
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/queuescheduledcampaigns
## Responses
## Try It
---
## Technical docs: POST Cleanup declined invites
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanupdeclinedinvites
## Request Body
QStash verification body
## Responses
## Try It
---
## Technical docs: POST Cleanup demo embed partners
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanupdemoembedpartners
## Request Body
QStash verification body
## Responses
## Try It
---
## Technical docs: POST Cleanup E2E test data
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanupe2etests
## Responses
## Try It
---
## Technical docs: POST Cleanup expired fraud groups
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanupexpiredfraudgroups
## Responses
## Try It
---
## Technical docs: POST Cleanup expired tokens
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanupexpiredtokens
## Responses
## Try It
---
## Technical docs: POST Cleanup links based on retention days
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanuplinkretention
## Responses
## Try It
---
## Technical docs: POST Cleanup orphaned records
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanuporphaned
## Responses
## Try It
---
## Technical docs: POST Cleanup rejected program applications
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanuprejectedapplications
## Responses
## Try It
---
## Technical docs: POST Cleanup unenrolled partners
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/cleanupunenrolledpartners
## Responses
## Try It
---
## Technical docs: POST Backfill referral commissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/backfillreferralcommissions
## Responses
## Try It
---
## Technical docs: POST Create referral commission
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/createreferralcommission
## Responses
## Try It
---
## Technical docs: POST Queue referral commissions for payout
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/queuereferralcommissions
## Responses
## Try It
---
## Technical docs: POST Drain shim for discount code creation
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/creatediscountcode
## Responses
## Try It
---
## Technical docs: POST Disable discount code
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/disablediscountcode
## Responses
## Try It
---
## Technical docs: POST Sync disposable and Tremendous prohibited email domains
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/syncdisposableemails
## Responses
## Try It
---
## Technical docs: GET Create payment intents for domain renewals
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/domainrenewalpayments
## Responses
## Try It
---
## Technical docs: GET Send domain renewal reminders
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/domainrenewalreminders
## Responses
## Try It
---
## Technical docs: POST Renew domains for a given invoice
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/domainrenewalsucceeded
## Request Body
Invoice identifier for completed renewal
## Responses
## Try It
---
## Technical docs: POST Transfer domain between workspaces
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/transferdomain
## Request Body
Domain transfer payload
## Responses
## Try It
---
## Technical docs: POST Update links associated with a domain update
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/updatedomainlinks
## Request Body
Domain update payload
## Responses
## Try It
---
## Technical docs: GET Check domain verification status
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/verifydomainscron
## Responses
## Try It
---
## Technical docs: POST Update Resend domain click tracking
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/updateemaildomain
## Request Body
Domain update payload
## Responses
## Try It
---
## Technical docs: GET Verify email domains
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/verifyemaildomains
## Responses
## Try It
---
## Technical docs: POST Export commissions worker
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/exportcommissions
## Request Body
Commissions export payload
## Responses
## Try It
---
## Technical docs: POST Export partner customers worker
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/exportpartnercustomers
## Request Body
Partner customer export payload
## Responses
## Try It
---
## Technical docs: POST Export workspace customers worker
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/exportcustomers
## Request Body
Customer export payload
## Responses
## Try It
---
## Technical docs: POST Export partner events worker
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/exportpartnerevents
## Request Body
Partner events export payload
## Responses
## Try It
---
## Technical docs: POST Process large event exports
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-export-events-workspace
## Request Body
Export filters and metadata
## Responses
## Try It
---
## Technical docs: POST Process large link exports
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-export-links
## Request Body
Export filters and metadata
## Responses
## Try It
---
## Technical docs: POST Process large partner exports
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-export-partners
## Request Body
Export filters and metadata
## Responses
## Try It
---
## Technical docs: POST Process large payout exports
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-export-payouts
## Request Body
Export filters and metadata
## Responses
## Try It
---
## Technical docs: POST Backfill framer leads batch
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-framer-backfill-leads-batch
## Request Body
Array of lead events to backfill
## Responses
## Try It
---
## Technical docs: POST Release all hold commissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-fraud-release-all-hold-commissions
## Request Body
Program ID
## Responses
## Try It
---
## Technical docs: POST Release hold commissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/endpoints/post-api-cron-fraud-release-hold-commissions
## Request Body
Program ID, partner ID, and resolved group IDs
## Responses
## Try It
---
## Technical docs: GET Fraud events summary cron
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/getfraudsummarycron
## Request Body
Optional request body for pagination cursor
## Responses
## Try It
---
## Technical docs: POST Fraud events summary cron
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postfraudsummarycron
## Request Body
Optional request body for pagination cursor
## Responses
## Try It
---
## Technical docs: POST FX rates update cron
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postfxratescron
## Responses
## Try It
---
## Technical docs: POST Create default links cron
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcreatedefaultlinkscron
## Request Body
Payload containing defaultLinkId, userId, and optional cursor
## Responses
## Try It
---
## Technical docs: POST Remap default links cron
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postremapdefaultlinkscron
## Request Body
Payload containing programId, groupId, partnerIds, and userId
## Responses
## Try It
---
## Technical docs: POST Update default links cron
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postupdatedefaultlinkscron
## Request Body
Payload containing defaultLinkId and optional cursor
## Responses
## Try It
---
## Technical docs: POST Import links from Bitly
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/post-api-cron-import-bitly
## Request Body
Bitly import payload containing workspaceId, bitlyGroup, etc.
## Responses
## Try It
---
## Technical docs: POST Import links from CSV
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importcsvcron
## Request Body
CSV import payload
## Responses
## Try It
---
## Technical docs: POST Import from FirstPromoter
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importfirstpromotercron
## Request Body
FirstPromoter import payload
## Responses
## Try It
---
## Technical docs: POST Import from Lemon Squeezy
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importlemonsqueezycron
## Request Body
Lemon Squeezy import payload
## Responses
## Try It
---
## Technical docs: POST Import from PartnerStack
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importpartnerstackcron
## Request Body
PartnerStack import payload
## Responses
## Try It
---
## Technical docs: POST Import from Rebrandly
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importrebrandlycron
## Request Body
Rebrandly import payload
## Responses
## Try It
---
## Technical docs: POST Import from Rewardful
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importrewardfulcron
## Request Body
Rewardful import payload
## Responses
## Try It
---
## Technical docs: POST Import from Short.io
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/importshortiocron
## Request Body
Short.io import payload
## Responses
## Try It
---
## Technical docs: POST Import Tapfiliate data
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronimporttapfiliate
## Request Body
Tapfiliate import payload containing action type
## Responses
## Try It
---
## Technical docs: POST Import Tolt data
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronimporttolt
## Request Body
Tolt import payload containing action type
## Responses
## Try It
---
## Technical docs: POST Retry failed invoice
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcroninvoicesretryfailed
## Request Body
Object containing the invoiceId to retry
## Responses
## Try It
---
## Technical docs: POST Complete link AB tests
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronlinkscompletetests
## Parameters
## Responses
## Try It
---
## Technical docs: POST Delete unclaimed demo link
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronlinksdelete
## Request Body
Object containing the linkId to delete
## Responses
## Try It
---
## Technical docs: POST Invalidate partner links cache
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronlinksinvalidateforpartners
## Request Body
Object containing the partnerId
## Responses
## Try It
---
## Technical docs: POST Notify partner of unread messages
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronmessagesnotifypartner
## Request Body
Payload containing programId, partnerId, and lastMessageId
## Responses
## Try It
---
## Technical docs: POST Notify program of unread messages
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/postcronmessagesnotifyprogram
## Request Body
Payload containing programId, partnerId, and lastMessageId
## Responses
## Try It
---
## Technical docs: POST Calculate program similarities
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/calculateprogramsimilarities
## Request Body
Payload for calculating program similarities
## Responses
## Try It
---
## Technical docs: POST Update verified partner platforms
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/cron/updatepartnerplatforms
## Request Body
Payload for updating partner platforms batch
## Responses
## Try It
---
## Technical docs: GET Get referrals embed token
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/api/embed/getreferralsembedtoken
## Responses
## Try It
---
## User guide: Quickstart Overview
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/getting-started/quickstart-overview
## Overview
### Introduction
Dub is a modern link management and attribution platform designed for marketing teams, creators, and developers. It helps you create branded short links, generate QR codes, analyze link performance, and set up affiliate or referral programs—all in one place.
This guide will walk you through setting up your Dub account, creating your first short link, and understanding the core platform features to get you up and running quickly.
---
### Step 1: Create your Dub account
### 1. Register and configure your workspace
To begin using Dub, create an account and set up your workspace:
1. Navigate to the registration page to create your account.
2. Select your account type and provide your workspace details, such as your workspace name and logo.
3. Finish the onboarding setup to land on your central dashboard.
> [!TIP]
> During onboarding, you can optionally choose whether you want to manage short links or set up an affiliate partner program.
---
### Step 2: Generate your first short link
### 1. Create a short link
Once your workspace is ready, you can start shortening and managing links.
1. Go to your workspace dashboard and navigate to the links section (`?newLink=true`).
2. Enter your destination URL (the web page you want people to visit) and choose your preferred short link domain.
3. Click save or create to generate your short link instantly. Every short link you create automatically includes a free QR code and tracking capabilities.
> [!NOTE]
> You can also use branded short-link domains such as your default domain or claim a free subdomain to increase user trust and click-through rates.
---
### Key Concepts
Familiarize yourself with these core terms as you explore Dub:
* **Workspace:** A collaborative environment where you and your teammates can manage short links, analytics, custom domains, and partner programs together.
* **Short Link:** A customized, trackable URL that forwards visitors to a destination URL.
* **Conversion Tracking:** The ability to monitor user actions (such as clicks, leads, and sales) driven by your short links.
* **Partner Program:** An integrated affiliate and referral system that lets you reward partners, influencers, and users for driving traffic and conversions.
---
### User Workflow
Here is how a typical user interaction flows within the platform:
```mermaid
flowchart TD
A[Sign up & Create Workspace] --> B[Generate Short Link]
B --> C[Share Link & Drive Traffic]
C --> D[View Analytics & Track Conversions]
```
---
### Platform Features Comparison
Dub provides a comprehensive set of tools depending on your marketing needs:
| Feature | Description |
| :--- | :--- |
| **Custom Domains** | Connect your own branded domain or claim a free domain for short links. |
| **Analytics** | View real-time clicks, geolocation, device, browser, and referrer data. |
| **QR Codes** | Automatically generate free, customizable QR codes for every short link. |
| **Partner Programs** | Grow revenue with automated partner referrals, reward structures, and payouts. |
| **Team Collaboration** | Invite teammates to your workspace with role-based access control. |
> [!TIP]
> Explore your workspace settings to install tracking scripts or configure integrations whenever you are ready to expand your workflow.
## Related
- [Account and Workspaces](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/getting-started/account-and-workspaces)
- [Managing Short Links](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/managing-short-links)
---
## User guide: Account and Workspaces
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/getting-started/account-and-workspaces
## Overview
Managing your user account and workspaces allows you to configure your personal profile details, set up collaborative environments for your team, and control who has access to your resources. This guide covers how to set up your profile, create and customize workspaces, invite team members, and assign role-based permissions.
```mermaid
flowchart TD
A[Log In / Register] --> B[Configure User Profile]
B --> C[Create or Select Workspace]
C --> D[Invite Team Members]
D --> E[Assign Workspace Roles]
```
---
## Configuring Your User Profile
### Profile Details and Settings
Your user profile holds your personal identity information across the platform, including your display name, email address, profile picture, and default workspace preferences.
### Updating Personal Information
1. Navigate to your account settings page (`/account/settings`).
2. Update your **Display Name** (maximum 32 characters).
3. Update your **Email Address**.
> [!NOTE]
> Changing your email address requires email confirmation. Your email will not be updated until you click the verification link sent to your new address.
### Managing Account Settings
- **Profile Picture:** Upload or update your personal avatar image.
- **Default Workspace:** Set a preferred workspace to automatically redirect to upon logging in.
- **Account Deletion:** Permanently delete your user account and remove associated personal data.
---
## Working with Workspaces
### Workspace Essentials and Limits
A workspace is a dedicated, collaborative environment where you and your team manage short links, partner programs, domains, and analytics.
### Key Workspace Concepts
- **Workspace Slug:** A unique URL identifier for your workspace (e.g., `app.dub.co/my-workspace`), consisting of lowercase letters, numbers, and dashes (3 to 48 characters).
- **Free Workspaces Limit:** Users can create up to 3 free workspaces. Additional workspaces require upgrading to a paid plan.
### Creating a New Workspace
1. Open the workspace dropdown menu in the sidebar and click **Create workspace** (or navigate to the workspace creation onboarding step).
2. Enter your **Workspace Name** (maximum 32 characters).
3. Set your **Workspace Slug**, which acts as your unique URL identifier.
4. Upload an optional **Workspace Logo** (recommended size: 160x160px, up to 2MB).
5. Click **Create workspace** to finish.
### Updating Workspace Settings
Workspace owners can modify general settings under `/[slug]/settings`:
- **Workspace Name:** Change the display name of your workspace.
- **Workspace Slug:** Update the unique URL slug. Changing the slug automatically redirects your active session and updates workspace navigation.
- **Logo:** Upload or change the workspace logo image.
- **Default Product:** Set the default landing product view for the workspace.
---
## Collaborating with Team Members
### Team Management and Access
Workspaces enable you to collaborate by inviting team members and assigning them specific security roles.
### Inviting Teammates
1. Go to your workspace settings and select **Members** (`/[slug]/settings/members`).
2. Click **Invite member** to open the invitation modal.
3. Enter the email addresses of the teammates you want to invite (up to 10 at a time).
4. Select a role for the invited users and click send.
> [!TIP]
> You can also generate and share a secure invite link to let teammates join your workspace directly. Invite links and email invitations remain valid for 14 days.
### Workspace Roles and Permissions
Each workspace member is assigned a specific role that dictates their access level and capabilities.
| Role | Description |
| :--- | :--- |
| `owner` | Full administrative control over the workspace, billing, settings, and team members. |
| `member` | Standard read and write access for managing links and resources. |
| `billing` | Access to manage subscription details, invoices, and billing settings. |
| `viewer` | Read-only access to view links, analytics, and workspace data. |
> [!WARNING]
> You cannot remove the last remaining owner from a workspace. To remove yourself as an owner, you must first transfer ownership to another user.
## Related
- [Quickstart Overview](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/getting-started/quickstart-overview)
- [Workspace Security Settings](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/configuration/workspace-security-settings)
---
## User guide: Managing Short Links
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/managing-short-links
## Overview
Managing short links allows you to create, organize, edit, and configure how your links behave when visitors open them. You can customize short link paths (keys), assign custom domains, attach tags for organization, generate customized QR codes, and manage redirects based on user devices or link retention settings.
---
## Creating and Customizing Short Links
### How to Create a Short Link
1. Open your workspace dashboard and click the button to create a new link.
2. Enter your destination URL in the URL field.
3. Select a domain from the domain dropdown list.
4. Enter a custom path (key) for your short link, or use the automated tools to generate one.
> [!TIP]
> You can generate a random key by clicking the random icon, or generate an AI-powered key based on your link title and destination URL by clicking the magic icon.
---
## Organizing Links with Tags and Folders
### Workspace Organization
* **Tags:** Assign color-coded tags to your short links to categorize campaigns, channels, or content types. You can filter your link list by tags using the filter menu.
* **Folders:** Group links into folders to manage permissions and keep collaborative workspaces tidy.
---
## Generating and Customizing QR Codes
### Customizing QR Codes
1. Open the QR code preview panel or click the QR code option from the link menu.
2. Modify design options such as foreground colors, dot styles, marker styles, and logo visibility.
3. Save your changes to update the live QR code preview instantly.
> [!NOTE]
> Pro plans allow you to hide or show custom logos within the center of your QR codes.
---
## Managing Redirects and Link Behavior
### Supported Redirection and Routing Options
* **Device-Specific Redirects:** Automatically route mobile visitors to dedicated iOS or Android links and app store pages.
* **Link Cloaking / Rewriting:** Display your destination webpage content directly under your short link without changing the browser URL.
* **Link Retention:** Configure automated cleanup rules to remove outdated links after a set number of days.
## Related
- [Custom Domains Setup](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/configuration/custom-domains-setup)
- [Analytics and Reporting](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/analytics-and-reporting)
---
## User guide: Analytics and Reporting
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/analytics-and-reporting
## Overview
The Analytics and Reporting feature provides deep insights into how your links perform. It lets you monitor clicks, measure conversions (leads and sales), analyze geographic and device data, and export comprehensive performance reports. Whether you are tracking standard link clicks or managing partner programs, the analytics system gives you the data you need to optimize your campaigns.
> [!NOTE]
> Workspace-level conversion tracking can be managed from your workspace settings and requires a Business plan or higher.
## Tracking Cills and Visits
### Understanding Interaction Tracking
The software automatically records visitor interactions whenever someone visits or clicks your shortened links, QR codes, or custom tracking domains.
To ensure accurate analytics, the system automatically filters out known automated bots, crawler requests, and visits flagged with no-track headers.
### Core Metrics Tracked
- **Clicks:** The total number of times your links have been accessed.
- **Leads:** The total number of signups or initial customer milestones generated through your links.
- **Sales (Conversions):** The total number of paid conversions resulting from link interactions, along with the total monetary sale amount.
## Geographic and Technical Insights
### Audience Breakdown Dimensions
In addition to click volumes, analytics break down audience engagement across multiple dimensions so you can see where and how your users are interacting with your links.
- **Continents:** Breakdown of traffic by continent code.
- **Countries:** ISO-3166-1 country-level breakdown.
- **Regions:** State or regional level tracking.
- **Cities:** Specific city-level interaction data.
- **Devices:** Device categories (such as Desktop, Mobile, or Tablet).
- **Browsers:** Software applications used to view links (such as Chrome, Safari, or Firefox).
- **Operating Systems:** Client operating systems (such as iOS, Android, macOS, or Windows).
- **Referrers:** The origin website or platform that referred traffic to your link.
> [!TIP]
> Visitor IP addresses from European Union (EU) countries are automatically omitted or anonymized during tracking to respect regional privacy standards.
## Exporting Performance Reports
### Downloading Report Archives
You can export your analytics data into a comprehensive ZIP archive containing detailed performance breakdowns.
1. Navigate to your workspace analytics dashboard.
2. Select your desired date range and filters (such as specific links, folders, or domains).
3. Click the export option to generate and download your performance report ZIP file.
> [!WARNING]
> Analytics data availability is tied to your workspace plan capabilities and creation date. Attempting to query date ranges outside your plan limits will result in validation errors.
```mermaid
graph TD
A[User Clicks Link / Visits Page] --> B[System Detects Bot & Validates Request]
B --> C{Allowed Hostname?}
C -- Yes --> D[Record Event in Analytics Database]
C -- No --> E[Reject Request]
D --> F[View Real-Time Stats & Export Reports]
```
## Related
- [Managing Short Links](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/managing-short-links)
- [Affiliate Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs)
---
## User guide: Affiliate Partner Programs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs
## Overview
Affiliate Partner Programs enable businesses to kickstart viral, product-led growth by creating powerful, branded referral and affiliate programs. With Dub Partners, workspace administrators can easily set up and manage affiliate programs, configure reward structures, invite partners, track performance, and automate payouts globally.
Partners can join your program, share unique referral links, track their clicks, leads, and sales conversions, and receive earnings seamlessly.
```mermaid
flowchart TD
A[Admin Creates Program] --> B[Partner Applies or is Invited]
B --> C[Partner Shares Referral Link]
C --> D[User Clicks Link & Converts]
D --> E[System Tracks Commission & Analytics]
E --> F[Partner Receives Payout]
```
## Creating and Managing Programs
### Setting Up a Program
Workspace owners and members on eligible plans can create and configure affiliate partner programs.
1. Navigate to your workspace dashboard in Dub.
2. Click on the **Program** section in the sidebar.
3. Follow the onboarding prompts to define your program details, such as program name, custom domain, target website URL, support email, help URL, and terms of service.
4. Set up your default reward structures and invite your initial partners.
> [!NOTE]
> Creating and managing affiliate programs requires a workspace plan with partner capabilities enabled (Business, Advanced, or Enterprise plans).
## Partner Onboarding and Links
### Partner Links & Attribution
Partners can join your affiliate program through public application pages or direct email invitations. Once approved, partners gain access to a dedicated dashboard where they can manage their links and view real-time statistics.
* **Referral Links:** Partners receive unique referral links (e.g., `https://partners.dub.co/your-program/apply?via=username` or custom short links) to drive traffic.
* **Attribution Window:** Conversions are attributed on a last-click basis. New customers who sign up for a paid plan within 90 days of using a partner's referral link count as a successful conversion.
* **Self-Referrals:** Self-referrals are automatically restricted to ensure program integrity and prevent users from getting discounts on their own accounts.
## Commission Structures and Tiers
### Reward Types and Triggers
Dub supports flexible reward and commission models that can be customized to match your business goals. Programs can reward partners based on specific user actions and reward configurations:
| Reward Type / Event | Description |
| :--- | :--- |
| **Click** | Earn a commission based on link clicks. |
| **Lead** | Earn a commission when a referred user signs up or becomes a lead. |
| **Sale** | Earn a flat fee or a percentage of the customer's subscription or sale amount. |
| **Partner Referral** | Earn a percentage of referred partners' payout fees or bonuses for a set duration. |
> [!TIP]
> Advanced plans allow you to configure dynamic click, lead, or sale-based rewards with country and product-specific modifiers, as well as automated partner group move rules based on performance.
## Payouts and Earnings
Partners can track their upcoming and paid earnings directly within their referral dashboard.
* **Withdrawals and Payout Methods:** Partners can connect their preferred payout methods to withdraw earnings once they meet program criteria (such as completing at least one sale).
* **Supported Payout Regions:** Payout methods and services like Tremendous are supported across eligible countries worldwide.
* **Admin Controls:** Workspace administrators can view partner performance, manage manual commissions or clawbacks, and process global payouts seamlessly.
> [!WARNING]
> Ensure all affiliate promotions comply with FTC guidelines. Partners must clearly disclose their financially compensated relationship when sharing referral links on social media or other platforms.
## Related
- [Launching Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/launching-partner-programs)
- [Payouts and Commissions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/payouts-and-commissions)
- [Partner Portal Guide](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/partner-portal-guide)
---
## User guide: Bounties and Campaigns
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/bounties-and-campaigns
## Overview
Bounties and campaigns are performance-based incentive tools that help you drive creator and partner engagement within your partner program. By setting up targeted bounties, you can reward partners with commissions or bonuses when they complete specific tasks, hit performance milestones, or achieve verified engagement metrics on social media platforms.
This guide covers how to create, manage, and track performance bounties, submission-based tasks, social metrics synchronization, and campaign workflows.
---
## Key Concepts
To effectively use bounties and campaigns, it helps to understand the core structures and terms used across the platform:
| Concept | Definition |
| :--- | :--- |
| **Bounty Type** | The category of bounty. Supported types: `performance`, `submission`. |
| **Performance Scope** | Defines whether milestone tracking evaluates `new` metrics or `lifetime` stats. |
| **Submission Status** | The workflow state of a partner entry. Supported statuses: `draft`, `submitted`, `approved`, `rejected`. |
| **Start Mode** | How a bounty's active window begins. Supported modes: `absolute` (fixed calendar date), `relative` (duration after enrollment/start). |
| **Submission Frequency** | How often partners can submit proof or repeat a bounty task. Supported frequencies: `day`, `week`, `month`. |
| **Rejection Reason** | The categorized rationale if a submission is declined. Supported reasons: `invalidProof`, `duplicateSubmission`, `outOfTimeWindow`, `didNotMeetCriteria`, `other`. |
| **Social Platforms** | Supported external channels for automated metric verification. Supported platforms: `youtube`, `tiktok`, `instagram`, `twitter`, `linkedin`. |
---
## Creating and Managing Bounties
### Bounty Creation Guide
You can configure and oversee performance bounties directly from your program management dashboard using the steps below:
1. Navigate to your program's dashboard and select **Bounties**.
2. Click **Create bounty** to open the bounty configuration panel.
3. Select the bounty type:
- **Performance:** Automatically rewards partners for reaching quantifiable goals (such as clicks, leads, sales, or total commissions).
- **Submission:** Rewards partners upon completing a manual task or providing required proof (such as a text description, file upload, or link).
- **Social metrics:** Rewards partners based on verified social engagement milestones (such as views or likes).
4. Configure the duration, reward amount, target audience groups, and partner tags.
5. Save and publish your bounty to make it live for eligible program participants.
> [!TIP]
> You can restrict bounties to specific partner groups or partner tags to target high-performing creators or tiered affiliate segments.
---
## Social Metrics and Content Verification
### Platform Rules and Sync Mechanics
For bounties that require social media engagement, the platform automatically syncs content metrics and verifies creator compliance according to specific platform rules:
* **Supported Platforms:** `youtube`, `tiktok`, `instagram`, `twitter`, `linkedin`
* **Supported Metrics:** `views`, `likes` (availability varies by platform)
* **Automated Syncing:** Background jobs periodically query platform analytics for active submissions to update view counts and like counts.
* **Milestone Payouts:** Bounties can include incremental bonus milestones (e.g., earning a bonus for every additional tier of views reached).
* **Automatic Completion:** Once a submission's live metric count meets or exceeds the target criteria, the submission transitions to a completed state and notifies the partner automatically.
> [!WARNING]
> Social metrics cannot be manually synced or updated after a bounty has officially ended or after a submission has already been fully approved or rejected.
---
## Tracking Partner Progress and Submissions
### Submission Workflow and Lifecycle
Enrolled partners can view available bounties, track their personal progress in real time, and submit proof through their partner portal or embedded referral views following this lifecycle:
```mermaid
flowchart TD
A[Partner Enrolls in Program] --> B[Draft Submission Created]
B --> C[Partner Submits Proof / URL]
C --> D{Meets Criteria?}
D -- Yes --> E[Submission Status: Submitted]
D -- No / Pending Review --> F[Review or Resubmit]
E --> G[Admin Approves]
G --> H[Commission & Reward Issued]
```
* **Drafts:** Automatically created for lifetime performance bounties or started by partners when working toward a goal.
* **Submitted:** Proof or social URLs have been provided and meet the threshold criteria awaiting final verification.
* **Approved:** Verified by program administrators or automated criteria checks, generating an associated commission reward.
* **Rejected:** Declined due to criteria mismatch, duplicate entries, or invalid proof.
## Related
- [Affiliate Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs)
- [Partner Portal Guide](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/partner-portal-guide)
---
## User guide: Launching Partner Programs
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/launching-partner-programs
## Overview
### Introduction to Partner Programs
Launching an affiliate and referral program allows you to kickstart product-led growth by empowering partners, influencers, and affiliates to drive traffic, leads, and sales for your business. Using the step-by-step program wizard, you can easily configure your program details, establish commission structures, invite your first partners, and brand your experience.
> [!NOTE]
> Creating a partner program requires a Business plan or higher.
---
### Step-by-Step Program Launch Wizard
Follow these steps in your workspace dashboard to configure and launch your partner program:
1. **Getting Started**
Navigate to your workspace and open the program creation page. Provide your company name, upload a square company logo (recommended size: 160×160px), set up your destination website URL where customers will be redirected, and supply a support email address that partners can see on their dashboard.
2. **Configure Rewards**
Choose your default reward type (**lead** or **sale**), select your commission structure (**one-off** or **recurring**), and determine whether your payout model uses a flat cash amount or a percentage of revenue. If you select recurring commissions, you can choose a specific duration in months or leave it set to lifetime rewards.
3. **Invite Partners**
Kickstart your program by inviting your first wave of affiliates, influencers, or users. You can add up to 25 partner email addresses during the initial setup wizard.
4. **Help and Support**
Provide additional support resources for your partners, such as a help center URL or terms and conditions link, to ensure they have all the information they need.
5. **Review and Create**
Inspect your program summary on the overview screen. Once you are satisfied with your settings, click **Create program** to finalize the setup and publish your program.
---
### Key Concepts
* **Program Domain:** A dedicated custom domain or subdomain used exclusively for your short links and affiliate program pages.
* **Reward Types:** The qualifying event that triggers a partner payout. You can reward partners based on **lead** generation or completed **sale** conversions.
* **Commission Structure:** How long and how often a partner continues earning commissions. **One-off** rewards apply to the initial transaction, while **recurring** rewards continue for a specified duration or a customer's lifetime.
* **Partner Group:** A collection of partners who share common reward settings and referral link configurations. A default group is automatically created when you launch a program.
---
### Summary Configuration Options
| Step | Configuration Option | Description |
| :--- | :--- | :--- |
| Getting Started | Company Name | The public name of your company and program. |
| Getting Started | Logo | A square brand logo used throughout your partner program. |
| Getting Started | Destination URL | The website URL where users are redirected when clicking referral links. |
| Getting Started | Support Email | The contact email displayed to partners on their dashboard. |
| Configure Rewards | Reward Type | Choose whether partners earn rewards per **lead** or per **sale**. |
| Configure Rewards | Commission Structure | Choose between **one-off** payouts or **recurring** revenue shares. |
| Configure Rewards | Reward Amount | Set the payout value as a flat cash amount or a percentage rate. |
---
### Tips for Success
> [!TIP]
> After launching your program, make sure to set up conversion tracking on your website (such as installing tracking scripts or connecting platforms like Shopify) so that partner clicks, leads, and sales are measured accurately.
> [!WARNING]
> Ensure your billing plan supports partner management before starting the wizard; legacy business plans or lower tiers without program capabilities will prompt you to upgrade your subscription.
## Related
- [Affiliate Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs)
- [Payouts and Commissions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/payouts-and-commissions)
---
## User guide: Payouts and Commissions
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/payouts-and-commissions
## Overview
The Payouts and Commissions feature manages affiliate earnings, partner invoices, and financial distributions. It handles the complete lifecycle of commission payouts—from approval and invoicing to multi-channel distribution—supporting multiple payout providers including Stripe, PayPal, and Stablecoin.
```mermaid
flowchart TD
A[Partner Earns Commission] --> B[Holding Period & Approval]
B --> C[Invoice Generation & Processing]
C --> D[Payout Sent via Stripe, PayPal, or Stablecoin]
D --> E[Status Updated to Completed]
```
---
## Payout Methods
Partners can receive earnings through several supported payout methods, each with specific processing times and requirements.
Supported payout providers: `connect` (Bank Account), `stablecoin` (USDC Crypto Wallet), `paypal` (PayPal), `tremendous` (Gift Card)
Sources: `apps/web/ui/partners/payouts/payout-method-config.ts`, `apps/web/lib/constants/payouts.ts`
| Method ID | Title | Description & Processing Time |
| :--- | :--- | :--- |
| `connect` | Bank Account | Paid in local currency; deposited in 2-5 business days via Stripe Connect. Local bank account required. |
| `stablecoin` | Stablecoin | Paid in USDC with a `0.5%` payout fee; deposited in minutes. No local bank account required. |
| `paypal` | PayPal | Paid in local currency with a `3%` FX fee; deposited in 5-10 business days. |
| `tremendous` | Gift Card | Delivered via gift card email; typically arrives in minutes. |
> [!NOTE]
> Stablecoin payouts incur a `0.5%` fee rate and a fixed `0.50` USD fee per transaction to cover network transfer costs.
---
## Approving Commissions and Processing Payouts
### Reviewing and Confirming Payouts
Workspace administrators can review eligible partner commissions and generate invoices to fund payouts by following these steps:
1. **Review Eligible Payouts:** Navigate to the payouts dashboard within your workspace to view accumulated partner commissions that have cleared the program's holding period.
2. **Configure Payout Parameters:** Select the payouts you want to include, choose your payment method, and set optional cutoff periods.
3. **Confirm and Process:** Confirm the payout batch to generate an invoice. The system validates payment details, calculates applicable payout fees, and creates a payment intent to fund the transfers.
> [!WARNING]
> If an invoice includes external payouts, you must have an active webhook subscribed to the `payout.confirmed` event before proceeding, otherwise the request will be rejected.
---
## Handling Refunds and Adjustments
When customer payments are refunded or disputed, associated commission statuses and balances are automatically adjusted to reflect the change in funds.
- **Holding Periods:** Payouts remain in a `pending` status during the program's holding period (options include `0`, `7`, `14`, `30`, `60`, or `90` days) to account for potential refunds.
- **Failed Charges:** If an invoice payment fails or is reversed before funds settle, automated cron jobs pause payout distribution to prevent advancing uncollected funds.
---
## Issuing Invoices
Invoices are automatically generated when a payout batch is confirmed.
- **Invoices for Programs:** Workspace administrators can view invoice summaries detailing total payout amounts, platform fees, and net charges.
- **Invoices for Partners:** Partners can view and download individualized PDF invoices for completed payouts directly from their partner dashboard (`/invoices/[payoutId]`). These documents include program details, payout amounts, transaction reference numbers, and applicable VAT or GST reverse-charge notices for international partners (such as EU countries or Australia).
---
## Sending Payouts via Stripe, PayPal, or Stablecoin
Once an invoice charge succeeds, the system automatically routes funds through the partner's designated payout method:
- **Stripe Transfers (`connect`):** Funds are transferred directly to the partner's connected Stripe account. For card payments, source transaction references are included to handle fast settlements.
- **PayPal Payouts (`paypal`):** Payout items are batched and sent via PayPal's batch payout API to the partner's registered PayPal email.
- **Stablecoin Payouts (`stablecoin`):** Dub funds its internal financial account, deducts the `0.5%` stablecoin fee, and transfers USDC directly to the partner's connected crypto wallet via Stripe's recipient crypto capabilities.
> [!TIP]
> If a partner's payout amount falls below the minimum withdrawal threshold of `$10.00`, the payout is marked as `processed` and held for up to 90 days. Partners can manually trigger an instant withdrawal by selecting **"Pay out now"** on their dashboard, which incurs a small withdrawal fee of `$0.50`.
## Related
- [Launching Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/launching-partner-programs)
- [Affiliate Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs)
---
## User guide: Importing and Migrating
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/importing-and-migrating
## Overview
The importing and migrating tools allow you to seamlessly transition your existing short links, custom domains, tags, and affiliate program data into your workspace. Instead of recreating everything manually, you can automatically pull in historical data from external services like Bitly, Short.io, Rebrandly, and Rewardful.
---
## Supported Import Providers
You can import links, tags, and affiliate information from several third-party platforms.
| Provider | Supported Data Types | Import Mechanism |
| :--- | :--- | :--- |
| **Bitly** | Links, Groups, Tags, Custom Domains | OAuth or API Token / Background Queue |
| **Short.io** | Links, Tags, Custom Domains | API Token / Background Queue |
| **Rebrandly** | Links, Tags, Custom Domains | API Token / Background Queue |
| **Rewardful** | Campaigns, Affiliates, Affiliate Coupons, Customers, Commissions | Automated API Importer |
---
## Importing Links and Domains
### 1. Open the Import Menu
Navigate to your workspace links page in the dashboard, click the three-dot options menu, and select your source platform under the **Import Links** section.
### 2. Connect Your Account
Provide your access credentials for the chosen provider when prompted:
* **Bitly:** Authenticate securely using the OAuth connection flow.
* **Short.io & Rebrandly:** Paste your account API key or access token into the input field to connect.
### 3. Select Domains and Options
Once connected, the system displays a list of available domains and associated link counts found in your external account.
1. Toggle the checkboxes next to the domains you want to bring over.
2. Choose whether to import your existing tags by enabling the **Import all tags?** toggle.
3. Click **Confirm import** to queue the migration process.
> [!NOTE]
> Large imports run in the background. You can safely navigate away from the page while your data is processed, and you will receive an email notification as soon as the import completes.
---
## Migrating Affiliate Programs and Data
### Affiliate Migration Workflow
```mermaid
flowchart TD
A[Start Import] --> B[Import Campaigns & Groups]
B --> C[Import Partners & Create Links]
C --> D[Import Customers & Affiliate Coupons]
D --> E[Backfill Historical Commissions]
```
### Key Concepts to Know
* **Program Enrollments:** When importing partners from external affiliate platforms, the system automatically creates partner profiles and enrolls them into your workspace program.
* **Commission Deduplication:** During commission imports, the system cross-references existing Stripe customer records and transaction timestamps to prevent duplicate entries if a transaction was already tracked.
* **Clawbacks and Adjustments:** Complex historical adjustments (such as handling commissions paid out to incorrect partners during a transition period) utilize automated dummy records and clawbacks to balance financial books safely.
## Related
- [Managing Short Links](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/managing-short-links)
- [Custom Domains Setup](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/configuration/custom-domains-setup)
---
## User guide: Partner Portal Guide
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/partner-portal-guide
## Overview
The Partner Portal is an online hub where affiliates and partners can apply to programs, retrieve their referral links, monitor performance metrics, and submit bounty proofs. This guide explains how to navigate these features to manage your partnership activities effectively.
```mermaid
flowchart TD
A[Partner Sign In] --> B[Browse Marketplace / Programs]
B --> C[Apply to Program]
C --> D[Get Referral Link]
D --> E[Track Earnings & Stats]
E --> F[View & Submit Bounties]
```
---
## Applying to Programs
To earn commissions, you must first apply to join a partner program.
1. Navigate to the **Marketplace** or your **Programs** tab from the sidebar.
2. Select a program you wish to join to view its details, rewards, and requirements.
3. Click **Apply** to open the application form.
4. Fill out any requested information and submit your application for review.
> [!NOTE]
> You may need to complete your partner profile checklist before your application can be submitted for review.
---
## Finding and Using Referral Links
Once your application is approved, the portal provides unique referral links that attribute traffic and sales back to your account.
1. Open your enrolled program from the program dropdown in the sidebar.
2. Go to your program dashboard or **Links** section.
3. Locate your primary referral link or secondary links.
4. Click **Copy link** to copy the URL to your clipboard.
> [!TIP]
> You can also append `?via=your_username` to any page URL on the host domain to create a custom referral link on the fly.
---
## Tracking Earnings and Performance
### Key Performance Metrics
The partner dashboard provides real-time statistics regarding your promotional activity and compensation.
* **Clicks:** The number of times users have clicked your referral links.
* **Leads:** The number of prospective sign-ups or registered users generated through your links.
* **Sales:** The total number of completed customer purchases or conversions.
* **Revenue:** The gross monetary value of sales driven by your referrals.
* **Earnings:** Your total earned commissions across the program.
You can view these statistics over custom time intervals using the date range picker on your program overview page.
---
## Submitting Bounty Proofs
Some programs offer performance or submission-based bounties to reward you for hitting specific goals.
1. Navigate to the **Bounties** section of your program.
2. Click on an available bounty card to open its detail view.
3. Review the reward criteria and submission requirements.
4. For submission-based bounties, provide any necessary proof or identifier details for your active period and submit them for review.
## Related
- [Affiliate Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs)
- [Payouts and Commissions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/payouts-and-commissions)
---
## User guide: Custom Domains Setup
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/configuration/custom-domains-setup
## Overview
### Introduction
Custom domains allow you to brand your shortened links and email communications with your own domain name (such as `go.yourcompany.com`) rather than using default platform links. Connecting a custom domain increases trust, improves click-through rates, and creates a professional experience for your audience.
You can connect custom domains for two main purposes in your workspace:
- **Short Links Domains:** Dedicate a custom domain or subdomain exclusively for creating and tracking shortened links and affiliate programs.
- **Email Domains:** Connect a custom domain for branded partner communications and email campaigns (available on Advanced plans and higher).
---
### Connecting a Custom Domain for Short Links
To connect a custom domain you own for your shortened links, follow these steps:
1. Navigate to your workspace settings and select **Domains**.
2. Click **Add custom domain** and choose **Connect a domain you own**.
3. Enter your domain name (for example, `go.yourcompany.com` or your apex domain like `yourcompany.com`).
4. Configure the required DNS records provided in your dashboard at your domain provider (DNS registrar).
- For an **Apex Domain** (e.g., `yourcompany.com`), configure an **A Record** pointing to `76.76.21.21`.
- For a **Subdomain** (e.g., `go.yourcompany.com`), configure a **CNAME Record** pointing to `cname.dub.co`.
5. Once your DNS records are added, the system automatically checks and verifies your domain configuration.
> [!TIP]
> If you use Vercel or Cloudflare as your DNS provider, you may see an option to **Auto configure** using Domain Connect, which securely applies the necessary DNS records automatically with a single click.
---
### Connecting an Email Domain
If your workspace is on an Advanced plan or higher, you can connect a custom email domain to send branded communications and affiliate email campaigns.
1. Navigate to your workspace settings and select **Domains**, then open the **Email** tab.
2. Click **Add domain** and enter the email domain you wish to use.
3. Configure the required **DKIM** and **SPF** records provided in your dashboard with your DNS provider to authorize email sending.
4. Optionally, add a **DMARC** record (`_dmarc` with value `v=DMARC1; p=none;`) to protect against email spoofing and build domain trust.
5. Once verified, you can begin sending branded email campaigns directly from your domain.
> [!WARNING]
> Each program can have only one active email domain. You cannot delete or update an email domain while there are active email campaigns using it; you must pause or complete those campaigns first.
---
### Key Concepts
Review these terms to better understand how domain management works:
- **Apex Domain:** The root domain without any subdomains, such as `yourcompany.com`.
- **Subdomain:** A prefix added to your main domain, such as `go.yourcompany.com` or `links.yourcompany.com`. Subdomains are recommended for short links so your main website remains unaffected.
- **DNS Records:** Settings at your domain registrar that tell the internet where to direct traffic for your web pages and emails. Key types include:
- **A Record:** Points an apex domain to an IP address.
- **CNAME Record:** Maps a subdomain to another domain name.
- **TXT Record:** Used for ownership verification and security protocols like SPF and DMARC.
- **Domain Connect:** An open standard protocol supported by select providers (such as Vercel and Cloudflare) that automates DNS configuration securely.
---
### Alternative Domain Options
If you do not want to connect your own external domain right away, alternative domain options are available depending on your plan:
- **.dub.link Subdomains:** Available for quick testing and onboarding, allowing you to launch instantly using a managed subdomain.
- **Free .link Domains:** Paid accounts may be eligible to claim a free `.link` domain for one year directly through the dashboard.
- **Default Branded Domains:** Workspaces can leverage pre-configured default shortcut domains for specific platforms.
| Feature / Option | Availability | Purpose |
| :--- | :--- | :--- |
| **Custom Domains** | All plans (limits apply) | Brand short links with your own custom domain name |
| **Email Domains** | Advanced & Enterprise plans | Send branded email campaigns and partner communications |
| **Free .link Domain** | Paid plans | Claim a complimentary `.link` domain for one year |
| **Default Domains** | Pro plan and above | Leverage built-in branded shortcut domains |
---
### Troubleshooting Verification Issues
If your custom domain shows a status other than **Valid Configuration**, review the following common states:
- **Pending Verification:** DNS changes can take anywhere from a few minutes up to 24 hours to propagate globally across the internet. Ensure your DNS records match the exact values shown in your settings.
- **Conflicting DNS Records:** If your domain currently points to an existing website or has conflicting records, remove the conflicting records from your DNS provider before adding the required Dub records.
- **Invalid Configuration:** If a domain remains unverified or misconfigured for an extended period, the system will send reminder notifications. Domains that remain invalid for more than 30 days are automatically removed from the workspace.
## Related
- [Managing Short Links](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/managing-short-links)
- [Troubleshooting and FAQ](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/troubleshooting/troubleshooting-and-faq)
---
## User guide: Workspace Security Settings
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/configuration/workspace-security-settings
## Overview
The Workspace Security Settings page allows administrators and team members with appropriate permissions to manage advanced authentication, risk monitoring, and compliance for their workspace. This includes setting up Single Sign-On (SSO) via SAML, configuring identity provider directory sync using SCIM, managing fraud prevention rules to protect partner programs, and exporting security audit logs.
> [!NOTE]
> Most security features, such as SAML Single Sign-On, SCIM Directory Sync, and audit log exports, are exclusively available on the **Enterprise Plan**. Fraud rules require an **Advanced** or **Enterprise Plan**.
---
## Configuring SAML Single Sign-On (SSO)
### SAML Overview
SAML Single Sign-On allows your team members to sign in to your workspace using your corporate identity provider.
### How to Configure SAML SSO
1. Navigate to your workspace **Settings** and select **Security**.
2. Under the **SAML Single Sign-On** section, click **Configure**.
3. Choose your identity provider from the dropdown menu.
4. Provide the required connection details:
- For most providers, paste the URL to your identity provider's metadata (`metadataUrl`).
- For Google, upload your metadata XML file (`encodedRawMetadata`).
5. Click **Save changes** to complete the configuration.
> [!IMPORTANT]
> You must be logged into your workspace using your organization’s work email address to configure SAML SSO. Generic email domains cannot be used for SAML configuration.
---
## Managing Fraud Prevention Rules
### Risk Rules Overview
Workspace administrators can set up and customize risk rules to detect and prevent fraudulent activity within partner programs.
### Configuring Risk Rules
1. Open your workspace risk management or program settings and open the **Risk rules** configuration sheet.
2. Review the available risk rules and toggle them on or off as needed.
3. For rules that support advanced settings, customize parameters such as whitelisted campaign IDs or banned domains.
4. Click **Save** to apply your changes.
> [!WARNING]
> Disabling certain risk rules may trigger automatic resolution of pending fraud events and release held commissions. A confirmation prompt will appear if any active rules are being turned off.
---
## Viewing and Exporting Audit Logs
### Audit Log Overview
Audit logs maintain a history of workspace events, partner activities, and payout records for compliance and security reviews.
### Exporting Audit Logs
1. Go to your workspace **Security** settings page and locate the **Audit Logs** section.
2. Select your desired date range using the date picker.
3. Click **Export CSV** to download your audit log report.
---
## Key Concepts
* **Single Sign-On (SSO):** An authentication method that allows users to securely log in to multiple applications using a single set of credentials provided by an identity provider.
* **SCIM Directory Sync:** An automated protocol used to provision and deprovision users from your identity provider directly into your workspace.
* **Audit Logs:** A chronological record of security-related events and workspace activity used for compliance tracking.
* **Fraud Prevention Rules:** Automated checks designed to detect suspicious referral traffic, duplicate accounts, and fraudulent customer email matches.
## Related
- [Account and Workspaces](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/getting-started/account-and-workspaces)
- [Troubleshooting and FAQ](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/troubleshooting/troubleshooting-and-faq)
---
## User guide: Connecting Third-Party Tools
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/integrations/connecting-third-party-tools
## Overview
Connecting third-Party tools allows you to sync your marketing analytics, leads, and sales data seamlessly between Dub and your favorite external platforms. By integrating payment providers, Customer Relationship Management (CRM) tools, and ad platforms, you gain end-to-end visibility into your marketing funnel—tracking traffic from initial click all the way to final revenue and partner commissions.
Dub supports integrations across several categories, including payment processing, customer management, authentication, scheduling, and analytics.
```mermaid
flowchart TD
A[Visitor Clicks Dub Link] --> B[External Tool / Storefront]
B --> C[Dub Receives Conversion Event]
C --> D[Analytics, Revenue & Commissions Updated]
```
---
## Supported Third-Party Integrations
Dub offers built-in integrations with a variety of industry-leading tools to help automate your conversion tracking and partner workflows.
| Integration Name | Category | Description |
| :--- | :--- | :--- |
| **Stripe** | Payments | Track sales, subscriptions, free trials, and customer data via Checkout, Payment Links, or Customer events. |
| **Shopify** | Payments | Real-time conversion tracking for Shopify e-commerce stores, measuring sales, customer value, and ROI. |
| **HubSpot** | Scheduling / CRM | Bidirectional sync for contacts and deal changes, supporting HubSpot Forms, Meeting Scheduler, and Closed Won deals. |
| **Google Ads** | Analytics | Upload offline click conversions to Google Ads to optimize ad performance. |
| **Google Tag Manager** | Analytics | Track client-side lead and conversion events using Google Tag Manager. |
| **Segment** | Analytics | Send lead and sale conversion events directly through your Segment data pipeline. |
| **Slack** | Productivity | Receive notifications and updates directly inside your team channels. |
| **Zapier** | Automation | Connect Dub to thousands of other web services using automated workflows. |
| **AppsFlyer** | Analytics | Listen to Postback events from AppsFlyer to track mobile app leads and sales. |
| **Singular** | Analytics | Track mobile attribution and postback conversion events. |
| **Supabase** | Authentication | Track user signup events with Dub Conversions. |
| **Clerk** | Authentication | Track user authentication and signups for conversion attribution. |
| **Auth0** | Authentication | Monitor user identity signups and sync them as lead events. |
| **Better Auth** | Authentication | Sync user registrations directly into your Dub analytics funnel. |
| **NextAuth.js** | Authentication | Automatically track user signups using built-in session triggers. |
| **Appwrite** | Authentication | Track signup and authentication events within your database platform. |
| **Cal.com** | Scheduling | Track scheduling and booking conversion events. |
| **Typefully** | Social Media | Automatically shorten social links created on Typefully using Dub. |
> [!NOTE]
> Supported integrations: Stripe, Shopify, HubSpot, Google Ads, Google Tag Manager, Segment, Slack, Zapier, AppsFlyer, Singular, Supabase, Clerk, Auth0, Better Auth, NextAuth.js, Appwrite, Cal.com, Typefully.
> Sources: `apps/web/scripts/dev/data.json`, `apps/web/ui/guides/integrations.ts`, `apps/web/app/(ee)/api/appsflyer/webhook/route.ts`, `apps/web/app/(ee)/api/singular/webhook/route.ts`, `apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx`, `packages/utils/src/constants/integrations.ts`.
---
## Connecting an Integration
To connect and configure a third-party tool within your Dub workspace, follow these general steps:
1. Log in to your Dub dashboard and navigate to your workspace settings.
2. Select **Integrations** from the settings menu to view the list of available tools.
3. Locate the provider you wish to connect (such as Stripe, Shopify, or HubSpot) and click on it.
4. Follow the on-screen instructions to authorize the connection, enter your required credentials or store identifiers, and save your settings.
> [!TIP]
> For advanced integrations like Google Ads or specific CRM configurations, make sure you have workspace owner permissions to successfully authorize and install the application.
## Related
- [Affiliate Partner Programs](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/core-features/affiliate-partner-programs)
- [Payouts and Commissions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/payouts-and-commissions)
---
## User guide: Troubleshooting and FAQ
URL: https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/troubleshooting/troubleshooting-and-faq
## Overview
This guide helps you diagnose and resolve common issues you might encounter while using the application, including domain verification errors, failed partner payouts, tracking installation problems, and login or authorization challenges.
Use the sections below to find step-by-step troubleshooting instructions for each scenario.
---
## Domain Verification Errors
### Understanding Domain Verification Issues
When adding a custom domain to your workspace, you may occasionally run into verification issues due to incorrect DNS records, conflicts, or missing configurations.
### Common Domain Errors and Their Meanings
| Status / Error Code | Description | Resolution Steps |
| :--- | :--- | :--- |
| **Domain Not Found** | The domain has not been added to your project or DNS configuration properly. | Check that you entered the correct domain name and that it points to your project. |
| **Conflicting DNS Records** | Existing DNS records (such as an old A or CNAME record) are conflicting with the required configuration. | Remove the conflicting records from your DNS provider, then set the recommended `A` or `CNAME` record. |
| **Invalid Configuration** | The domain's DNS records do not match the expected values. | Verify your DNS provider settings against the required `A`, `CNAME`, or `TXT` verification values provided in your dashboard. |
| **Unknown Error** | An unexpected error occurred while communicating with the domain registrar or DNS management service. | Wait a few minutes and try verifying again. If the issue persists, contact support. |
> [!WARNING]
> If a domain remains invalid for more than 14 or 28 days, reminder emails will be sent to workspace owners. If a domain remains unverified for more than 30 days and has no active link clicks, it may be automatically deleted from the database.
---
## Failed Payouts
### Understanding Payout Failures
Partner payouts can occasionally fail due to issues with payment methods, authentication requirements, or insufficient billing details. When a partner payout fails, the affected payouts are automatically reverted back to a **Pending** status, and you will receive a notification email detailing the failure reason. If applicable, a payment failure fee may be charged to your card to cover processing costs.
### Resolving Payout Failures
1. Open your workspace settings and navigate to your billing or payment methods page to update your card or direct debit details.
2. Go to your program's **Payouts** tab.
3. Review the pending payouts and click **Retry payout** or **Confirm all payouts** once your payment details have been updated.
> [!TIP]
> You can press the `C` key as a keyboard shortcut while viewing the payouts page to quickly open the confirmation sheet for pending payouts.
---
## Tracking Discrepancies and Installation Issues
### Understanding Tracking Installation Errors
If your analytics or conversion tracking script is not working correctly, you can verify your installation directly from your workspace settings. When you use the **Verify installation** tool in your tracking settings, you may encounter specific error codes that explain why the script cannot be validated.
### Troubleshooting Installation Error Codes
- **Script is not installed (`not_installed`):** The tracking script could not be found on the specified hostname. Ensure the script tag is added to your website's HTML header.
- **Script missing attributes (`missing_attributes`):** The conversion tracking script is missing required attributes, such as a publishable key or SDK name.
- **Script is missing the referral link domain (`missing_refer_domain`):** The tracking script needs to specify the correct referral link domain attribute.
- **Duplicate script (`duplicate`):** More than one tracking script tag was detected on the page. Remove all but one valid script tag.
- **Malformed script (`malformed`):** The script tag is improperly formatted or missing required source attributes.
- **We couldn’t reach this hostname (`unreachable`):** The system was unable to establish a connection to your hostname. Check that your website is live and publicly accessible.
- **Wildcard hostnames can’t be verified (`unsupported`):** Wildcard hostnames (starting with `*.`) cannot be automatically verified. Please select a specific subdomain or apex domain.
```mermaid
flowchart TD
A[Select Hostname] --> B[Click Verify Installation]
B --> C{Result Status?}
C -->|Success| D[Connected and Ready]
C -->|Error| E[Review Error Headline & Fix Script]
E --> B
```
> [!IMPORTANT]
> Make sure your tracking script includes your correct publishable key and matches your active website domain.
---
## Login and Authorization Issues
### Understanding Access and Authorization Challenges
If you or your partners encounter issues accessing the application or partner portal, review the common error messages and resolution steps outlined below to restore access.
### Authentication Error Reference
| Error Code / Message | Meaning | Resolution |
| :--- | :--- | :--- |
| **Unauthorized** | You are not logged in or your session has expired. | Log in to your account at the appropriate portal URL to continue. |
| **Partner profile not found** | Your partner account does not exist or was not found. | Complete the partner onboarding flow to create your profile. |
| **Invalid or expired state** | The security state token for authentication or connection has expired. | Restart the login or connection process from the beginning. |
| **PayPal email address is not verified** | Your connected PayPal account has an unverified email address. | Log in to PayPal, verify your email address, and try reconnecting. |
| **The PayPal account you're trying to connect is already in use** | The PayPal account is linked to another partner profile. | Use a different PayPal account that is not currently tied to another partner. |
> [!TIP]
> If you experience persistent session issues, try clearing your browser cookies and cache, or log in using an incognito window.
## Related
- [Custom Domains Setup](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/configuration/custom-domains-setup)
- [Payouts and Commissions](https://www.doc0.dev/docs/934e554a-e6a1-476f-bb2f-23e62d86c3fd/guide/how-to-guides/payouts-and-commissions)
---