Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add cursor based pagination to Links, Customers, and Commissions (#3184)

Kiran K8de071b3b92d
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
index bde9833b4c..109094f523 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
@@ -22,8 +22,15 @@ export const GET = withWorkspace(
},
});
- const { status, groupId, partnerId, sortOrder, sortBy, page, pageSize } =
- getBountySubmissionsQuerySchema.parse(searchParams);
+ const {
+ status,
+ groupId,
+ partnerId,
+ sortOrder,
+ sortBy,
+ page = 1,
+ pageSize,
+ } = getBountySubmissionsQuerySchema.parse(searchParams);
const submissions = await prisma.bountySubmission.findMany({
where: {
diff --git a/apps/web/app/(ee)/api/campaigns/route.ts b/apps/web/app/(ee)/api/campaigns/route.ts
index d47c324170..d06ae6539e 100644
--- a/apps/web/app/(ee)/api/campaigns/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/route.ts
@@ -22,8 +22,14 @@ export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const { type, status, search, triggerCondition, page, pageSize } =
- getCampaignsQuerySchema.parse(searchParams);
+ const {
+ type,
+ status,
+ search,
+ triggerCondition,
+ page = 1,
+ pageSize,
+ } = getCampaignsQuerySchema.parse(searchParams);
const campaigns = await prisma.campaign.findMany({
where: {
diff --git a/apps/web/app/(ee)/api/fraud/events/route.ts b/apps/web/app/(ee)/api/fraud/events/route.ts
index 1d1f4d7d89..0eb527c3e4 100644
--- a/apps/web/app/(ee)/api/fraud/events/route.ts
+++ b/apps/web/app/(ee)/api/fraud/events/route.ts
@@ -14,8 +14,11 @@ import * as z from "zod/v4";
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const { page, pageSize, ...queryParams } =
- fraudEventQuerySchema.parse(searchParams);
+ const {
+ page = 1,
+ pageSize,
+ ...queryParams
+ } = fraudEventQuerySchema.parse(searchParams);
let where: Prisma.FraudEventWhereInput = {};
let eventGroupType: FraudRuleType | undefined;
diff --git a/apps/web/app/(ee)/api/fraud/groups/route.ts b/apps/web/app/(ee)/api/fraud/groups/route.ts
index 1cf57d130f..5a77ff2d0d 100644
--- a/apps/web/app/(ee)/api/fraud/groups/route.ts
+++ b/apps/web/app/(ee)/api/fraud/groups/route.ts
@@ -18,7 +18,7 @@ export const GET = withWorkspace(
type,
partnerId,
groupId,
- page,
+ page = 1,
pageSize,
sortBy,
sortOrder,
diff --git a/apps/web/app/(ee)/api/network/programs/route.ts b/apps/web/app/(ee)/api/network/programs/route.ts
index bdcddb69fc..561be8670b 100644
--- a/apps/web/app/(ee)/api/network/programs/route.ts
+++ b/apps/web/app/(ee)/api/network/programs/route.ts
@@ -18,7 +18,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
status,
sortBy,
sortOrder,
- page,
+ page = 1,
pageSize,
} = getNetworkProgramsQuerySchema.parse(searchParams);
diff --git a/apps/web/app/(ee)/api/partner-profile/payouts/route.ts b/apps/web/app/(ee)/api/partner-profile/payouts/route.ts
index a3ffa3bd9c..f952ef9288 100644
--- a/apps/web/app/(ee)/api/partner-profile/payouts/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/payouts/route.ts
@@ -8,8 +8,14 @@ import * as z from "zod/v4";
// GET /api/partner-profile/payouts - get all payouts for a partner
export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
- const { programId, status, sortBy, sortOrder, page, pageSize } =
- partnerProfilePayoutsQuerySchema.parse(searchParams);
+ const {
+ programId,
+ status,
+ sortBy,
+ sortOrder,
+ page = 1,
+ pageSize,
+ } = partnerProfilePayoutsQuerySchema.parse(searchParams);
const payouts = await prisma.payout.findMany({
where: {
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts
index 7f9f3f9e2b..972dc2be0d 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts
@@ -22,8 +22,15 @@ import * as z from "zod/v4";
export const GET = withPartnerProfile(
async ({ partner, params, searchParams }) => {
const { programId } = params;
- const { search, country, linkId, sortBy, sortOrder, page, pageSize } =
- getPartnerCustomersQuerySchema.parse(searchParams);
+ const {
+ search,
+ country,
+ linkId,
+ sortBy,
+ sortOrder,
+ page = 1,
+ pageSize,
+ } = getPartnerCustomersQuerySchema.parse(searchParams);
const { program, totalCommissions, customerDataSharingEnabledAt } =
await getProgramEnrollmentOrThrow({
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts
index be08c0dae2..30d94badaf 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts
@@ -24,7 +24,7 @@ export const GET = withPartnerProfile(
});
const {
- page,
+ page = 1,
pageSize,
type,
status,
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts
index 68a9dd62d9..263eaa1c31 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts
@@ -12,8 +12,12 @@ import * as z from "zod/v4";
export const GET = withPartnerProfile(
async ({ partner, params, searchParams }) => {
const { programId } = params;
- const { status, search, page, pageSize } =
- getPartnerReferralsQuerySchema.parse(searchParams);
+ const {
+ status,
+ search,
+ page = 1,
+ pageSize,
+ } = getPartnerReferralsQuerySchema.parse(searchParams);
const { program } = await getProgramEnrollmentOrThrow({
partnerId: partner.id,
diff --git a/apps/web/app/(ee)/api/payouts/route.ts b/apps/web/app/(ee)/api/payouts/route.ts
index 7cbc854854..4303e76179 100644
--- a/apps/web/app/(ee)/api/payouts/route.ts
+++ b/apps/web/app/(ee)/api/payouts/route.ts
@@ -26,7 +26,7 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
invoiceId,
sortBy,
sortOrder,
- page,
+ page = 1,
pageSize,
} = payoutsQuerySchema.parse(isHoldStatus ? restSearchParams : searchParams);
diff --git a/apps/web/app/(ee)/api/programs/[programId]/referrals/route.ts b/apps/web/app/(ee)/api/programs/[programId]/referrals/route.ts
index 2e9d2d06b8..80dbcf34df 100644
--- a/apps/web/app/(ee)/api/programs/[programId]/referrals/route.ts
+++ b/apps/web/app/(ee)/api/programs/[programId]/referrals/route.ts
@@ -14,8 +14,13 @@ export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const { partnerId, status, search, page, pageSize } =
- getPartnerReferralsQuerySchema.parse(searchParams);
+ const {
+ partnerId,
+ status,
+ search,
+ page = 1,
+ pageSize,
+ } = getPartnerReferralsQuerySchema.parse(searchParams);
const partnerReferrals = await prisma.partnerReferral.findMany({
where: {
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx
index d1bd610602..022e630bf7 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx
@@ -292,7 +292,12 @@ export function ProgramCustomersPageClient() {
resourceName: (p) => `customer${p ? "s" : ""}`,
rowCount: customersCount || 0,
loading: isLoading,
- error: error || countError ? "Failed to load customers" : undefined,
+ error:
+ error instanceof Error
+ ? error.message
+ : countError
+ ? "Failed to load customers"
+ : undefined,
});
return (
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 4374160882..2710f6dc25 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -21,8 +21,13 @@ import { NextResponse } from "next/server";
// GET /api/domains – get all domains for a workspace
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
- const { search, archived, page, pageSize, includeLink } =
- getDomainsQuerySchemaExtended.parse(searchParams);
+ const {
+ search,
+ archived,
+ page = 1,
+ pageSize,
+ includeLink,
+ } = getDomainsQuerySchemaExtended.parse(searchParams);
const domains = await prisma.domain.findMany({
where: {
diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.ts
index 2c720c74ee..9aa8bf72e4 100644
--- a/apps/web/app/api/tags/route.ts
+++ b/apps/web/app/api/tags/route.ts
@@ -19,7 +19,7 @@ export const GET = withWorkspace(
ids,
sortBy,
sortOrder,
- page,
+ page = 1,
pageSize,
includeLinksCount,
} = getTagsQuerySchemaExtended.parse(searchParams);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commissions-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commissions-table.tsx
index 2026f3983f..9e5a09332e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commissions-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commissions-table.tsx
@@ -362,7 +362,11 @@ export function CommissionsTable() {
commissions?.length ??
0,
loading: isLoading,
- error: error ? "Failed to load commissions" : undefined,
+ error: error
+ ? error instanceof Error
+ ? error.message
+ : "Failed to load commissions"
+ : undefined,
});
return (
diff --git a/apps/web/lib/api/campaigns/get-campaign-events.ts b/apps/web/lib/api/campaigns/get-campaign-events.ts
index 4c05a35e39..0df52c6cce 100644
--- a/apps/web/lib/api/campaigns/get-campaign-events.ts
+++ b/apps/web/lib/api/campaigns/get-campaign-events.ts
@@ -13,7 +13,7 @@ interface GetCampaignEventsParams
export const getCampaignEvents = async ({
campaignId,
status,
- page,
+ page = 1,
pageSize,
search,
}: GetCampaignEventsParams) => {
diff --git a/apps/web/lib/api/commissions/get-commissions.ts b/apps/web/lib/api/commissions/get-commissions.ts
index 3193383408..ac87b87565 100644
--- a/apps/web/lib/api/commissions/get-commissions.ts
+++ b/apps/web/lib/api/commissions/get-commissions.ts
@@ -3,6 +3,8 @@ import { getCommissionsQuerySchema } from "@/lib/zod/schemas/commissions";
import { prisma } from "@dub/prisma";
import { CommissionStatus, FraudEventStatus } from "@dub/prisma/client";
import * as z from "zod/v4";
+import { DubApiError } from "../errors";
+import { buildPaginationQuery } from "../pagination";
type CommissionsFilters = z.infer<typeof getCommissionsQuerySchema> & {
programId: string;
@@ -23,13 +25,35 @@ export async function getCommissions(filters: CommissionsFilters) {
end,
interval,
timezone,
- page,
- pageSize,
- sortBy,
- sortOrder,
isHoldStatus,
+ startingAfter,
+ endingBefore,
} = filters;
+ 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,
+ },
+ });
+
+ if (!commission || commission.programId !== programId) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Invalid cursor: the provided ID does not exist.",
+ });
+ }
+ }
+
const { startDate, endDate } = getStartEndDates({
interval,
start,
@@ -87,8 +111,6 @@ export async function getCommissions(filters: CommissionsFilters) {
partner: true,
programEnrollment: true,
},
- skip: (page - 1) * pageSize,
- take: pageSize,
- orderBy: { [sortBy]: sortOrder },
+ ...paginationQuery,
});
}
diff --git a/apps/web/lib/api/groups/get-groups.ts b/apps/web/lib/api/groups/get-groups.ts
index a522d10649..2436af2980 100644
--- a/apps/web/lib/api/groups/get-groups.ts
+++ b/apps/web/lib/api/groups/get-groups.ts
@@ -11,7 +11,7 @@ export async function getGroups(filters: GroupFilters) {
const {
search,
groupIds,
- page,
+ page = 1,
pageSize,
sortBy,
sortOrder,
diff --git a/apps/web/lib/api/links/get-links-for-workspace.ts b/apps/web/lib/api/links/get-links-for-workspace.ts
index 37196606e0..e0a25ae9dc 100644
--- a/apps/web/lib/api/links/get-links-for-workspace.ts
+++ b/apps/web/lib/api/links/get-links-for-workspace.ts
@@ -1,6 +1,8 @@
import { getLinksQuerySchemaExtended } from "@/lib/zod/schemas/links";
import { prisma } from "@dub/prisma";
import * as z from "zod/v4";
+import { DubApiError } from "../errors";
+import { buildPaginationQuery } from "../pagination";
import { combineTagIds } from "../tags/combine-tag-ids";
import { encodeKeyIfCaseSensitive } from "./case-sensitivity";
import { transformLink } from "./utils";
@@ -13,40 +15,62 @@ export interface GetLinksForWorkspaceProps
endDate?: Date;
}
-export async function getLinksForWorkspace({
- workspaceId,
- domain,
- tagId,
- tagIds,
- tagNames,
- search,
- searchMode,
- sort, // Deprecated
- sortBy,
- sortOrder,
- page,
- pageSize,
- userId,
- showArchived,
- withTags,
- folderId,
- folderIds,
- linkIds,
- includeUser,
- includeWebhooks,
- includeDashboard,
- tenantId,
- partnerId,
- startDate,
- endDate,
-}: GetLinksForWorkspaceProps) {
- const combinedTagIds = combineTagIds({ tagId, tagIds });
+export async function getLinksForWorkspace(filters: GetLinksForWorkspaceProps) {
+ let {
+ workspaceId,
+ domain,
+ tagId,
+ tagIds,
+ tagNames,
+ search,
+ searchMode,
+ sort,
+ userId,
+ showArchived,
+ withTags,
+ folderId,
+ folderIds,
+ linkIds,
+ includeUser,
+ includeWebhooks,
+ includeDashboard,
+ tenantId,
+ partnerId,
+ startDate,
+ endDate,
+ } = filters;
- // support legacy sort param
+ // Support legacy sort param
if (sort && sort !== "createdAt") {
- sortBy = sort;
+ filters = { ...filters, sortBy: sort };
}
+ const paginationQuery = buildPaginationQuery(filters);
+
+ // Validate the provided cursor ID
+ const cursorId = filters.startingAfter || filters.endingBefore;
+
+ if (cursorId) {
+ const link = await prisma.link.findUnique({
+ where: {
+ id: cursorId,
+ },
+ select: {
+ id: true,
+ projectId: true,
+ },
+ });
+
+ if (!link || link.projectId !== workspaceId) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Invalid cursor: the provided ID does not exist.",
+ });
+ }
+ }
+
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
+
if (searchMode === "exact" && search) {
try {
const url = new URL(search);
@@ -162,11 +186,7 @@ export async function getLinksForWorkspace({
webhooks: includeWebhooks,
dashboard: includeDashboard,
},
- orderBy: {
- [sortBy]: sortOrder,
- },
- take: pageSize,
- skip: (page - 1) * pageSize,
+ ...paginationQuery,
});
return links.map((link) => transformLink(link));
diff --git a/apps/web/lib/api/network/calculate-partner-ranking.ts b/apps/web/lib/api/network/calculate-partner-ranking.ts
index 0c0b97bde2..9e38795bd0 100644
--- a/apps/web/lib/api/network/calculate-partner-ranking.ts
+++ b/apps/web/lib/api/network/calculate-partner-ranking.ts
@@ -47,7 +47,7 @@ export async function calculatePartnerRanking({
starred,
platform,
subscribers,
- page,
+ page = 1,
pageSize,
status = "discover",
similarPrograms = [],
diff --git a/apps/web/lib/api/pagination.ts b/apps/web/lib/api/pagination.ts
new file mode 100644
index 0000000000..d7a78252be
--- /dev/null
+++ b/apps/web/lib/api/pagination.ts
@@ -0,0 +1,89 @@
+import { DubApiError } from "@/lib/api/errors";
+import { Prisma } from "@dub/prisma/client";
+
+interface Filters {
+ page?: number;
+ pageSize: number;
+ startingAfter?: string | null;
+ endingBefore?: string | null;
+ sortBy: string;
+ sortOrder: Prisma.SortOrder;
+}
+
+interface PaginationQuery {
+ cursor?: { id: string };
+ skip: number;
+ take: number;
+ orderBy:
+ | Record<string, Prisma.SortOrder>
+ | Array<Record<string, Prisma.SortOrder>>;
+}
+
+export const MAX_OFFSET_PAGE = 1000;
+
+export function buildPaginationQuery(filters: Filters): PaginationQuery {
+ let { page, pageSize, startingAfter, endingBefore, sortBy, sortOrder } =
+ filters;
+
+ const useCursorPagination = !!startingAfter || !!endingBefore;
+
+ // Cursor pagination validations
+ if (startingAfter && endingBefore) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both startingAfter and endingBefore at the same time.",
+ });
+ }
+
+ if (useCursorPagination && sortBy !== "createdAt") {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "Cursor-based pagination only supports sorting by `createdAt`. Use offset-based pagination (page/pageSize) for other sort fields.",
+ });
+ }
+
+ if (useCursorPagination && page) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both page and startingAfter/endingBefore at the same time. Please use one pagination method.",
+ });
+ }
+
+ if (useCursorPagination) {
+ const cursorId = startingAfter || endingBefore!;
+
+ return {
+ cursor: {
+ id: cursorId,
+ },
+ orderBy: {
+ id: sortOrder,
+ },
+ take: endingBefore ? -pageSize : pageSize,
+ skip: 1,
+ };
+ }
+
+ page = page ?? 1;
+
+ // Offset pagination validations
+ if (page > MAX_OFFSET_PAGE) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `Page is too big (cannot be more than ${MAX_OFFSET_PAGE}), recommend using cursor-based pagination instead.`,
+ });
+ }
+
+ return {
+ // Order by id only for better query performance on large datasets (single-column PK index).
+ // Trade-off: ordering is by id rather than createdAt, so order may not strictly match creation time.
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ take: pageSize,
+ skip: (page - 1) * pageSize,
+ };
+}
diff --git a/apps/web/lib/api/partners/get-partners.ts b/apps/web/lib/api/partners/get-partners.ts
index eb946ab5aa..04cd6bfb00 100644
--- a/apps/web/lib/api/partners/get-partners.ts
+++ b/apps/web/lib/api/partners/get-partners.ts
@@ -15,7 +15,7 @@ export async function getPartners(filters: PartnerFilters) {
email,
tenantId,
partnerIds,
- page,
+ page = 1,
pageSize,
sortBy,
sortOrder,
diff --git a/apps/web/lib/api/payouts/get-eligible-payouts.ts b/apps/web/lib/api/payouts/get-eligible-payouts.ts
index d8a05c9fcd..038e252259 100644
--- a/apps/web/lib/api/payouts/get-eligible-payouts.ts
+++ b/apps/web/lib/api/payouts/get-eligible-payouts.ts
@@ -26,7 +26,7 @@ export async function getEligiblePayouts({
selectedPayoutId,
excludedPayoutIds,
pageSize,
- page,
+ page = 1,
}: GetEligiblePayoutsProps) {
const cutoffPeriodValue = CUTOFF_PERIOD.find(
(c) => c.id === cutoffPeriod,
diff --git a/apps/web/lib/customers/api/get-customers.ts b/apps/web/lib/customers/api/get-customers.ts
index 1a5650b658..58b811c9b2 100644
--- a/apps/web/lib/customers/api/get-customers.ts
+++ b/apps/web/lib/customers/api/get-customers.ts
@@ -1,6 +1,8 @@
import { getCustomersQuerySchemaExtended } from "@/lib/zod/schemas/customers";
import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
import * as z from "zod/v4";
+import { DubApiError } from "../../api/errors";
+import { buildPaginationQuery } from "../../api/pagination";
type GetCustomersInput = z.infer<typeof getCustomersQuerySchemaExtended> & {
workspaceId: string;
@@ -17,13 +19,35 @@ export async function getCustomers(filters: GetCustomersInput) {
search,
country,
linkId,
- sortBy,
- sortOrder,
- page,
- pageSize,
includeExpandedFields,
+ startingAfter,
+ endingBefore,
} = filters;
+ const paginationQuery = buildPaginationQuery(filters);
+
+ // Validate the provided cursor ID
+ const cursorId = startingAfter || endingBefore;
+
+ if (cursorId) {
+ const customer = await prisma.customer.findUnique({
+ where: {
+ id: cursorId,
+ },
+ select: {
+ id: true,
+ projectId: true,
+ },
+ });
+
+ if (!customer || customer.projectId !== workspaceId) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Invalid cursor: the provided ID does not exist.",
+ });
+ }
+ }
+
return await prisma.customer.findMany({
where: {
...(customerIds
@@ -57,11 +81,7 @@ export async function getCustomers(filters: GetCustomersInput) {
linkId,
}),
},
- orderBy: {
- [sortBy]: sortOrder,
- },
- skip: (page - 1) * pageSize,
- take: pageSize,
+ ...paginationQuery,
...(includeExpandedFields
? {
include: {
diff --git a/apps/web/lib/openapi/commissions/list-commissions.ts b/apps/web/lib/openapi/commissions/list-commissions.ts
index c4a0df3744..b00b46a260 100644
--- a/apps/web/lib/openapi/commissions/list-commissions.ts
+++ b/apps/web/lib/openapi/commissions/list-commissions.ts
@@ -9,6 +9,19 @@ import { openApiErrorResponses } from "../responses";
export const listCommissions: ZodOpenApiOperationObject = {
operationId: "listCommissions",
"x-speakeasy-name-override": "list",
+ "x-speakeasy-pagination": {
+ type: "cursor",
+ inputs: [
+ {
+ name: "startingAfter",
+ in: "parameters",
+ type: "cursor",
+ },
+ ],
+ outputs: {
+ nextCursor: "$[-1].id",
+ },
+ },
summary: "List all commissions",
description: "Retrieve a list of commissions for your partner program.",
requestParams: {
diff --git a/apps/web/lib/openapi/customers/get-customers.ts b/apps/web/lib/openapi/customers/get-customers.ts
index dd4b34ce0c..3ecb55308d 100644
--- a/apps/web/lib/openapi/customers/get-customers.ts
+++ b/apps/web/lib/openapi/customers/get-customers.ts
@@ -9,6 +9,19 @@ import {
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: "Retrieve a list of customers",
description: "Retrieve a list of customers for the authenticated workspace.",
requestParams: {
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index 760e5a345f..67e19b631f 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -3,7 +3,10 @@ import { CommissionStatus, CommissionType } from "@dub/prisma/client";
import * as z from "zod/v4";
import { CustomerSchema } from "./customers";
import { LinkSchema } from "./links";
-import { getPaginationQuerySchema } from "./misc";
+import {
+ getCursorPaginationQuerySchema,
+ getPaginationQuerySchema,
+} from "./misc";
import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";
import { centsSchema, parseDateSchema } from "./utils";
@@ -118,13 +121,23 @@ export const getCommissionsQuerySchema = z
.describe("The end date of the date range to filter the commissions by."),
timezone: z.string().optional(),
})
- .extend(getPaginationQuerySchema({ pageSize: COMMISSIONS_MAX_PAGE_SIZE }));
+ .extend({
+ ...getCursorPaginationQuerySchema({
+ example: "cm_1KAP4CGN2Z5TPYYQ1W4JEYD56",
+ }),
+ ...getPaginationQuerySchema({
+ pageSize: COMMISSIONS_MAX_PAGE_SIZE,
+ deprecated: true,
+ }),
+ });
export const getCommissionsCountQuerySchema = getCommissionsQuerySchema.omit({
page: true,
pageSize: true,
sortOrder: true,
sortBy: true,
+ startingAfter: true,
+ endingBefore: true,
});
export const createCommissionSchema = z.object({
@@ -291,7 +304,12 @@ export const DEFAULT_COMMISSION_EXPORT_COLUMNS =
);
export const commissionsExportQuerySchema = getCommissionsQuerySchema
- .omit({ page: true, pageSize: true })
+ .omit({
+ page: true,
+ pageSize: true,
+ startingAfter: true,
+ endingBefore: true,
+ })
.extend({
columns: z
.string()
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index aa3c16dccb..aeb02e6e7f 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -1,7 +1,11 @@
import * as z from "zod/v4";
import { DiscountSchema } from "./discount";
import { LinkSchema } from "./links";
-import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
+import {
+ booleanQuerySchema,
+ getCursorPaginationQuerySchema,
+ getPaginationQuerySchema,
+} from "./misc";
import { PartnerSchema } from "./partners";
import { centsSchema } from "./utils";
@@ -64,7 +68,15 @@ export const getCustomersQuerySchema = z
.default("desc")
.describe("The sort order. The default is `desc`."),
})
- .extend(getPaginationQuerySchema({ pageSize: CUSTOMERS_MAX_PAGE_SIZE }));
+ .extend({
+ ...getCursorPaginationQuerySchema({
+ example: "cus_1KAP4CDPBSVMMBMH9XX3YZZ0Z",
+ }),
+ ...getPaginationQuerySchema({
+ pageSize: CUSTOMERS_MAX_PAGE_SIZE,
+ deprecated: true,
+ }),
+ });
export const getCustomersQuerySchemaExtended = getCustomersQuerySchema.extend({
customerIds: z
@@ -81,6 +93,8 @@ export const getCustomersCountQuerySchema = getCustomersQuerySchema
pageSize: true,
sortBy: true,
sortOrder: true,
+ startingAfter: true,
+ endingBefore: true,
})
.extend({ groupBy: z.enum(["country", "linkId", "partnerId"]).optional() });
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index 112e071393..b027ecf060 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -4,6 +4,7 @@ import * as z from "zod/v4";
import {
base64ImageSchema,
booleanQuerySchema,
+ getCursorPaginationQuerySchema,
getPaginationQuerySchema,
publicHostedImageSchema,
} from "./misc";
@@ -29,6 +30,7 @@ export const getDomainQuerySchema = z.object({
export const MIN_TEST_PERCENTAGE = 10;
export const MAX_TEST_COUNT = 4;
+export const LINKS_MAX_PAGE_SIZE = 100;
export const ABTestVariantsSchema = z
.array(
@@ -167,7 +169,15 @@ export const getLinksQuerySchemaBase = LinksQuerySchema.extend({
sort: sortBy
.meta({ deprecated: true })
.describe("DEPRECATED. Use `sortBy` instead."),
-}).extend(getPaginationQuerySchema({ pageSize: 100 }));
+}).extend({
+ ...getCursorPaginationQuerySchema({
+ example: "link_1KAP4CDPBSVMMBMH9XX3YZZ0Z...",
+ }),
+ ...getPaginationQuerySchema({
+ pageSize: LINKS_MAX_PAGE_SIZE,
+ deprecated: true,
+ }),
+});
export const getLinksCountQuerySchema = LinksQuerySchema.extend({
groupBy: z
diff --git a/apps/web/lib/zod/schemas/misc.ts b/apps/web/lib/zod/schemas/misc.ts
index f718259054..946177bd90 100644
--- a/apps/web/lib/zod/schemas/misc.ts
+++ b/apps/web/lib/zod/schemas/misc.ts
@@ -32,17 +32,23 @@ export const booleanQuerySchema = z
// Pagination
export const getPaginationQuerySchema = ({
pageSize,
+ deprecated = false,
}: {
pageSize: number;
+ deprecated?: boolean;
}) => ({
page: z.coerce
.number({ error: "Page must be a number." })
.positive({ message: "Page must be greater than 0." })
.optional()
- .default(1)
- .describe("The page number for pagination.")
+ .describe(
+ deprecated
+ ? "DEPRECATED. Use `startingAfter` instead."
+ : "The page number for pagination.",
+ )
.meta({
example: 1,
+ deprecated,
}),
pageSize: z.coerce
.number({ error: "Page size must be a number." })
@@ -58,6 +64,32 @@ export const getPaginationQuerySchema = ({
}),
});
+// Cursor-based pagination
+export const getCursorPaginationQuerySchema = ({
+ example,
+}: {
+ example: string;
+}) => ({
+ endingBefore: z
+ .string()
+ .optional()
+ .describe(
+ "If specified, the query only searches for results before this cursor. Mutually exclusive with `startingAfter`.",
+ )
+ .meta({
+ example,
+ }),
+ startingAfter: z
+ .string()
+ .optional()
+ .describe(
+ "If specified, the query only searches for results after this cursor. Mutually exclusive with `endingBefore`.",
+ )
+ .meta({
+ example,
+ }),
+});
+
export const maxDurationSchema = z.coerce
.number()
.refine((val) => RECURRING_MAX_DURATIONS.includes(val), {
diff --git a/apps/web/tests/commissions/pagination.test.ts b/apps/web/tests/commissions/pagination.test.ts
new file mode 100644
index 0000000000..252b397190
--- /dev/null
+++ b/apps/web/tests/commissions/pagination.test.ts
@@ -0,0 +1,218 @@
+import { CommissionResponse } from "@/lib/types";
+import { beforeAll, describe, expect, test } from "vitest";
+import {
+ expectNoOverlap,
+ expectSortedByCreatedAt,
+ expectSortedById,
+} from "../utils/helpers";
+import { IntegrationHarness } from "../utils/integration";
+
+describe.concurrent("/commissions/** - pagination", async () => {
+ const h = new IntegrationHarness();
+ let http: IntegrationHarness["http"];
+ let baseline: CommissionResponse[];
+ let baselineIds: string[];
+
+ const commonQuery = {
+ pageSize: "5",
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ };
+
+ beforeAll(async () => {
+ ({ http } = await h.init());
+
+ const { status, data } = await http.get<CommissionResponse[]>({
+ path: "/commissions",
+ query: { ...commonQuery, pageSize: "25" },
+ });
+
+ expect(status).toEqual(200);
+
+ baseline = data;
+ baselineIds = baseline.map((c) => c.id);
+ expectSortedByCreatedAt(baseline);
+ });
+
+ test("Offset pagination works", async () => {
+ const page1 = await http.get<CommissionResponse[]>({
+ path: "/commissions",
+ query: { ...commonQuery, page: "1" },
+ });
+ const page2 = await http.get<CommissionResponse[]>({
+ path: "/commissions",
+ query: { ...commonQuery, page: "2" },
+ });
+
+ expect(page1.status).toEqual(200);
+ expect(page2.status).toEqual(200);
+
+ expect(page1.data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));
+ expect(page2.data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));
+
+ expectNoOverlap(page1.data, page2.data);
+ });
+
+ test("Cursor forward (startingAfter)", async () => {
+ const firstPage = baseline.slice(0, 5);
+ const lastId = firstPage[4].id;
+ const expectedIds = baseline
+ .filter((b) => b.id < lastId)
+ .sort((a, b) => b.id.localeCompare(a.id))
+ .slice(0, 5)
+ .map((b) => b.id);
+
+ const { status, data } = await http.get<CommissionResponse[]>({
+ path: "/commissions",
+ query: {
+ ...commonQuery,
+ pageSize: "5",
+ startingAfter: lastId,
+ },
+ });
+
+ expect(status).toEqual(200);
+ expect(data.map((d) => d.id)).toEqual(expectedIds);
+ expectSortedById(data, "desc");
+ });
+
+ test("Cursor backward (endingBefore)", async () => {
+ const beforeId = baseline[5].id;
+ const expectedIds = baseline
+ .filter((b) => b.id > beforeId)
+ .sort((a, b) => b.id.localeCompare(a.id))
+ .slice(0, 5)
+ .map((b) => b.id);
+
+ const { status, data } = await http.get<CommissionResponse[]>({
+ path: "/commissions",
+ query: {
+ ...commonQuery,
+ pageSize: "5",
+ endingBefore: beforeId,
+ },
+ });
+
+ expect(status).toEqual(200);
+ expect(data.map((d) => d.id)).toEqual(expectedIds);
+ expectSortedById(data, "desc");
+ });
+
+ test("Rejects both startingAfter and endingBefore", async () => {
+ const { status, data: error } = await http.get({
+ path: "/commissions",
+ query: {
+ pageSize: "5",
+ startingAfter: "id",
+ endingBefore: "id",
+ },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both startingAfter and endingBefore at the same time.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("Rejects page > MAX_OFFSET_PAGE", async () => {
+ const { status, data: error } = await http.get({
+ path: "/commissions",
+ query: { page: "1001", pageSize: "10" },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "Page is too big (cannot be more than 1000), recommend using cursor-based pagination instead.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("Invalid cursor ID (startingAfter / endingBefore) returns error", async () => {
+ const invalidCursorError = {
+ error: {
+ code: "unprocessable_entity",
+ message: "Invalid cursor: the provided ID does not exist.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ };
+
+ const { status: statusAfter, data: errorAfter } = await http.get({
+ path: "/commissions",
+ query: { pageSize: "5", startingAfter: "cm_invalid_id_12345" },
+ });
+
+ expect(statusAfter).toEqual(422);
+ expect(errorAfter).toStrictEqual(invalidCursorError);
+
+ const { status: statusBefore, data: errorBefore } = await http.get({
+ path: "/commissions",
+ query: { pageSize: "5", endingBefore: "cm_invalid_id_12345" },
+ });
+
+ expect(statusBefore).toEqual(422);
+ expect(errorBefore).toStrictEqual(invalidCursorError);
+ });
+
+ test("Rejects mixing page with startingAfter / endingBefore", async () => {
+ const mixedPaginationError = {
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both page and startingAfter/endingBefore at the same time. Please use one pagination method.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ };
+
+ const firstPage = baseline.slice(0, 5);
+ const { status: statusAfter, data: errorAfter } = await http.get({
+ path: "/commissions",
+ query: { page: "2", pageSize: "5", startingAfter: firstPage[4].id },
+ });
+
+ expect(statusAfter).toEqual(422);
+ expect(errorAfter).toStrictEqual(mixedPaginationError);
+
+ const { status: statusBefore, data: errorBefore } = await http.get({
+ path: "/commissions",
+ query: { page: "2", pageSize: "5", endingBefore: baseline[5].id },
+ });
+
+ expect(statusBefore).toEqual(422);
+ expect(errorBefore).toStrictEqual(mixedPaginationError);
+ });
+
+ test("Rejects cursor pagination with unsupported sort field", async () => {
+ const { status, data: error } = await http.get({
+ path: "/commissions",
+ query: {
+ pageSize: "5",
+ startingAfter: baseline[0].id,
+ sortBy: "amount",
+ },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "Cursor-based pagination only supports sorting by `createdAt`. Use offset-based pagination (page/pageSize) for other sort fields.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+});
diff --git a/apps/web/tests/customers/pagination.test.ts b/apps/web/tests/customers/pagination.test.ts
new file mode 100644
index 0000000000..15a869c44c
--- /dev/null
+++ b/apps/web/tests/customers/pagination.test.ts
@@ -0,0 +1,197 @@
+import { Customer } from "@/lib/types";
+import { beforeAll, describe, expect, test } from "vitest";
+import {
+ expectNoOverlap,
+ expectSortedByCreatedAt,
+ expectSortedById,
+} from "../utils/helpers";
+import { IntegrationHarness } from "../utils/integration";
+
+describe.concurrent("/customers/** - pagination", async () => {
+ const h = new IntegrationHarness();
+ let http: IntegrationHarness["http"];
+ let baseline: Customer[];
+ let baselineIds: string[];
+
+ const commonQuery = {
+ pageSize: "5",
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ };
+
+ beforeAll(async () => {
+ ({ http } = await h.init());
+
+ const { status, data } = await http.get<Customer[]>({
+ path: "/customers",
+ query: { ...commonQuery, pageSize: "25" },
+ });
+
+ expect(status).toEqual(200);
+
+ baseline = data;
+ baselineIds = baseline.map((c) => c.id);
+
+ expectSortedByCreatedAt(baseline);
+ });
+
+ test("Offset pagination works", async () => {
+ const page1 = await http.get<Customer[]>({
+ path: "/customers",
+ query: { ...commonQuery, page: "1" },
+ });
+ const page2 = await http.get<Customer[]>({
+ path: "/customers",
+ query: { ...commonQuery, page: "2" },
+ });
+
+ expect(page1.status).toEqual(200);
+ expect(page2.status).toEqual(200);
+
+ expect(page1.data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));
+ expect(page2.data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));
+
+ expectNoOverlap(page1.data, page2.data);
+ });
+
+ test("Cursor forward (startingAfter)", async () => {
+ const firstPage = baseline.slice(0, 5);
+ const lastId = firstPage[4].id;
+
+ const { status, data } = await http.get<Customer[]>({
+ path: "/customers",
+ query: { pageSize: "5", startingAfter: lastId },
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toHaveLength(5);
+ expectSortedById(data, "desc");
+ });
+
+ test("Cursor backward (endingBefore)", async () => {
+ const beforeId = baseline[5].id;
+
+ const { status, data } = await http.get<Customer[]>({
+ path: "/customers",
+ query: { pageSize: "5", endingBefore: beforeId },
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toHaveLength(5);
+ expectSortedById(data, "desc");
+ });
+
+ test("Rejects both startingAfter and endingBefore", async () => {
+ const { status, data: error } = await http.get({
+ path: "/customers",
+ query: { pageSize: "5", startingAfter: "id", endingBefore: "id" },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both startingAfter and endingBefore at the same time.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("Rejects page > MAX_OFFSET_PAGE", async () => {
+ const { status, data: error } = await http.get({
+ path: "/customers",
+ query: { page: "1001", pageSize: "10" },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "Page is too big (cannot be more than 1000), recommend using cursor-based pagination instead.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("Invalid cursor ID (startingAfter / endingBefore) returns error", async () => {
+ const invalidCursorError = {
+ error: {
+ code: "unprocessable_entity",
+ message: "Invalid cursor: the provided ID does not exist.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ };
+
+ const { status: statusAfter, data: errorAfter } = await http.get({
+ path: "/customers",
+ query: { pageSize: "5", startingAfter: "cus_invalid_id_12345" },
+ });
+
+ expect(statusAfter).toEqual(422);
+ expect(errorAfter).toStrictEqual(invalidCursorError);
+
+ const { status: statusBefore, data: errorBefore } = await http.get({
+ path: "/customers",
+ query: { pageSize: "5", endingBefore: "cus_invalid_id_12345" },
+ });
+
+ expect(statusBefore).toEqual(422);
+ expect(errorBefore).toStrictEqual(invalidCursorError);
+ });
+
+ test("Rejects mixing page with startingAfter / endingBefore", async () => {
+ const mixedPaginationError = {
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both page and startingAfter/endingBefore at the same time. Please use one pagination method.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ };
+
+ const firstPage = baseline.slice(0, 5);
+ const { status: statusAfter, data: errorAfter } = await http.get({
+ path: "/customers",
+ query: { page: "2", pageSize: "5", startingAfter: firstPage[4].id },
+ });
+
+ expect(statusAfter).toEqual(422);
+ expect(errorAfter).toStrictEqual(mixedPaginationError);
+
+ const { status: statusBefore, data: errorBefore } = await http.get({
+ path: "/customers",
+ query: { page: "2", pageSize: "5", endingBefore: baseline[5].id },
+ });
+
+ expect(statusBefore).toEqual(422);
+ expect(errorBefore).toStrictEqual(mixedPaginationError);
+ });
+
+ test("Rejects cursor pagination with unsupported sort field", async () => {
+ const { status, data: error } = await http.get({
+ path: "/customers",
+ query: {
+ pageSize: "5",
+ startingAfter: baseline[0].id,
+ sortBy: "saleAmount",
+ },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "Cursor-based pagination only supports sorting by `createdAt`. Use offset-based pagination (page/pageSize) for other sort fields.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+});
diff --git a/apps/web/tests/links/list-links.test.ts b/apps/web/tests/links/list-links.test.ts
index 8decc7506b..a0a3bbb237 100644
--- a/apps/web/tests/links/list-links.test.ts
+++ b/apps/web/tests/links/list-links.test.ts
@@ -1,6 +1,11 @@
import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { Link } from "@dub/prisma/client";
-import { expect, onTestFinished, test } from "vitest";
+import { beforeAll, describe, expect, onTestFinished, test } from "vitest";
+import {
+ expectNoOverlap,
+ expectSortedByCreatedAt,
+ expectSortedById,
+} from "../utils/helpers";
import { IntegrationHarness } from "../utils/integration";
import { E2E_LINK } from "../utils/resource";
@@ -40,3 +45,196 @@ test("GET /links", async (ctx) => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${firstLink.key}?qr=1`,
});
});
+
+describe.concurrent("/links/** - pagination", async () => {
+ const h = new IntegrationHarness();
+ let http: IntegrationHarness["http"];
+ let baseline: Link[];
+ let baselineIds: string[];
+
+ const commonQuery = {
+ pageSize: "5",
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ };
+
+ beforeAll(async () => {
+ ({ http } = await h.init());
+
+ const { status, data } = await http.get<Link[]>({
+ path: "/links",
+ query: { ...commonQuery, pageSize: "25" },
+ });
+
+ expect(status).toEqual(200);
+
+ baseline = data;
+ baselineIds = baseline.map((l) => l.id);
+
+ expectSortedByCreatedAt(baseline);
+ });
+
+ test("Offset pagination works", async () => {
+ const page1 = await http.get<Link[]>({
+ path: "/links",
+ query: { ...commonQuery, page: "1" },
+ });
+ const page2 = await http.get<Link[]>({
+ path: "/links",
+ query: { ...commonQuery, page: "2" },
+ });
+
+ expect(page1.status).toEqual(200);
+ expect(page2.status).toEqual(200);
+
+ expect(page1.data.map((l) => l.id)).toEqual(baselineIds.slice(0, 5));
+ expect(page2.data.map((l) => l.id)).toEqual(baselineIds.slice(5, 10));
+
+ expectNoOverlap(page1.data, page2.data);
+ });
+
+ test("Cursor forward (startingAfter)", async () => {
+ const firstPage = baseline.slice(0, 5);
+ const lastId = firstPage[4].id;
+
+ const { status, data } = await http.get<Link[]>({
+ path: "/links",
+ query: { pageSize: "5", startingAfter: lastId },
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toHaveLength(5);
+ expectSortedById(data, "desc");
+ });
+
+ test("Cursor backward (endingBefore)", async () => {
+ const beforeId = baseline[5].id;
+
+ const { status, data } = await http.get<Link[]>({
+ path: "/links",
+ query: { pageSize: "5", endingBefore: beforeId },
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toHaveLength(5);
+ expectSortedById(data, "desc");
+ });
+
+ test("Rejects both startingAfter and endingBefore", async () => {
+ const { status, data: error } = await http.get({
+ path: "/links",
+ query: {
+ pageSize: "5",
+ startingAfter: baselineIds[0],
+ endingBefore: baselineIds[1],
+ },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both startingAfter and endingBefore at the same time.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("Rejects page > MAX_OFFSET_PAGE", async () => {
+ const { status, data: error } = await http.get({
+ path: "/links",
+ query: { page: "1001", pageSize: "10" },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "Page is too big (cannot be more than 1000), recommend using cursor-based pagination instead.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("Invalid cursor ID (startingAfter / endingBefore) returns error", async () => {
+ const invalidCursorError = {
+ error: {
+ code: "unprocessable_entity",
+ message: "Invalid cursor: the provided ID does not exist.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ };
+
+ const { status: statusAfter, data: errorAfter } = await http.get({
+ path: "/links",
+ query: { pageSize: "5", startingAfter: "link_invalid_id_12345" },
+ });
+
+ expect(statusAfter).toEqual(422);
+ expect(errorAfter).toStrictEqual(invalidCursorError);
+
+ const { status: statusBefore, data: errorBefore } = await http.get({
+ path: "/links",
+ query: { pageSize: "5", endingBefore: "link_invalid_id_12345" },
+ });
+
+ expect(statusBefore).toEqual(422);
+ expect(errorBefore).toStrictEqual(invalidCursorError);
+ });
+
+ test("Rejects mixing page with startingAfter / endingBefore", async () => {
+ const mixedPaginationError = {
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "You cannot use both page and startingAfter/endingBefore at the same time. Please use one pagination method.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ };
+
+ const firstPage = baseline.slice(0, 5);
+ const { status: statusAfter, data: errorAfter } = await http.get({
+ path: "/links",
+ query: { page: "2", pageSize: "5", startingAfter: firstPage[4].id },
+ });
+
+ expect(statusAfter).toEqual(422);
+ expect(errorAfter).toStrictEqual(mixedPaginationError);
+
+ const { status: statusBefore, data: errorBefore } = await http.get({
+ path: "/links",
+ query: { page: "2", pageSize: "5", endingBefore: baseline[5].id },
+ });
+
+ expect(statusBefore).toEqual(422);
+ expect(errorBefore).toStrictEqual(mixedPaginationError);
+ });
+
+ test("Rejects cursor pagination with unsupported sort field", async () => {
+ const { status, data: error } = await http.get({
+ path: "/links",
+ query: {
+ pageSize: "5",
+ startingAfter: baseline[0].id,
+ sortBy: "clicks",
+ },
+ });
+
+ expect(status).toEqual(422);
+ expect(error).toStrictEqual({
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "Cursor-based pagination only supports sorting by `createdAt`. Use offset-based pagination (page/pageSize) for other sort fields.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+});
diff --git a/apps/web/tests/utils/helpers.ts b/apps/web/tests/utils/helpers.ts
index cbfab4760f..7b71e73066 100644
--- a/apps/web/tests/utils/helpers.ts
+++ b/apps/web/tests/utils/helpers.ts
@@ -1,5 +1,6 @@
import { generateRandomName } from "@/lib/names";
import { OG_AVATAR_URL, nanoid, randomValue } from "@dub/utils";
+import { expect } from "vitest";
export const randomId = (length = 24) => nanoid(length);
@@ -56,3 +57,42 @@ export async function retry<T>(
throw lastError;
}
+
+export function expectSortedById(
+ items: { id: string }[],
+ order: "asc" | "desc",
+) {
+ for (let i = 0; i < items.length - 1; i++) {
+ const cmp = items[i].id.localeCompare(items[i + 1].id);
+ if (order === "desc") {
+ expect(cmp).toBeGreaterThanOrEqual(0);
+ } else {
+ expect(cmp).toBeLessThanOrEqual(0);
+ }
+ }
+}
+
+export function expectSortedByCreatedAt<T extends { createdAt: string | Date }>(
+ items: T[],
+) {
+ for (let i = 0; i < items.length - 1; i++) {
+ const a = new Date(items[i].createdAt).getTime();
+ const b = new Date(items[i + 1].createdAt).getTime();
+ expect(a).toBeGreaterThanOrEqual(b);
+ }
+}
+
+export function expectSortedByCreatedAtAsc<
+ T extends { createdAt: string | Date },
+>(items: T[]) {
+ for (let i = 0; i < items.length - 1; i++) {
+ const a = new Date(items[i].createdAt).getTime();
+ const b = new Date(items[i + 1].createdAt).getTime();
+ expect(a).toBeLessThanOrEqual(b);
+ }
+}
+
+export function expectNoOverlap<T extends { id: string }>(a: T[], b: T[]) {
+ const overlap = a.map((x) => x.id).filter((id) => b.some((x) => x.id === id));
+ expect(overlap).toHaveLength(0);
+}
diff --git a/apps/web/ui/customers/customers-table/customers-table.tsx b/apps/web/ui/customers/customers-table/customers-table.tsx
index 9ee70f2dbf..a1ef84a8d9 100644
--- a/apps/web/ui/customers/customers-table/customers-table.tsx
+++ b/apps/web/ui/customers/customers-table/customers-table.tsx
@@ -405,7 +405,12 @@ export function CustomersTable({
resourceName: (p) => `customer${p ? "s" : ""}`,
rowCount: customersCount || 0,
loading: isLoading,
- error: error || countError ? "Failed to load customers" : undefined,
+ error:
+ error instanceof Error
+ ? error.message
+ : countError
+ ? "Failed to load customers"
+ : undefined,
});
return (
diff --git a/apps/web/ui/links/links-container.tsx b/apps/web/ui/links/links-container.tsx
index d1bbbe6646..0a3fe32f64 100644
--- a/apps/web/ui/links/links-container.tsx
+++ b/apps/web/ui/links/links-container.tsx
@@ -37,7 +37,7 @@ export default function LinksContainer({
const { folderId } = useCurrentFolderId();
- const { links, isValidating } = useLinks({
+ const { links, isValidating, error } = useLinks({
sortBy,
showArchived,
folderId: folderId ?? "",
@@ -57,6 +57,7 @@ export default function LinksContainer({
links={links}
count={count}
loading={isValidating}
+ error={error}
compact={viewMode === "rows"}
/>
</PageWidthWrapper>
@@ -76,12 +77,14 @@ function LinksList({
links,
count,
loading,
+ error,
compact,
}: {
CreateLinkButton: () => JSX.Element;
links?: ResponseLink[];
count?: number;
loading?: boolean;
+ error?: unknown;
compact: boolean;
}) {
const searchParams = useSearchParams();
@@ -98,10 +101,17 @@ function LinksList({
"showArchived",
].some((param) => searchParams.has(param));
+ const errorMessage =
+ error instanceof Error ? error.message : "Failed to load links";
+
return (
<LinksListContext.Provider value={{ openMenuLinkId, setOpenMenuLinkId }}>
<LinkSelectionProvider links={links}>
- {!links || links.length ? (
+ {error ? (
+ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">
+ {errorMessage}
+ </div>
+ ) : !links || links.length ? (
// Cards
<CardList variant={compact ? "compact" : "loose"} loading={loading}>
{links?.length