The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add error handling for API requests
Kiran K0cc287d2033e
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 03a7474671..ec4aa63fcf 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -3,6 +3,7 @@ import { deleteLink, editLink, processLink } from "@/lib/api/links";import { NextResponse } from "next/server";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { qstash } from "@/lib/cron";+import { ErrorResponse, handleApiError } from "@/lib/errors";// GET /api/links/[linkId] – get a linkexport const GET = withAuth(async ({ headers, link }) => {diff --git a/apps/web/app/api/links/exists/route.ts b/apps/web/app/api/links/exists/route.tsindex 9cab80d7f8..7504e9bdf6 100644--- a/apps/web/app/api/links/exists/route.ts+++ b/apps/web/app/api/links/exists/route.ts@@ -1,18 +1,22 @@import { withAuth } from "@/lib/auth";import { checkIfKeyExists } from "@/lib/api/links";import { NextResponse } from "next/server";+import { ErrorResponse, handleApiError } from "@/lib/errors";+import { DomainKeySchema } from "@/lib/zod";-// GET /api//links/exists – check if a link exists+// GET /api/links/exists – check if a link existsexport const GET = withAuth(async ({ headers, searchParams }) => {- const { domain, key } = searchParams;- if (!domain || !key) {- return new Response("Missing domain or key", { status: 400 });+ try {+ const { domain, key } = DomainKeySchema.parse(searchParams);+ const response = await checkIfKeyExists(domain, key);+ return NextResponse.json(response, {+ headers,+ });+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { headers, status });}- const response = await checkIfKeyExists(domain, key);- return NextResponse.json(response, {- headers,- });},{ skipLinkChecks: true },);diff --git a/apps/web/app/api/links/random/route.ts b/apps/web/app/api/links/random/route.tsindex 5486d17691..c1058683ed 100644--- a/apps/web/app/api/links/random/route.ts+++ b/apps/web/app/api/links/random/route.ts@@ -3,7 +3,7 @@ import { getRandomKey } from "@/lib/api/links";import { NextResponse } from "next/server";// GET /api/links/random – get a random available link key-export const GET = withAuth(async ({ headers, searchParams }) => {+(async ({ headers, searchParams }) => {const { domain } = searchParams;if (!domain) {return new Response("Missing domain", { status: 400 });diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.tsindex 0db04c8ef4..339b5607f3 100644--- a/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.ts+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/exists/route.ts@@ -3,7 +3,7 @@ import { domainExists } from "@/lib/api/domains";import { NextResponse } from "next/server";// GET /api/projects/[slug]/domains/[domain]/exists – check if a domain exists-export const GET = withAuth(async ({ domain, project }) => {+export const GET = withAuth(async ({ domain }) => {const exists = await domainExists(domain);if (exists) {return NextResponse.json(1);diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/route.tsindex 72bad75a7f..9f7377f49f 100644--- a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts@@ -11,36 +11,41 @@ import {} from "@/lib/api/domains";import { NextResponse } from "next/server";import { DUB_PROJECT_ID, isDubDomain } from "@dub/utils";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";// GET /api/projects/[slug]/domains/[domain] – get a project's domainexport const GET = withAuth(async ({ domain, project }) => {- if (isDubDomain(domain) && project.id !== DUB_PROJECT_ID) {- return new Response("Domain does not belong to project.", {- status: 403,+ try {+ if (isDubDomain(domain) && project.id !== DUB_PROJECT_ID) {+ throw new DubApiError({+ code: "forbidden",+ message: "Domain does not belong to project.",+ });+ }++ const data = await prisma.domain.findUniqueOrThrow({+ where: {+ slug: domain,+ },+ select: {+ slug: true,+ verified: true,+ primary: true,+ target: true,+ type: true,+ placeholder: true,+ clicks: true,+ },});- }- const data = await prisma.domain.findUnique({- where: {- slug: domain,- },- select: {- slug: true,- verified: true,- primary: true,- target: true,- type: true,- placeholder: true,- clicks: true,- },- });- if (!data) {- return new Response("Domain not found", { status: 404 });+ return NextResponse.json({+ ...data,+ url: data.target,+ });+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { status });}- return NextResponse.json({- ...data,- url: data.target,- });});// PUT /api/projects/[slug]/domains/[domain] – edit a project's domaindiff --git a/apps/web/app/api/projects/[slug]/import/bitly/route.ts b/apps/web/app/api/projects/[slug]/import/bitly/route.tsindex 6889845b71..2d0e6dbe11 100644--- a/apps/web/app/api/projects/[slug]/import/bitly/route.ts+++ b/apps/web/app/api/projects/[slug]/import/bitly/route.ts@@ -1,6 +1,7 @@import { addDomainToVercel } from "@/lib/api/domains";import { withAuth } from "@/lib/auth";import { qstash } from "@/lib/cron";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";import prisma from "@/lib/prisma";import { BitlyGroupProps } from "@/lib/types";import { redis } from "@/lib/upstash";@@ -9,43 +10,54 @@ import { NextResponse } from "next/server";// GET /api/projects/[slug]/import/bitly – get all bitly groups for a projectexport const GET = withAuth(async ({ project }) => {- const accessToken = await redis.get(`import:bitly:${project.id}`);- if (!accessToken) {- return new Response("No Bitly access token found", { status: 400 });- }- const response = await fetch(`https://api-ssl.bitly.com/v4/groups`, {- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${accessToken}`,- },- });- const data = await response.json();- if (data.message === "FORBIDDEN") {- return new Response("Invalid Bitly access token", { status: 403 });- }+ try {+ const accessToken = await redis.get(`import:bitly:${project.id}`);+ if (!accessToken) {+ throw new DubApiError({+ code: "bad_request",+ message: "No Bitly access token found",+ });+ }+ const response = await fetch(`https://api-ssl.bitly.com/v4/groups`, {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${accessToken}`,+ },+ });+ const data = await response.json();+ if (data.message === "FORBIDDEN") {+ throw new DubApiError({+ code: "forbidden",+ message: "Invalid Bitly access token",+ });+ }- const groups = data.groups- // filter for active groups only- .filter(({ is_active }) => is_active) as BitlyGroupProps[];+ const groups = data.groups+ // filter for active groups only+ .filter(({ is_active }) => is_active) as BitlyGroupProps[];- const groupsWithTags = await Promise.all(- groups.map(async (group) => ({- ...group,- tags: await fetch(- `https://api-ssl.bitly.com/v4/groups/${group.guid}/tags`,- {- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${accessToken}`,+ const groupsWithTags = await Promise.all(+ groups.map(async (group) => ({+ ...group,+ tags: await fetch(+ `https://api-ssl.bitly.com/v4/groups/${group.guid}/tags`,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${accessToken}`,+ },},- },- )- .then((r) => r.json())- .then((r) => r.tags),- })),- ).then((g) => g.filter(({ bsds }) => bsds.length > 0));+ )+ .then((r) => r.json())+ .then((r) => r.tags),+ })),+ ).then((g) => g.filter(({ bsds }) => bsds.length > 0));- return NextResponse.json(groupsWithTags);+ return NextResponse.json(groupsWithTags);+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { status });+ }});// POST /api/projects/[slug]/import/bitly - create job to import links from bitlydiff --git a/apps/web/app/api/projects/[slug]/import/rebrandly/route.ts b/apps/web/app/api/projects/[slug]/import/rebrandly/route.tsindex fa394be877..d41bb172d9 100644--- a/apps/web/app/api/projects/[slug]/import/rebrandly/route.ts+++ b/apps/web/app/api/projects/[slug]/import/rebrandly/route.ts@@ -1,6 +1,7 @@import { addDomainToVercel } from "@/lib/api/domains";import { withAuth } from "@/lib/auth";import { qstash } from "@/lib/cron";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";import prisma from "@/lib/prisma";import { redis } from "@/lib/upstash";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";@@ -8,53 +9,64 @@ import { NextResponse } from "next/server";// GET /api/projects/[slug]/import/rebrandly – get all Rebrandly domains for a projectexport const GET = withAuth(async ({ project }) => {- const accessToken = await redis.get(`import:rebrandly:${project.id}`);- if (!accessToken) {- return new Response("No Rebrandly access token found", { status: 400 });- }+ try {+ const accessToken = await redis.get(`import:rebrandly:${project.id}`);+ if (!accessToken) {+ throw new DubApiError({+ code: "bad_request",+ message: "No Rebrandly access token found",+ });+ }- const response = await fetch(`https://api.rebrandly.com/v1/domains`, {- headers: {- "Content-Type": "application/json",- apikey: accessToken as string,- },- });- const data = await response.json();- if (data.error === "Unauthorized") {- return new Response("Invalid Rebrandly access token", { status: 403 });- }+ const response = await fetch(`https://api.rebrandly.com/v1/domains`, {+ headers: {+ "Content-Type": "application/json",+ apikey: accessToken as string,+ },+ });+ const data = await response.json();+ if (data.error === "Unauthorized") {+ throw new DubApiError({+ code: "forbidden",+ message: "Invalid Rebrandly access token",+ });+ }- const domains = await Promise.all(- data- .filter(({ fullName }) => fullName !== "rebrand.ly")- .map(async ({ id, fullName }: { id: number; fullName: string }) => ({- id,- domain: fullName,- links: await fetch(- `https://api.rebrandly.com/v1/links/count?domain.id=${id}`,- {- headers: {- "Content-Type": "application/json",- apikey: accessToken as string,+ const domains = await Promise.all(+ data+ .filter(({ fullName }) => fullName !== "rebrand.ly")+ .map(async ({ id, fullName }: { id: number; fullName: string }) => ({+ id,+ domain: fullName,+ links: await fetch(+ `https://api.rebrandly.com/v1/links/count?domain.id=${id}`,+ {+ headers: {+ "Content-Type": "application/json",+ apikey: accessToken as string,+ },},- },- )- .then((r) => r.json())- .then((data) => data.count) // subtract 1 to exclude root domain- .catch(() => 0),- })),- );+ )+ .then((r) => r.json())+ .then((data) => data.count) // subtract 1 to exclude root domain+ .catch(() => 0),+ })),+ );- const tagsCount = await fetch("https://api.rebrandly.com/v1/tags/count", {- headers: {- "Content-Type": "application/json",- apikey: accessToken as string,- },- })- .then((r) => r.json())- .then((data) => data.count);+ const tagsCount = await fetch("https://api.rebrandly.com/v1/tags/count", {+ headers: {+ "Content-Type": "application/json",+ apikey: accessToken as string,+ },+ })+ .then((r) => r.json())+ .then((data) => data.count);- return NextResponse.json({ domains, tagsCount });+ return NextResponse.json({ domains, tagsCount });+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { status });+ }});// PUT /api/projects/[slug]/import/rebrandly - save Rebrandly API keydiff --git a/apps/web/app/api/projects/[slug]/import/short/route.ts b/apps/web/app/api/projects/[slug]/import/short/route.tsindex 626266360a..8b8c7496e5 100644--- a/apps/web/app/api/projects/[slug]/import/short/route.ts+++ b/apps/web/app/api/projects/[slug]/import/short/route.ts@@ -1,6 +1,7 @@import { addDomainToVercel } from "@/lib/api/domains";import { withAuth } from "@/lib/auth";import { qstash } from "@/lib/cron";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";import prisma from "@/lib/prisma";import { redis } from "@/lib/upstash";import { APP_DOMAIN_WITH_NGROK, fetchWithTimeout } from "@dub/utils";@@ -8,42 +9,53 @@ import { NextResponse } from "next/server";// GET /api/projects/[slug]/import/short – get all short.io domains for a projectexport const GET = withAuth(async ({ project }) => {- const accessToken = await redis.get(`import:short:${project.id}`);- if (!accessToken) {- return new Response("No Short.io access token found", { status: 400 });- }+ try {+ const accessToken = await redis.get(`import:short:${project.id}`);+ if (!accessToken) {+ throw new DubApiError({+ code: "bad_request",+ message: "No Short.io access token found",+ });+ }- const response = await fetch(`https://api.short.io/api/domains`, {- headers: {- "Content-Type": "application/json",- Authorization: accessToken as string,- },- });- const data = await response.json();- if (data.error === "Unauthorized") {- return new Response("Invalid Short.io access token", { status: 403 });- }+ const response = await fetch(`https://api.short.io/api/domains`, {+ headers: {+ "Content-Type": "application/json",+ Authorization: accessToken as string,+ },+ });+ const data = await response.json();+ if (data.error === "Unauthorized") {+ throw new DubApiError({+ code: "forbidden",+ message: "Invalid Short.io access token",+ });+ }- const domains = await Promise.all(- data.map(async ({ id, hostname }: { id: number; hostname: string }) => ({- id,- domain: hostname,- links: await fetchWithTimeout(- `https://api-v2.short.cm/statistics/domain/${id}?period=total`,- {- headers: {- "Content-Type": "application/json",- Authorization: accessToken as string,+ const domains = await Promise.all(+ data.map(async ({ id, hostname }: { id: number; hostname: string }) => ({+ id,+ domain: hostname,+ links: await fetchWithTimeout(+ `https://api-v2.short.cm/statistics/domain/${id}?period=total`,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: accessToken as string,+ },},- },- )- .then((r) => r.json())- .then((data) => data.links - 1) // subtract 1 to exclude root domain- .catch(() => 0),- })),- );+ )+ .then((r) => r.json())+ .then((data) => data.links - 1) // subtract 1 to exclude root domain+ .catch(() => 0),+ })),+ );- return NextResponse.json(domains);+ return NextResponse.json(domains);+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { status });+ }});// PUT /api/projects/[slug]/import/short - save Short.io API keydiff --git a/apps/web/app/api/projects/[slug]/route.ts b/apps/web/app/api/projects/[slug]/route.tsindex 5e90a06bbf..65b87717e8 100644--- a/apps/web/app/api/projects/[slug]/route.ts+++ b/apps/web/app/api/projects/[slug]/route.ts@@ -9,12 +9,7 @@ import { Project } from "@/lib/zod/schemas/projects";// GET /api/projects/[slug] – get a specific projectexport const GET = withAuth(async ({ project, headers }) => {- try {- return NextResponse.json(project, { headers });- } catch (err) {- const { error, status } = handleApiError(err);- return NextResponse.json<ErrorResponse>({ error }, { headers, status });- }+ return NextResponse.json(project, { headers });});// PUT /api/projects/[slug] – update a specific projectdiff --git a/apps/web/app/api/projects/[slug]/scim/route.ts b/apps/web/app/api/projects/[slug]/scim/route.tsindex bce7411b23..be356cdef0 100644--- a/apps/web/app/api/projects/[slug]/scim/route.ts+++ b/apps/web/app/api/projects/[slug]/scim/route.ts@@ -1,23 +1,32 @@import { withAuth } from "@/lib/auth";import { NextResponse } from "next/server";import jackson from "@/lib/jackson";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";// GET /api/projects/[slug]/scim – get all SCIM directoriesexport const GET = withAuth(async ({ project }) => {const { directorySyncController } = await jackson();- const { data, error } =- await directorySyncController.directories.getByTenantAndProduct(- project.id,- "Dub",- );- if (error) {- return new Response(error.message, { status: 500 });- }+ try {+ const { data, error } =+ await directorySyncController.directories.getByTenantAndProduct(+ project.id,+ "Dub",+ );+ if (error) {+ throw new DubApiError({+ code: "internal_server_error",+ message: error.message,+ });+ }- return NextResponse.json({- directories: data,- });+ return NextResponse.json({+ directories: data,+ });+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { status });+ }});// POST /api/projects/[slug]/scim – create a new SCIM directorydiff --git a/apps/web/app/api/stats/[endpoint]/route.ts b/apps/web/app/api/stats/[endpoint]/route.tsindex 901a327137..91eafab9f4 100644--- a/apps/web/app/api/stats/[endpoint]/route.ts+++ b/apps/web/app/api/stats/[endpoint]/route.ts@@ -1,35 +1,51 @@import { withAuth } from "@/lib/auth";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";import { getStats } from "@/lib/stats";import { NextResponse } from "next/server";+import { z } from "zod";++const QueryParamsSchema = z.object({+ domain: z.string().min(1),+ key: z.string().optional(),+ interval: z.enum(["all", "90d"]),+});// GET /api/stats/[endpoint] – get stats for a specific endpointexport const GET = withAuth(async ({ params, searchParams, project }) => {- const { endpoint } = params;- let { domain, key, interval } = searchParams;+ try {+ const { endpoint } = params;+ let { domain, key, interval } = QueryParamsSchema.parse(searchParams);- // TODO: remove this logic after #545 merges- if (!domain && project.domains.length > 0) {- domain = project.domains.map((d) => d.slug).join(",");- }+ // TODO: remove this logic after #545 merges+ if (!domain && project.domains.length > 0) {+ domain = project.domains.map((d) => d.slug).join(",");+ }- // return 403 if project is on the free plan and interval is 90d or all- if (- project?.plan === "free" &&- (interval === "all" || interval === "90d")- ) {- return new Response(`Require higher plan`, { status: 403 });- }+ // 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 response = await getStats({- projectId: project.id,- domain,- key,- endpoint,- interval,- ...searchParams,- });- return NextResponse.json(response);+ const response = await getStats({+ projectId: project.id,+ domain,+ key: key as string,+ endpoint,+ interval,+ ...searchParams,+ });+ return NextResponse.json(response);+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { status });+ }},{needNotExceededClicks: true,