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 and API response format
Kiran K5e2878a2fa1b
diff --git a/apps/web/app/api/projects/[slug]/tags/route.ts b/apps/web/app/api/projects/[slug]/tags/route.tsindex 1a8f63f230..77ea93014c 100644--- a/apps/web/app/api/projects/[slug]/tags/route.ts+++ b/apps/web/app/api/projects/[slug]/tags/route.ts@@ -3,25 +3,30 @@ import { withAuth } from "@/lib/auth";import prisma from "@/lib/prisma";import { randomBadgeColor } from "@/ui/links/tag-badge";import { NextResponse } from "next/server";-import { DubApiError, handleApiError } from "@/lib/errors";+import { DubApiError, ErrorResponse, handleApiError } from "@/lib/errors";import { createTagSchema, Tag } from "@/lib/zod/schemas/tags";// GET /api/projects/[slug]/tags - get all tags for a projectexport const GET = withAuth(async ({ project, headers }) => {- const tags = await prisma.tag.findMany({- where: {- projectId: project.id,- },- select: {- id: true,- name: true,- color: true,- },- orderBy: {- name: "asc",- },- });- return NextResponse.json<Tag[]>(tags, { headers });+ try {+ const tags = await prisma.tag.findMany({+ where: {+ projectId: project.id,+ },+ select: {+ id: true,+ name: true,+ color: true,+ },+ orderBy: {+ name: "asc",+ },+ });+ return NextResponse.json<{ data: Tag[] }>({ data: tags }, { headers });+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { headers, status });+ }});// POST /api/projects/[slug]/tags - create a tag for a project@@ -73,9 +78,12 @@ export const POST = withAuth(async ({ req, project, headers }) => {},});- return NextResponse.json<Tag>(response, { headers, status: 201 });+ return NextResponse.json<{ data: Tag }>(+ { data: response },+ { headers, status: 201 },+ );} catch (err) {const { error, status } = handleApiError(err);- return NextResponse.json(error, { ...headers, status });+ return NextResponse.json<ErrorResponse>({ error }, { headers, status });}});diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.tsindex da3efab3f7..1fb4d37ca6 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -8,6 +8,8 @@ import { API_DOMAIN, getSearchParams, isDubDomain } from "@dub/utils";import { ratelimit } from "../upstash";import { exceededLimitError } from "../api/errors";import { isAdmin } from "app/admin.dub.co/actions";+import { DubApiError, ErrorResponse, handleApiError } from "../errors";+import { NextResponse } from "next/server";export interface Session {user: {@@ -91,305 +93,305 @@ export const withAuth =let session: Session | undefined;let headers = {};- // if there's no projectSlug defined- if (!slug) {- if (allowAnonymous) {- // @ts-expect-error- return handler({- req,- params: params || {},- searchParams,- headers,- });- } else {- return new Response(- "Project slug not found. Did you forget to include a `projectSlug` query parameter?",- {- status: 400,- },- );+ try {+ // if there's no projectSlug defined+ if (!slug) {+ if (allowAnonymous) {+ // @ts-expect-error+ return handler({+ req,+ params: params || {},+ searchParams,+ headers,+ });+ } else {+ throw new DubApiError({+ code: "not_found",+ message:+ "Project slug not found. Did you forget to include a `projectSlug` query parameter?",+ });+ }}- }- const authorizationHeader = req.headers.get("Authorization");- if (authorizationHeader) {- if (!authorizationHeader.includes("Bearer ")) {- return new Response(- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://dub.sh/auth ",- {- status: 400,- },- );- }- const apiKey = authorizationHeader.replace("Bearer ", "");-- const url = new URL(req.url || "", API_DOMAIN);-- if (url.pathname.includes("/stats")) {- return new Response("API access is not available for stats yet.", {- status: 403,+ const authorizationHeader = req.headers.get("Authorization");+ if (authorizationHeader) {+ if (!authorizationHeader.includes("Bearer ")) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://dub.sh/auth",+ });+ }+ const apiKey = authorizationHeader.replace("Bearer ", "");++ const url = new URL(req.url || "", API_DOMAIN);++ if (url.pathname.includes("/stats")) {+ throw new DubApiError({+ code: "forbidden",+ message: "API access is not available for stats yet.",+ });+ }++ const hashedKey = hashToken(apiKey, {+ noSecret: true,});- }-- const hashedKey = hashToken(apiKey, {- noSecret: true,- });- const user = await prisma.user.findFirst({- where: {- tokens: {- some: {- hashedKey,+ const user = await prisma.user.findFirst({+ where: {+ tokens: {+ some: {+ hashedKey,+ },},},- },- select: {- id: true,- name: true,- email: true,- },- });- if (!user) {- return new Response("Unauthorized: Invalid API key.", {- status: 401,- });- }-- const { success, limit, reset, remaining } = await ratelimit(- 10,- "1 s",- ).limit(apiKey);-- headers = {- "Retry-After": reset.toString(),- "X-RateLimit-Limit": limit.toString(),- "X-RateLimit-Remaining": remaining.toString(),- "X-RateLimit-Reset": reset.toString(),- };-- if (!success) {- return new Response("Too many requests.", {- status: 429,- headers,+ select: {+ id: true,+ name: true,+ email: true,+ },});- }- await prisma.token.update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- });- session = {- user: {- id: user.id,- name: user.name || "",- email: user.email || "",- },- };- } else {- session = await getSession();- if (!session?.user?.id) {- return new Response("Unauthorized: Login required.", {- status: 401,- headers,+ if (!user) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Invalid API key.",+ });+ }++ const { success, limit, reset, remaining } = await ratelimit(+ 10,+ "1 s",+ ).limit(apiKey);++ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests.",+ });+ }+ await prisma.token.update({+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },});+ session = {+ user: {+ id: user.id,+ name: user.name || "",+ email: user.email || "",+ },+ };+ } else {+ session = await getSession();+ if (!session?.user?.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Login required.",+ });+ }}- }- const [project, link] = (await Promise.all([- prisma.project.findUnique({- where: {- slug,- },- select: {- id: true,- name: true,- slug: true,- logo: true,- usage: true,- usageLimit: true,- linksUsage: true,- linksLimit: true,- domainsLimit: true,- tagsLimit: true,- usersLimit: true,- plan: true,- stripeId: true,- billingCycleStart: true,- createdAt: true,- users: {- where: {- userId: session.user.id,- },- select: {- role: true,- },+ const [project, link] = (await Promise.all([+ prisma.project.findUnique({+ where: {+ slug,},- domains: {- select: {- slug: true,- primary: true,- },- },- metadata: true,- },- }),- linkId- ? prisma.link.findUnique({- where: {- id: linkId,+ select: {+ id: true,+ name: true,+ slug: true,+ logo: true,+ usage: true,+ usageLimit: true,+ linksUsage: true,+ linksLimit: true,+ domainsLimit: true,+ tagsLimit: true,+ usersLimit: true,+ plan: true,+ stripeId: true,+ billingCycleStart: true,+ createdAt: true,+ users: {+ where: {+ userId: session.user.id,+ },+ select: {+ role: true,+ },},- })- : domain && key && key !== "_root"- ? prisma.link.findUnique({- where: {- domain_key: {- domain,- key,+ domains: {+ select: {+ slug: true,+ primary: true,},},- })- : undefined,- ])) as [ProjectProps, LinkProps | undefined];-- if (!project || !project.users) {- // project doesn't exist- return new Response("Project not found.", {- status: 404,- headers,- });- }-- // prevent unauthorized access to domains that don't belong to the project- if (- domain &&- !isDubDomain(domain) &&- !project.domains.find((d) => d.slug === domain)- ) {- return new Response("Domain does not belong to project.", {- status: 403,- headers,- });- }-- // project exists but user is not part of it- if (project.users.length === 0) {- const pendingInvites = await prisma.projectInvite.findUnique({- where: {- email_projectId: {- email: session.user.email,- projectId: project.id,+ metadata: true,},- },- select: {- expires: true,- },- });- if (!pendingInvites) {- return new Response("Project not found.", {- status: 404,- headers,+ }),+ linkId+ ? prisma.link.findUnique({+ where: {+ id: linkId,+ },+ })+ : domain && key && key !== "_root"+ ? prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ })+ : undefined,+ ])) as [ProjectProps, LinkProps | undefined];++ if (!project || !project.users) {+ // project doesn't exist+ throw new DubApiError({+ code: "not_found",+ message: "Project not found.",});- } else if (pendingInvites.expires < new Date()) {- return new Response("Project invite expired.", {- status: 410,- headers,+ }++ // prevent unauthorized access to domains that don't belong to the project+ if (+ domain &&+ !isDubDomain(domain) &&+ !project.domains.find((d) => d.slug === domain)+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Domain does not belong to project.",});- } else {- return new Response("Project invite pending.", {- status: 409,- headers,+ }++ // project exists but user is not part of it+ if (project.users.length === 0) {+ const pendingInvites = await prisma.projectInvite.findUnique({+ where: {+ email_projectId: {+ email: session.user.email,+ projectId: project.id,+ },+ },+ select: {+ expires: true,+ },});+ if (!pendingInvites) {+ throw new DubApiError({+ code: "not_found",+ message: "Project not found.",+ });+ } else if (pendingInvites.expires < new Date()) {+ throw new DubApiError({+ code: "invite_expired",+ message: "Project invite expired.",+ });+ } else {+ throw new DubApiError({+ code: "invite_pending",+ message: "Project invite pending.",+ });+ }}- }- // project role checks (enterprise only)- if (- requiredRole &&- project.plan === "enterprise" &&- !requiredRole.includes(project.users[0].role) &&- !(allowSelf && searchParams.userId === session.user.id)- ) {- return new Response("Unauthorized: Insufficient permissions.", {- status: 403,- headers,- });- }+ // project role checks (enterprise only)+ if (+ requiredRole &&+ project.plan === "enterprise" &&+ !requiredRole.includes(project.users[0].role) &&+ !(allowSelf && searchParams.userId === session.user.id)+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Unauthorized: Insufficient permissions.",+ });+ }- // clicks usage overage checks- if (needNotExceededClicks && project.usage > project.usageLimit) {- return new Response(- exceededLimitError({- plan: project.plan,- limit: project.usageLimit,- type: "clicks",- }),- {- status: 403,- headers,- },- );- }+ // clicks usage overage checks+ if (needNotExceededClicks && project.usage > project.usageLimit) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: project.plan,+ limit: project.usageLimit,+ type: "clicks",+ }),+ });+ }- // links usage overage checks- if (- needNotExceededLinks &&- project.linksUsage > project.linksLimit &&- (project.plan === "free" || project.plan === "pro")- ) {- return new Response(- exceededLimitError({- plan: project.plan,- limit: project.linksLimit,- type: "links",- }),- {- status: 403,- headers,- },- );- }+ // links usage overage checks+ if (+ needNotExceededLinks &&+ project.linksUsage > project.linksLimit &&+ (project.plan === "free" || project.plan === "pro")+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: project.plan,+ limit: project.linksLimit,+ type: "links",+ }),+ });+ }- // plan checks- if (!requiredPlan.includes(project.plan)) {- // return res.status(403).end("Unauthorized: Need higher plan.");- return new Response("Unauthorized: Need higher plan.", {- status: 403,- headers,- });- }+ // plan checks+ if (!requiredPlan.includes(project.plan)) {+ // return res.status(403).end("Unauthorized: Need higher plan.");- // link checks (if linkId or domain and key are provided)- if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {- // if link doesn't exist- if (!link) {- return new Response("Link not found.", {- status: 404,- headers,+ throw new DubApiError({+ code: "forbidden",+ message: "Unauthorized: Need higher plan.",});}- // make sure the link is owned by the project- if (link.projectId !== project?.id) {- return new Response("Link not found.", {- status: 404,- headers,- });+ // link checks (if linkId or domain and key are provided)+ if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {+ // if link doesn't exist+ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: "Link not found.",+ });+ }++ // make sure the link is owned by the project+ if (link.projectId !== project?.id) {+ throw new DubApiError({+ code: "not_found",+ message: "Link not found.",+ });+ }}- }- return handler({- req,- params: params || {},- searchParams,- headers,- session,- project,- domain,- link,- });+ return handler({+ req,+ params: params || {},+ searchParams,+ headers,+ session,+ project,+ domain,+ link,+ });+ } catch (err) {+ const { error, status } = handleApiError(err);+ return NextResponse.json<ErrorResponse>({ error }, { headers, status });+ }};interface WithSessionHandler {diff --git a/apps/web/lib/errors.ts b/apps/web/lib/errors.tsindex 3ad5fd7c16..e703fe77ae 100644--- a/apps/web/lib/errors.ts+++ b/apps/web/lib/errors.ts@@ -15,7 +15,6 @@ const ErrorCode = z.enum(["invite_pending","exceeded_limit","conflict",-]);const errorCodeToHttpStatus: Record<z.infer<typeof ErrorCode>, number> = {@@ -56,7 +55,7 @@ const ErrorSchema = z.object({}),});-type ErrorResponse = z.infer<typeof ErrorSchema>;+export type ErrorResponse = z.infer<typeof ErrorSchema>;export class DubApiError extends Error {public readonly code: z.infer<typeof ErrorCode>;diff --git a/apps/web/lib/swr/use-tags.ts b/apps/web/lib/swr/use-tags.tsindex 7583d9b362..d43590b561 100644--- a/apps/web/lib/swr/use-tags.ts+++ b/apps/web/lib/swr/use-tags.ts@@ -6,7 +6,7 @@ import useSWR from "swr";export default function useTags() {const { slug } = useParams() as { slug?: string };- const { data: tags, isValidating } = useSWR<TagProps[]>(+ const { data: tags, isValidating } = useSWR<{ data: TagProps[] }>(slug && `/api/projects/${slug}/tags`,fetcher,{@@ -15,7 +15,7 @@ export default function useTags() {);return {- tags,+ tags: tags?.data,loading: tags ? false : true,isValidating,};diff --git a/apps/web/lib/zod/schemas/tags.ts b/apps/web/lib/zod/schemas/tags.tsindex b3d0a72d1b..ce1089aede 100644--- a/apps/web/lib/zod/schemas/tags.ts+++ b/apps/web/lib/zod/schemas/tags.ts@@ -46,7 +46,9 @@ export const createTag: ZodOpenApiOperationObject = {description: "The tag was created",content: {"application/json": {- schema: tagSchema,+ schema: z.object({+ data: tagSchema,+ }),},},},@@ -71,7 +73,9 @@ export const getTags: ZodOpenApiOperationObject = {description: "The tags were found",content: {"application/json": {- schema: z.array(tagSchema),+ schema: z.object({+ data: z.array(tagSchema),+ }),},},},diff --git a/apps/web/ui/modals/add-edit-link-modal/tags-section.tsx b/apps/web/ui/modals/add-edit-link-modal/tags-section.tsxindex f7bfbd675d..cc6211231a 100644--- a/apps/web/ui/modals/add-edit-link-modal/tags-section.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/tags-section.tsx@@ -1,5 +1,6 @@import useTags from "@/lib/swr/use-tags";import TagBadge from "@/ui/links/tag-badge";+import { extractApiErrorMessage } from "@/ui/utils";import { LoadingCircle, SimpleTooltipContent, Tooltip } from "@dub/ui";import { HOME_DOMAIN } from "@dub/utils";import { type Link as LinkProps } from "@prisma/client";@@ -49,11 +50,11 @@ export default function TagsSection({if (res.ok) {await mutate(`/api/projects/${slug}/tags`);const newTag = await res.json();- setData({ ...data, tagId: newTag.id });+ setData({ ...data, tagId: newTag.data.id });toast.success(`Successfully created tag!`);setCreatingTag(false);} else {- const error = await res.text();+ const error = extractApiErrorMessage(res);toast.error(error);}});diff --git a/apps/web/ui/utils.ts b/apps/web/ui/utils.tsnew file mode 100644index 0000000000..7587c2183f--- /dev/null+++ b/apps/web/ui/utils.ts@@ -0,0 +1,17 @@+// Keep this until we have move all error response to new JSON format+export const extractApiErrorMessage = async (response: Response) => {+ if (response.ok) {+ return null;+ }++ // If the response is JSON, try to parse it and extract the error message+ const contentType = response.headers.get("Content-Type");+ if (contentType === "application/json") {+ const { error } = await response.json();+ return error.message;+ }++ // If parsing JSON fails, treat it as plain text error+ const errorText = await response.text();+ return errorText;+};