The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor error handling for routes not using withAuth
Kiran Kc6cd62139980
diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.tsindex 58e3898f7c..1e85ddd988 100644--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts@@ -2,6 +2,7 @@ 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";@@ -25,80 +26,84 @@ export const GET = async (req: NextRequest,{ params }: { params: Record<string, string> },) => {- const searchParams = getSearchParams(req.url);- const { endpoint } = analyticsEndpointSchema.parse(params);- const parsedParams = getAnalyticsEdgeQuerySchema.parse(searchParams);- const { domain, key, interval } = parsedParams;+ try {+ 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"))) {+ // 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) {throw new DubApiError({- code: "rate_limit_exceeded",- message: "Don't DDoS me pls 🥺",+ code: "forbidden",+ message: "Analytics for this link are not public",});}- const ip = ipAddress(req) || LOCALHOST_IP;- const { success } = await ratelimit(- 15,- endpoint === "clicks" ? "10 s" : "1 h",- ).limit(`${ip}:${domain}:${key}:${endpoint}`);-- if (!success) {+ const project =+ link?.projectId && (await getProjectViaEdge(link.projectId));+ if (+ (!project || project.plan === "free") &&+ (interval === "all" || interval === "90d")+ ) {throw new DubApiError({- code: "rate_limit_exceeded",- message: "Don't DDoS me pls 🥺",+ 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",+ }),});}}- 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,- });+ 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);+ return NextResponse.json(response);+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }};diff --git a/apps/web/app/api/metatags/route.ts b/apps/web/app/api/metatags/route.tsindex 21180e6c54..806131af63 100644--- a/apps/web/app/api/metatags/route.ts+++ b/apps/web/app/api/metatags/route.ts@@ -1,4 +1,4 @@-import { DubApiError } from "@/lib/api/errors";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { ratelimit } from "@/lib/upstash";import z from "@/lib/zod";import { LOCALHOST_IP, isValidUrl } from "@dub/utils";@@ -14,34 +14,38 @@ const getMetaTagQuerySchema = z.object({export const runtime = "edge";export async function GET(req: NextRequest) {- const { url } = getMetaTagQuerySchema.parse({- url: req.nextUrl.searchParams.get("url"),- });+ try {+ const { url } = getMetaTagQuerySchema.parse({+ url: req.nextUrl.searchParams.get("url"),+ });- // Rate limit if user is not logged in- const session = await getToken({- req,- secret: process.env.NEXTAUTH_SECRET,- });- if (!session?.email) {- const ip = ipAddress(req) || LOCALHOST_IP;- const { success } = await ratelimit().limit(ip);- if (!success) {- throw new DubApiError({- code: "rate_limit_exceeded",- message: "Don't DDoS me pls 🥺",- });+ // Rate limit if user is not logged in+ const session = await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ });+ if (!session?.email) {+ const ip = ipAddress(req) || LOCALHOST_IP;+ const { success } = await ratelimit().limit(ip);+ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Don't DDoS me pls 🥺",+ });+ }}- }- const metatags = await getMetaTags(url);- return new Response(JSON.stringify(metatags), {- status: 200,- headers: {- "Content-Type": "application/json",- "Access-Control-Allow-Origin": "*",- },- });+ const metatags = await getMetaTags(url);+ return new Response(JSON.stringify(metatags), {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ "Access-Control-Allow-Origin": "*",+ },+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }}export function OPTIONS() {diff --git a/apps/web/app/api/qr/route.tsx b/apps/web/app/api/qr/route.tsxindex d76840a0c3..463b97d3c7 100644--- a/apps/web/app/api/qr/route.tsx+++ b/apps/web/app/api/qr/route.tsx@@ -1,4 +1,4 @@-import { DubApiError } from "@/lib/api/errors";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { QRCodeSVG } from "@/lib/qr/utils";import { ratelimit } from "@/lib/upstash";import { getQRCodeQuerySchema } from "@/lib/zod/schemas/qr";@@ -11,46 +11,50 @@ import { NextRequest } from "next/server";export const runtime = "edge";export async function GET(req: NextRequest) {- // Rate limit if user is not logged in- const session = await getToken({- req,- secret: process.env.NEXTAUTH_SECRET,- });- if (!session?.email) {- const ip = ipAddress(req) || LOCALHOST_IP;- const { success } = await ratelimit().limit(ip);- if (!success) {- throw new DubApiError({- code: "rate_limit_exceeded",- message: "Don't DDoS me pls 🥺",- });+ try {+ // Rate limit if user is not logged in+ const session = await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ });+ if (!session?.email) {+ const ip = ipAddress(req) || LOCALHOST_IP;+ const { success } = await ratelimit().limit(ip);+ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Don't DDoS me pls 🥺",+ });+ }}- }- const params = getSearchParams(req.url);- const { url, size, level, fgColor, bgColor, includeMargin } =- getQRCodeQuerySchema.parse(params);+ const params = getSearchParams(req.url);+ const { url, size, level, fgColor, bgColor, includeMargin } =+ getQRCodeQuerySchema.parse(params);- // const logo = req.nextUrl.searchParams.get("logo") || "https://assets.dub.co/logo.png";+ // const logo = req.nextUrl.searchParams.get("logo") || "https://assets.dub.co/logo.png";- return new ImageResponse(- QRCodeSVG({- value: url,- size,- level,- includeMargin,- fgColor,- bgColor,- // imageSettings: {- // src: logo,- // height: size / 4,- // width: size / 4,- // excavate: true,- // },- }),- {- width: size,- height: size,- },- );+ return new ImageResponse(+ QRCodeSVG({+ value: url,+ size,+ level,+ includeMargin,+ fgColor,+ bgColor,+ // imageSettings: {+ // src: logo,+ // height: size / 4,+ // width: size / 4,+ // excavate: true,+ // },+ }),+ {+ width: size,+ height: size,+ },+ );+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }}