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.

Analytics

Kiran K69acafe95c6a
diff --git a/apps/web/app/api/analytics/[endpoint]/route.ts b/apps/web/app/api/analytics/[endpoint]/route.ts
index 53a0dcd8ff..723351143d 100644
--- a/apps/web/app/api/analytics/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/[endpoint]/route.ts
@@ -1,6 +1,6 @@
import { getAnalytics } from "@/lib/analytics";
import { withAuth } from "@/lib/auth";
-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { DubApiError } from "@/lib/api/errors";
import { getDomainViaEdge } from "@/lib/planetscale";
import {
getAnalyticsQuerySchema,
@@ -11,38 +11,34 @@ import { NextResponse } from "next/server";
// GET /api/analytics/[endpoint] – get analytics for a specific endpoint
export const GET = withAuth(
async ({ params, searchParams, project, link }) => {
- try {
- const { endpoint } = analyticsEndpointSchema.parse(params);
- const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
- const { domain, key, interval } = parsedParams;
+ const { endpoint } = analyticsEndpointSchema.parse(params);
+ const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
+ const { domain, key, interval } = parsedParams;
- // return 403 if project is on the free plan and interval is 90d or all
- if (
- project?.plan === "free" &&
- (interval === "all" || interval === "90d")
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "Require higher plan",
- });
- }
-
- const linkId = link
- ? link.id
- : domain && key === "_root"
- ? await getDomainViaEdge(domain).then((d) => d?.id)
- : null;
-
- const response = await getAnalytics({
- projectId: project.id,
- ...(linkId && { linkId }),
- endpoint,
- ...parsedParams,
+ // return 403 if project is on the free plan and interval is 90d or all
+ if (
+ project?.plan === "free" &&
+ (interval === "all" || interval === "90d")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Require higher plan",
});
- return NextResponse.json(response);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
}
+
+ const linkId = link
+ ? link.id
+ : domain && key === "_root"
+ ? await getDomainViaEdge(domain).then((d) => d?.id)
+ : null;
+
+ const response = await getAnalytics({
+ projectId: project.id,
+ ...(linkId && { linkId }),
+ endpoint,
+ ...parsedParams,
+ });
+ return NextResponse.json(response);
},
{
needNotExceededClicks: true,
diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
index 1e85ddd988..58e3898f7c 100644
--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
@@ -2,7 +2,6 @@ import { getAnalytics } from "@/lib/analytics";
import {
DubApiError,
exceededLimitError,
- handleAndReturnErrorResponse,
} from "@/lib/api/errors";
import { isBlacklistedReferrer } from "@/lib/edge-config";
import { getDomainOrLink, getProjectViaEdge } from "@/lib/planetscale";
@@ -26,84 +25,80 @@ export const GET = async (
req: NextRequest,
{ params }: { params: Record<string, string> },
) => {
- try {
- const searchParams = getSearchParams(req.url);
- const { endpoint } = analyticsEndpointSchema.parse(params);
- const parsedParams = getAnalyticsEdgeQuerySchema.parse(searchParams);
- const { domain, key, interval } = parsedParams;
+ const searchParams = getSearchParams(req.url);
+ const { endpoint } = analyticsEndpointSchema.parse(params);
+ const parsedParams = getAnalyticsEdgeQuerySchema.parse(searchParams);
+ const { domain, key, interval } = parsedParams;
- let link;
+ let link;
- // demo link (dub.sh/try)
- if (domain === "dub.sh" && key === "try") {
- // Rate limit in production
- if (process.env.NODE_ENV !== "development") {
- if (await isBlacklistedReferrer(req.headers.get("referer"))) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Don't DDoS me pls 🥺",
- });
- }
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit(
- 15,
- endpoint === "clicks" ? "10 s" : "1 h",
- ).limit(`${ip}:${domain}:${key}:${endpoint}`);
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Don't DDoS me pls 🥺",
- });
- }
- }
-
- link = {
- id: DEMO_LINK_ID,
- projectId: DUB_PROJECT_ID,
- };
- } else {
- link = await getDomainOrLink({ domain, key });
- // if the link is explicitly private (publicStats === false)
- if (!link?.publicStats) {
+ // demo link (dub.sh/try)
+ if (domain === "dub.sh" && key === "try") {
+ // Rate limit in production
+ if (process.env.NODE_ENV !== "development") {
+ if (await isBlacklistedReferrer(req.headers.get("referer"))) {
throw new DubApiError({
- code: "forbidden",
- message: "Analytics for this link are not public",
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
});
}
- const project =
- link?.projectId && (await getProjectViaEdge(link.projectId));
- if (
- (!project || project.plan === "free") &&
- (interval === "all" || interval === "90d")
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "Need higher plan",
- });
- }
- if (project && project.usage > project.usageLimit) {
+ const ip = ipAddress(req) || LOCALHOST_IP;
+ const { success } = await ratelimit(
+ 15,
+ endpoint === "clicks" ? "10 s" : "1 h",
+ ).limit(`${ip}:${domain}:${key}:${endpoint}`);
+
+ if (!success) {
throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: project.plan,
- limit: project.usageLimit,
- type: "clicks",
- }),
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
});
}
}
- const response = await getAnalytics({
- // projectId can be undefined (for public links that haven't been claimed/synced to a project)
- ...(link.projectId && { projectId: link.projectId }),
- linkId: link.id,
- endpoint,
- ...parsedParams,
- });
-
- return NextResponse.json(response);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
+ link = {
+ id: DEMO_LINK_ID,
+ projectId: DUB_PROJECT_ID,
+ };
+ } else {
+ link = await getDomainOrLink({ domain, key });
+ // if the link is explicitly private (publicStats === false)
+ if (!link?.publicStats) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Analytics for this link are not public",
+ });
+ }
+ const project =
+ link?.projectId && (await getProjectViaEdge(link.projectId));
+ if (
+ (!project || project.plan === "free") &&
+ (interval === "all" || interval === "90d")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Need higher plan",
+ });
+ }
+ if (project && project.usage > project.usageLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: project.plan,
+ limit: project.usageLimit,
+ type: "clicks",
+ }),
+ });
+ }
}
+
+ const response = await getAnalytics({
+ // projectId can be undefined (for public links that haven't been claimed/synced to a project)
+ ...(link.projectId && { projectId: link.projectId }),
+ linkId: link.id,
+ endpoint,
+ ...parsedParams,
+ });
+
+ return NextResponse.json(response);
};
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
index c2c521e990..391c5acdd2 100644
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@ -1,5 +1,4 @@
import { withAuth } from "@/lib/auth";
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getDomainOrLink } from "@/lib/planetscale";
import prisma from "@/lib/prisma";
import z, { domainKeySchema } from "@/lib/zod";
@@ -11,32 +10,24 @@ const updatePublicStatsSchema = z.object({
// GET /api/analytics – get the publicStats setting for a link
export const GET = withAuth(async ({ searchParams }) => {
- try {
- const { domain, key } = domainKeySchema.parse(searchParams);
- const response = await getDomainOrLink({ domain, key });
- return NextResponse.json(response);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
+ const { domain, key } = domainKeySchema.parse(searchParams);
+ const response = await getDomainOrLink({ domain, key });
+ return NextResponse.json(response);
});
// PUT /api/analytics – update the publicStats setting for a link
export const PUT = withAuth(async ({ req, searchParams }) => {
- try {
- const { domain, key } = domainKeySchema.parse(searchParams);
- const { publicStats } = updatePublicStatsSchema.parse(await req.json());
- const response =
- key === "_root"
- ? await prisma.domain.update({
- where: { slug: domain },
- data: { publicStats },
- })
- : await prisma.link.update({
- where: { domain_key: { domain, key } },
- data: { publicStats },
- });
- return NextResponse.json(response);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
+ const { domain, key } = domainKeySchema.parse(searchParams);
+ const { publicStats } = updatePublicStatsSchema.parse(await req.json());
+ const response =
+ key === "_root"
+ ? await prisma.domain.update({
+ where: { slug: domain },
+ data: { publicStats },
+ })
+ : await prisma.link.update({
+ where: { domain_key: { domain, key } },
+ data: { publicStats },
+ });
+ return NextResponse.json(response);
});
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index b5b33352c7..47ce9ea136 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -57,36 +57,36 @@ interface WithAuthHandler {
link?: LinkProps;
}): Promise<Response>;
}
-export const withAuth =
- (
- handler: WithAuthHandler,
- {
- requiredPlan = [
- "free",
- "pro",
- "business",
- "business plus",
- "business max",
- "business extra",
- "enterprise",
- ], // if the action needs a specific plan
- requiredRole = ["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 usage
- allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
- allowSelf, // special case for removing yourself from a project
- skipLinkChecks, // special case for /api/links/exists – skip link checks
- }: {
- requiredPlan?: Array<PlanProps>;
- requiredRole?: Array<"owner" | "member">;
- needNotExceededClicks?: boolean;
- needNotExceededLinks?: boolean;
- allowAnonymous?: boolean;
- allowSelf?: boolean;
- skipLinkChecks?: boolean;
- } = {},
- ) =>
- async (
+
+export const withAuth = (
+ handler: WithAuthHandler,
+ {
+ requiredPlan = [
+ "free",
+ "pro",
+ "business",
+ "business plus",
+ "business max",
+ "business extra",
+ "enterprise",
+ ], // if the action needs a specific plan
+ requiredRole = ["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 usage
+ allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
+ allowSelf, // special case for removing yourself from a project
+ skipLinkChecks, // special case for /api/links/exists – skip link checks
+ }: {
+ requiredPlan?: Array<PlanProps>;
+ requiredRole?: Array<"owner" | "member">;
+ needNotExceededClicks?: boolean;
+ needNotExceededLinks?: boolean;
+ allowAnonymous?: boolean;
+ allowSelf?: boolean;
+ skipLinkChecks?: boolean;
+ } = {},
+) => {
+ return async (
req: Request,
{ params }: { params: Record<string, string> | undefined },
) => {
@@ -399,7 +399,7 @@ export const withAuth =
}
}
- return handler({
+ return await handler({
req,
params: params || {},
searchParams,
@@ -410,9 +410,11 @@ export const withAuth =
link,
});
} catch (error) {
+ console.error("withAuth Error -->", error.message);
return handleAndReturnErrorResponse(error);
}
};
+};
interface WithSessionHandler {
({
@@ -515,8 +517,9 @@ export const withSession =
}
const searchParams = getSearchParams(req.url);
- return handler({ req, params, searchParams, session });
+ return await handler({ req, params, searchParams, session });
} catch (error) {
+ console.error("withSession Error -->", error.message);
return handleAndReturnErrorResponse(error);
}
};