The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add throwIfClicksUsageExceeded & throwIfLinksUsageExceeded
Kiran K241a69d441d0
diff --git a/apps/web/app/api/analytics/events/export/route.ts b/apps/web/app/api/analytics/events/export/route.tsindex 6eccf65995..84aab43e81 100644--- a/apps/web/app/api/analytics/events/export/route.ts+++ b/apps/web/app/api/analytics/events/export/route.ts@@ -1,6 +1,7 @@import { getEvents } from "@/lib/analytics/get-events";import { convertToCSV, validDateRangeForPlan } from "@/lib/analytics/utils";import { getDomainOrThrow } from "@/lib/api/domains/get-domain";+import { throwIfClicksUsageExceeded } from "@/lib/api/errors";import { getLinkOrThrow } from "@/lib/api/links/get-link";import { withWorkspace } from "@/lib/auth";import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";@@ -37,62 +38,59 @@ const columnAccessors = {};// GET /api/analytics/events/export – get export data for analytics-export const GET = withWorkspace(- async ({ searchParams, workspace }) => {- const parsedParams = eventsQuerySchema- .and(- z.object({- columns: z- .string()- .transform((c) => c.split(","))- .pipe(z.string().array()),- }),- )- .parse(searchParams);+export const GET = withWorkspace(async ({ searchParams, workspace }) => {+ throwIfClicksUsageExceeded(workspace);- const { event, domain, interval, start, end, columns, key } = parsedParams;+ const parsedParams = eventsQuerySchema+ .and(+ z.object({+ columns: z+ .string()+ .transform((c) => c.split(","))+ .pipe(z.string().array()),+ }),+ )+ .parse(searchParams);- if (domain) {- await getDomainOrThrow({ workspace, domain });- }+ const { event, domain, interval, start, end, columns, key } = parsedParams;- const link =- domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;+ if (domain) {+ await getDomainOrThrow({ workspace, domain });+ }- validDateRangeForPlan({- plan: workspace.plan,- interval,- start,- end,- throwError: true,- });+ const link =+ domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;- const response = await getEvents({- ...parsedParams,- ...(link && { linkId: link.id }),- workspaceId: workspace.id,- limit: 100000,- });+ validDateRangeForPlan({+ plan: workspace.plan,+ interval,+ start,+ end,+ throwError: true,+ });- const data = response.map((row) =>- Object.fromEntries(- columns.map((c) => [- columnNames?.[c] ?? capitalize(c),- columnAccessors[c]?.(row) ?? row?.[c],- ]),- ),- );+ const response = await getEvents({+ ...parsedParams,+ ...(link && { linkId: link.id }),+ workspaceId: workspace.id,+ limit: 100000,+ });- const csvData = convertToCSV(data);+ const data = response.map((row) =>+ Object.fromEntries(+ columns.map((c) => [+ columnNames?.[c] ?? capitalize(c),+ columnAccessors[c]?.(row) ?? row?.[c],+ ]),+ ),+ );- return new Response(csvData, {- headers: {- "Content-Type": "application/csv",- "Content-Disposition": `attachment; filename=${event}_export.csv`,- },- });- },- {- needNotExceededClicks: true,- },-);+ const csvData = convertToCSV(data);++ return new Response(csvData, {+ headers: {+ "Content-Type": "application/csv",+ "Content-Disposition": `attachment; filename=${event}_export.csv`,+ },+ });+});diff --git a/apps/web/app/api/analytics/events/route.ts b/apps/web/app/api/analytics/events/route.tsindex 3f5e42d215..25e7c3ae51 100644--- a/apps/web/app/api/analytics/events/route.ts+++ b/apps/web/app/api/analytics/events/route.ts@@ -1,6 +1,7 @@import { getEvents } from "@/lib/analytics/get-events";import { validDateRangeForPlan } from "@/lib/analytics/utils";import { getDomainOrThrow } from "@/lib/api/domains/get-domain";+import { throwIfClicksUsageExceeded } from "@/lib/api/errors";import { getLinkOrThrow } from "@/lib/api/links/get-link";import { withWorkspace } from "@/lib/auth";import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";@@ -9,6 +10,8 @@ import { NextResponse } from "next/server";export const GET = withWorkspace(async ({ searchParams, workspace }) => {+ throwIfClicksUsageExceeded(workspace);+const parsedParams = eventsQuerySchema.parse(searchParams);let { event, interval, start, end, linkId, externalId, domain, key } =@@ -47,7 +50,6 @@ export const GET = withWorkspace(return NextResponse.json(response);},{- needNotExceededClicks: true,betaFeature: true,},);diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.tsindex 35e26baaff..010ec552e3 100644--- a/apps/web/app/api/analytics/export/route.ts+++ b/apps/web/app/api/analytics/export/route.ts@@ -2,69 +2,67 @@ import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";import { getAnalytics } from "@/lib/analytics/get-analytics";import { convertToCSV, validDateRangeForPlan } from "@/lib/analytics/utils";import { getDomainOrThrow } from "@/lib/api/domains/get-domain";+import { throwIfClicksUsageExceeded } from "@/lib/api/errors";import { getLinkOrThrow } from "@/lib/api/links/get-link";import { withWorkspace } from "@/lib/auth";import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";import JSZip from "jszip";// GET /api/analytics/export – get export data for analytics-export const GET = withWorkspace(- async ({ searchParams, workspace }) => {- const parsedParams = analyticsQuerySchema.parse(searchParams);+export const GET = withWorkspace(async ({ searchParams, workspace }) => {+ throwIfClicksUsageExceeded(workspace);- const { interval, start, end, linkId, domain, key } = parsedParams;+ const parsedParams = analyticsQuerySchema.parse(searchParams);- if (domain) {- await getDomainOrThrow({ workspace, domain });- }+ const { interval, start, end, linkId, domain, key } = parsedParams;- const link =- domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;+ if (domain) {+ await getDomainOrThrow({ workspace, domain });+ }- validDateRangeForPlan({- plan: workspace.plan,- interval,- start,- end,- throwError: true,- });+ const link =+ domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;- const zip = new JSZip();+ validDateRangeForPlan({+ plan: workspace.plan,+ interval,+ start,+ end,+ throwError: true,+ });- await Promise.all(- VALID_ANALYTICS_ENDPOINTS.map(async (endpoint) => {- // no need to fetch top links data if linkId is defined- // since this is just a single link- if (endpoint === "top_links" && linkId) return;- // we're not fetching top URLs data if linkId is not defined- if (endpoint === "top_urls" && !linkId) return;- // skip clicks count- if (endpoint === "count") return;+ const zip = new JSZip();- const response = await getAnalytics({- ...parsedParams,- workspaceId: workspace.id,- ...(link && { linkId: link.id }),- event: "clicks",- groupBy: endpoint,- });- if (!response || response.length === 0) return;+ await Promise.all(+ VALID_ANALYTICS_ENDPOINTS.map(async (endpoint) => {+ // no need to fetch top links data if linkId is defined+ // since this is just a single link+ if (endpoint === "top_links" && linkId) return;+ // we're not fetching top URLs data if linkId is not defined+ if (endpoint === "top_urls" && !linkId) return;+ // skip clicks count+ if (endpoint === "count") return;- const csvData = convertToCSV(response);- zip.file(`${endpoint}.csv`, csvData);- }),- );+ const response = await getAnalytics({+ ...parsedParams,+ workspaceId: workspace.id,+ ...(link && { linkId: link.id }),+ event: "clicks",+ groupBy: endpoint,+ });+ if (!response || response.length === 0) return;- const zipData = await zip.generateAsync({ type: "nodebuffer" });+ const csvData = convertToCSV(response);+ zip.file(`${endpoint}.csv`, csvData);+ }),+ );- return new Response(zipData, {- headers: {- "Content-Type": "application/zip",- "Content-Disposition": "attachment; filename=analytics_export.zip",- },- });- },- {- needNotExceededClicks: true,- },-);+ const zipData = await zip.generateAsync({ type: "nodebuffer" });++ return new Response(zipData, {+ headers: {+ "Content-Type": "application/zip",+ "Content-Disposition": "attachment; filename=analytics_export.zip",+ },+ });+});diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.tsindex 9365738633..00a53aa32e 100644--- a/apps/web/app/api/analytics/route.ts+++ b/apps/web/app/api/analytics/route.ts@@ -2,6 +2,7 @@ import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";import { getAnalytics } from "@/lib/analytics/get-analytics";import { validDateRangeForPlan } from "@/lib/analytics/utils";import { getDomainOrThrow } from "@/lib/api/domains/get-domain";+import { throwIfClicksUsageExceeded } from "@/lib/api/errors";import { getLinkOrThrow } from "@/lib/api/links/get-link";import { withWorkspace } from "@/lib/auth";import {@@ -14,6 +15,8 @@ import { NextResponse } from "next/server";// GET /api/analytics – get analyticsexport const GET = withWorkspace(async ({ params, searchParams, workspace }) => {+ throwIfClicksUsageExceeded(workspace);+let { eventType: oldEvent, endpoint: oldType } =analyticsPathParamsSchema.parse(params);@@ -82,7 +85,4 @@ export const GET = withWorkspace(return NextResponse.json(response);},- {- needNotExceededClicks: true,- },);diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex d8a34431d6..37de492b37 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -1,4 +1,8 @@-import { DubApiError, exceededLimitError } from "@/lib/api/errors";+import {+ DubApiError,+ exceededLimitError,+ throwIfLinksUsageExceeded,+} from "@/lib/api/errors";import { bulkCreateLinks, combineTagIds, processLink } from "@/lib/api/links";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";@@ -17,8 +21,10 @@ export const POST = withWorkspace("Missing workspace. Bulk link creation is only available for custom domain workspaces.",});}- const bodyRaw = await parseRequestBody(req);- const links = bulkCreateLinksBodySchema.parse(bodyRaw);++ throwIfLinksUsageExceeded(workspace);++ const links = bulkCreateLinksBodySchema.parse(await parseRequestBody(req));if (workspace.linksUsage + links.length > workspace.linksLimit &&(workspace.plan === "free" || workspace.plan === "pro")@@ -124,7 +130,4 @@ export const POST = withWorkspace(headers,});},- {- needNotExceededLinks: true,- },);diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex da41afa426..4017108aa1 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -1,5 +1,9 @@import { getDomainOrThrow } from "@/lib/api/domains/get-domain";-import { DubApiError, ErrorCodes } from "@/lib/api/errors";+import {+ DubApiError,+ ErrorCodes,+ throwIfLinksUsageExceeded,+} from "@/lib/api/errors";import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";@@ -54,8 +58,9 @@ export const GET = withWorkspace(async ({ req, headers, workspace }) => {// POST /api/links – create a new linkexport const POST = withWorkspace(async ({ req, headers, session, workspace }) => {- const bodyRaw = await parseRequestBody(req);- const body = createLinkBodySchema.parse(bodyRaw);+ throwIfLinksUsageExceeded(workspace);++ const body = createLinkBodySchema.parse(await parseRequestBody(req));if (!session) {const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;@@ -101,7 +106,6 @@ export const POST = withWorkspace(}},{- needNotExceededLinks: true,allowAnonymous: true,},);diff --git a/apps/web/lib/api/errors.ts b/apps/web/lib/api/errors.tsindex bcce883c9a..993e89c029 100644--- a/apps/web/lib/api/errors.ts+++ b/apps/web/lib/api/errors.ts@@ -4,7 +4,7 @@ import { NextResponse } from "next/server";import { ZodError } from "zod";import { generateErrorMessage } from "zod-error";import { ZodOpenApiResponseObject } from "zod-openapi";-import { PlanProps } from "../types";+import { PlanProps, WorkspaceWithUsers } from "../types";export const ErrorCode = z.enum(["bad_request",@@ -221,3 +221,34 @@ export const exceededLimitError = ({limit === 1 ? type.slice(0, -1) : type} on the ${capitalize(plan)} plan. Please upgrade to add more ${type}.`;};++// Workspace clicks usage overage checks+export const throwIfClicksUsageExceeded = (workspace: WorkspaceWithUsers) => {+ if (workspace.usage > workspace.usageLimit) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: workspace.plan,+ limit: workspace.usageLimit,+ type: "clicks",+ }),+ });+ }+};++// Workspace links usage overage checks+export const throwIfLinksUsageExceeded = (workspace: WorkspaceWithUsers) => {+ if (+ workspace.linksUsage > workspace.linksLimit &&+ (workspace.plan === "free" || workspace.plan === "pro")+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: workspace.plan,+ limit: workspace.linksLimit,+ type: "links",+ }),+ });+ }+};diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex 6a120a67b4..5cf55f8766 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -1,8 +1,4 @@-import {- DubApiError,- exceededLimitError,- handleAndReturnErrorResponse,-} from "@/lib/api/errors";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { prisma } from "@/lib/prisma";import { PlanProps, WorkspaceWithUsers } from "@/lib/types";import { ratelimit } from "@/lib/upstash";@@ -43,16 +39,12 @@ export const withWorkspace = ("enterprise",], // if the action needs a specific planrequiredRole = ["owner", "member"],- needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage- needNotExceededLinks, // if the action needs the user to not have exceeded their links usageallowAnonymous, // special case for /api/links (POST /api/links) – allow no sessionallowSelf, // special case for removing yourself from a workspacebetaFeature, // if the action is a beta feature}: {requiredPlan?: Array<PlanProps>;requiredRole?: Array<"owner" | "member">;- needNotExceededClicks?: boolean;- needNotExceededLinks?: boolean;allowAnonymous?: boolean;allowSelf?: boolean;betaFeature?: boolean;@@ -266,34 +258,6 @@ export const withWorkspace = (});}- // clicks usage overage checks- if (needNotExceededClicks && workspace.usage > workspace.usageLimit) {- throw new DubApiError({- code: "forbidden",- message: exceededLimitError({- plan: workspace.plan,- limit: workspace.usageLimit,- type: "clicks",- }),- });- }-- // links usage overage checks- if (- needNotExceededLinks &&- workspace.linksUsage > workspace.linksLimit &&- (workspace.plan === "free" || workspace.plan === "pro")- ) {- throw new DubApiError({- code: "forbidden",- message: exceededLimitError({- plan: workspace.plan,- limit: workspace.linksLimit,- type: "links",- }),- });- }-// plan checksif (!requiredPlan.includes(workspace.plan)) {throw new DubApiError({