The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add zod validation and openapi specs for links APIs
Kiran Kebf7e5bf12fd
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex ec4aa63fcf..edf8c80f10 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -3,7 +3,8 @@ 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";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";+import { CreateLinkBodySchema } from "@/lib/zod/schemas/links";// GET /api/links/[linkId] – get a linkexport const GET = withAuth(async ({ headers, link }) => {@@ -15,71 +16,56 @@ export const GET = withAuth(async ({ headers, link }) => {// PUT /api/links/[linkId] – update a linkexport const PUT = withAuth(async ({ req, headers, project, link }) => {- let body;try {- body = await req.json();- } catch (error) {- return new Response("Missing or invalid body.", { status: 400, headers });- }- if (Object.keys(body).length === 0) {- return new Response("No fields to update.", { status: 304, headers });- }+ const body = CreateLinkBodySchema.parse(await req.json());- const updatedLink = {- ...link,- ...body,- };+ const updatedLink = {+ ...link,+ ...body,+ };- if (updatedLink.projectId !== link?.projectId) {- return new Response(- "Transferring links to another project is not yet supported.",- {- status: 403,- headers,- },- );- }+ if (updatedLink.projectId !== link?.projectId) {+ throw new DubApiError({+ code: "forbidden",+ message: "Transferring links to another project is not yet supported.",+ });+ }- const {- link: processedLink,- error,- status,- } = await processLink({- payload: updatedLink,- project,- });+ const { link: processedLink } = await processLink({+ payload: updatedLink as any, // TODO: fix types+ project,+ });- if (error) {- return new Response(error, { status, headers });- }+ const [response, _] = await Promise.allSettled([+ editLink({+ // link is guaranteed to exist because if not we will return 404+ domain: link!.domain,+ key: link!.key,+ updatedLink: processedLink as any, // TODO: fix types+ }),+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,+ body: {+ linkId: link!.id,+ type: "edit",+ },+ }),+ // @ts-ignore+ ]).then((results) => results.map((result) => result.value));- const [response, _] = await Promise.allSettled([- editLink({- // link is guaranteed to exist because if not we will return 404- domain: link!.domain,- key: link!.key,- updatedLink: processedLink,- }),- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,- body: {- linkId: link!.id,- type: "edit",- },- }),- // @ts-ignore- ]).then((results) => results.map((result) => result.value));+ if (response === null) {+ throw new DubApiError({+ code: "conflict",+ message: "Duplicate key: This short link already exists.",+ });+ }- if (response === null) {- return new Response("Duplicate key: This short link already exists.", {- status: 409,+ return NextResponse.json(response, {headers,});+ } catch (err) {+ return handleAndReturnErrorResponse(err, headers);}-- return NextResponse.json(response, {- headers,- });});// DELETE /api/links/[linkId] – delete a linkdiff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex ed8ecebdec..2b1761f387 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -1,9 +1,9 @@import { addLink, getLinksForProject, processLink } from "@/lib/api/links";import { withAuth } from "@/lib/auth";import { qstash } from "@/lib/cron";-import { handleAndReturnErrorResponse } from "@/lib/errors";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";import { ratelimit } from "@/lib/upstash";-import { GetLinksQuery } from "@/lib/zod/schemas/links";+import { CreateLinkBodySchema, GetLinksQuery } from "@/lib/zod/schemas/links";import { APP_DOMAIN_WITH_NGROK, LOCALHOST_IP } from "@dub/utils";import { NextResponse } from "next/server";@@ -34,53 +34,49 @@ export const GET = withAuth(async ({ headers, searchParams, project }) => {// POST /api/links – create a new linkexport const POST = withAuth(async ({ req, headers, session, project }) => {- let body;try {- body = await req.json();- } catch (error) {- return new Response("Missing or invalid body.", { status: 400, headers });- }+ const body = CreateLinkBodySchema.parse(await req.json());- if (!session) {- const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;- const { success } = await ratelimit(10, "1 d").limit(ip);+ if (!session) {+ const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;+ const { success } = await ratelimit(10, "1 d").limit(ip);- if (!success) {- return new Response(- "Rate limited – you can only create up to 10 links per day without an account.",- { status: 429 },- );+ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message:+ "Rate limited – you can only create up to 10 links per day without an account.",+ });+ }}- }-- const { link, error, status } = await processLink({- payload: body,- project,- session,- });- if (error) {- return new Response(error, { status, headers });- }+ const { link } = await processLink({+ payload: body,+ project,+ session,+ });- const response = await addLink(link);+ const response = await addLink(link);- if (response === null) {- return new Response("Duplicate key: This short link already exists.", {- status: 409,- headers,- });- }+ if (response === null) {+ throw new DubApiError({+ code: "conflict",+ message: "Duplicate key: This short link already exists.",+ });+ }- await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,- body: {- linkId: response.id,- type: "create",- },- });+ // await qstash.publishJSON({+ // url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,+ // body: {+ // linkId: response.id,+ // type: "create",+ // },+ // });- return NextResponse.json(response, { headers });+ return NextResponse.json(response, { headers });+ } catch (err) {+ return handleAndReturnErrorResponse(err, headers);+ }},{needNotExceededLinks: true,diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 80a175f465..205f0093e6 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -23,7 +23,9 @@ import cloudinary from "cloudinary";import { LinkProps, ProjectProps, RedisLinkProps } from "../types";import { Session } from "../auth";import { getLinkViaEdge } from "../planetscale";-import { GetLinksCountParams } from "../zod";+import z, { GetLinksCountParams } from "../zod";+import { CreateLinkBody } from "../zod/schemas/links";+import { DubApiError } from "../errors";export async function getLinksForProject({projectId,@@ -37,7 +39,7 @@ export async function getLinksForProject({}: {projectId: string;domain?: string;- tagId?: string;+ tagId?: string | null;search?: string;sort?: "createdAt" | "clicks" | "lastClicked"; // descending for allpage?: number;@@ -208,7 +210,7 @@ export async function processLink({session,bulk = false,}: {- payload: LinkProps;+ payload: CreateLinkBody;project?: ProjectProps;session?: Session;bulk?: boolean;@@ -227,41 +229,30 @@ export async function processLink({geo,} = payload;- // url checks- if (!url) {- return {- link: payload,- error: "Missing destination url.",- status: 400,- };- }const processedUrl = getUrlFromString(url);if (!processedUrl) {- return {- link: payload,- error: "Invalid destination url.",- status: 422,- };+ throw new DubApiError({+ code: "unprocessible_entity",+ message: "Invalid destination url.",+ });}// free plan restrictionsif (!project || project.plan === "free") {if (proxy || password || rewrite || expiresAt || ios || android || geo) {- return {- link: payload,- error:+ throw new DubApiError({+ code: "forbidden",+ message:"You can only use custom social media cards, password-protection, link cloaking, link expiration, device and geo targeting on a Pro plan and above. Upgrade to Pro to use these features.",- status: 403,- };+ });}// can't use `/` in key on free planif (key?.includes("/")) {- return {- link: payload,- error:+ throw new DubApiError({+ code: "unprocessible_entity",+ message:"Key cannot contain '/'. You can only use this on a Pro plan and above. Upgrade to Pro to use this feature.",- status: 422,- };+ });}}@@ -272,21 +263,19 @@ export async function processLink({// checks for default short domainif (domain === SHORT_DOMAIN) {- const keyBlacklisted = await isBlacklistedKey(key);+ const keyBlacklisted = await isBlacklistedKey(key!);if (keyBlacklisted) {- return {- link: payload,- error: "Invalid key.",- status: 422,- };+ throw new DubApiError({+ code: "unprocessible_entity",+ message: "Invalid key.",+ });}const domainBlacklisted = await isBlacklistedDomain(url);if (domainBlacklisted) {- return {- link: payload,- error: "Invalid url.",- status: 422,- };+ throw new DubApiError({+ code: "unprocessible_entity",+ message: "Invalid url.",+ });}// checks for other Dub-owned domains (chatg.pt, spti.fi, etc.)@@ -295,22 +284,20 @@ export async function processLink({const { allowedHostnames } = DUB_DOMAINS.find((d) => d.slug === domain)!;const urlDomain = getDomainWithoutWWW(url) || "";if (!allowedHostnames.includes(urlDomain)) {- return {- link: payload,- error: `Invalid url. You can only use ${domain} short links for URLs starting with ${allowedHostnames+ throw new DubApiError({+ code: "unprocessible_entity",+ message: `Invalid url. You can only use ${domain} short links for URLs starting with ${allowedHostnames.map((d) => `\`${d}\``).join(", ")}.`,- status: 422,- };+ });}// else, check if the domain belongs to the project} else if (!project?.domains?.find((d) => d.slug === domain)) {- return {- link: payload,- error: "Domain does not belong to project.",- status: 403,- };+ throw new DubApiError({+ code: "forbidden",+ message: "Domain does not belong to project.",+ });}if (!key) {@@ -319,57 +306,33 @@ export async function processLink({if (bulk) {if (image) {- return {- link: payload,- error: "You cannot set custom social cards with bulk link creation.",- status: 422,- };+ throw new DubApiError({+ code: "unprocessible_entity",+ message: "You cannot set custom social cards with bulk link creation.",+ });}if (rewrite) {- return {- link: payload,- error: "You cannot use link cloaking with bulk link creation.",- status: 422,- };+ throw new DubApiError({+ code: "unprocessible_entity",+ message: "You cannot use link cloaking with bulk link creation.",+ });}const exists = await checkIfKeyExists(domain, key);if (exists) {- return {- link: payload,- error: `Link already exists.`,- status: 409,- };+ throw new DubApiError({+ code: "conflict",+ message: "Link already exists.",+ });}}// custom social media image checksconst uploadedImage = image && image.startsWith("data:image") ? true : false;if (uploadedImage && !process.env.CLOUDINARY_URL) {- return {- link: payload,- error: "Missing Cloudinary environment variable.",- status: 400,- };- }-- // expire date checks- if (expiresAt) {- const date = new Date(expiresAt);- if (isNaN(date.getTime())) {- return {- link: payload,- error: "Invalid expiry date. Expiry date must be in ISO-8601 format.",- status: 422,- };- }- // check if expiresAt is in the future- if (new Date(expiresAt) < new Date()) {- return {- link: payload,- error: "Expiry date must be in the future.",- status: 422,- };- }+ throw new DubApiError({+ code: "unprocessible_entity",+ message: "Missing Cloudinary environment variable.",+ });}// remove shortLink & qrCode attributes from payload since it's a polyfill@@ -394,7 +357,9 @@ export async function processLink({};}-export async function addLink(link: LinkProps) {+export async function addLink(+ link: CreateLinkBody & Pick<LinkProps, "domain" | "key">,+) {const { domain, key, url, expiresAt, title, description, image, proxy, geo } =link;const uploadedImage = image && image.startsWith("data:image") ? true : false;@@ -409,8 +374,8 @@ export async function addLink(link: LinkProps) {data: {...link,key,- title: truncate(title, 120),- description: truncate(description, 240),+ title: truncate(title || "", 120),+ description: truncate(description || "", 240),image: uploadedImage ? undefined : image,utm_source,utm_medium,diff --git a/apps/web/lib/errors.ts b/apps/web/lib/errors.tsindex ea0fd7e35b..ea6256440f 100644--- a/apps/web/lib/errors.ts+++ b/apps/web/lib/errors.ts@@ -16,6 +16,7 @@ const ErrorCode = z.enum(["invite_pending","exceeded_limit","conflict",+ "unprocessible_entity",]);const errorCodeToHttpStatus: Record<z.infer<typeof ErrorCode>, number> = {@@ -29,6 +30,7 @@ const errorCodeToHttpStatus: Record<z.infer<typeof ErrorCode>, number> = {invite_pending: 409,exceeded_limit: 403,conflict: 409,+ unprocessible_entity: 422,};const prismaErrorMapping: Record<@@ -153,5 +155,6 @@ export function handleAndReturnErrorResponse(headers?: Record<string, string>,) {const { error, status } = handleApiError(err);+ console.error(error);return NextResponse.json<ErrorResponse>({ error }, { headers, status });}diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 2557069d3a..c825f68d87 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -4,8 +4,6 @@ import { ZodOpenApiOperationObject, ZodOpenApiPathsObject } from "zod-openapi";export const LinkSchemaOpenApi = LinkSchema;-export type Link = z.infer<typeof LinkSchema>;-export const GetLinkInfoQuery = z.object({projectSlug: z.string().openapi({description:@@ -52,9 +50,96 @@ export const GetLinksQuery = z.object({description:"Whether to include archived links in the response. Defaults to `false` if not provided.",}),-})+});++export const CreateLinkBodySchema = z.object({+ domain: z.string().optional().openapi({+ description:+ "The domain of the short link. If not provided, the primary domain for the project will be used (or `dub.sh` if the project has no domains).",+ }),+ key: z.string().optional().openapi({+ description:+ "The short link slug. If not provided, a random 7-character slug will be generated.",+ }),+ url: z.string().url().openapi({+ description: "The destination URL of the short link.",+ }),+ archived: z.boolean().optional().openapi({+ description: "Whether the short link is archived.",+ default: false,+ }),+ expiresAt: z+ .string()+ .datetime({+ message: "Invalid expiry date. Expiry date must be in ISO-8601 format.",+ })+ .optional()+ .nullable()+ .openapi({+ description:+ "The date and time when the short link will expire in ISO-8601 format. Must be in the future.",+ })+ .refine(+ (expiresAt) => {+ return expiresAt ? new Date(expiresAt) > new Date() : true;+ },+ {+ message: "Expiry date must be in the future.",+ },+ ),+ password: z.string().optional().nullable().openapi({+ description:+ "The password required to access the destination URL of the short link.",+ }),+ proxy: z.boolean().optional().openapi({+ description:+ "Whether the short link uses Custom Social Media Cards feature.",+ default: false,+ }),+ title: z.string().optional().openapi({+ description:+ "The title of the short link generated via `api.dub.co/metatags`. Will be used for Custom Social Media Cards if `proxy` is true.",+ }),+ description: z.string().optional().openapi({+ description:+ "The description of the short link generated via `api.dub.co/metatags`. Will be used for Custom Social Media Cards if `proxy` is true.",+ }),+ image: z.string().optional().openapi({+ description:+ "The image of the short link generated via `api.dub.co/metatags`. Will be used for Custom Social Media Cards if `proxy` is true.",+ }),+ rewrite: z.boolean().optional().openapi({+ description: "Whether the short link uses link cloaking.",+ default: false,+ }),+ ios: z.string().optional().nullable().openapi({+ description:+ "The iOS destination URL for the short link for iOS device targeting.",+ }),+ android: z.string().optional().nullable().openapi({+ description:+ "The Android destination URL for the short link for Android device targeting.",+ }),+ geo: z.record(z.string()).optional().nullable().openapi({+ description:+ "Geo targeting information for the short link in JSON format `{[COUNTRY]: https://example.com }`.",+ }),+ publicStats: z.boolean().optional().openapi({+ description: "Whether the short link's stats are publicly accessible.",+ default: false,+ }),+ tagId: z.string().optional().nullable().openapi({+ description: "The tag ID to assign to the short link.",+ }),+ comments: z.string().optional().nullable().openapi({+ description: "The comments for the short link.",+ }),+});++export type Link = z.infer<typeof LinkSchema>;+export type CreateLinkBody = z.infer<typeof CreateLinkBodySchema>;-export const getLinkInfo: ZodOpenApiOperationObject = {+const getLinkInfo: ZodOpenApiOperationObject = {operationId: "getLinkInfo",summary: "Retrieve a link",description: "Retrieve the info for a link from their domain and key.",@@ -73,7 +158,7 @@ export const getLinkInfo: ZodOpenApiOperationObject = {},};-export const getLinks: ZodOpenApiOperationObject = {+const getLinks: ZodOpenApiOperationObject = {operationId: "getLinks",summary: "Retrieve a list of links",description:@@ -93,11 +178,35 @@ export const getLinks: ZodOpenApiOperationObject = {},};-export const linkPaths: ZodOpenApiPathsObject = {- "/links/info": {- get: getLinkInfo,+const createLink: ZodOpenApiOperationObject = {+ operationId: "createLink",+ summary: "Create a new link",+ description: "Create a new link for the authenticated project.",+ requestBody: {+ content: {+ "application/json": {+ schema: CreateLinkBodySchema,+ },+ },+ },+ responses: {+ "200": {+ description: "The link was created",+ content: {+ "application/json": {+ schema: LinkSchemaOpenApi,+ },+ },+ },},+};++export const linkPaths: ZodOpenApiPathsObject = {"/links": {get: getLinks,+ post: createLink,+ },+ "/links/info": {+ get: getLinkInfo,},};diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsxindex 31d7d38e3e..9d9d3d0f8e 100644--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx@@ -52,6 +52,7 @@ import Preview from "./preview";import RewriteSection from "./rewrite-section";import UTMSection from "./utm-section";import TagsSection from "./tags-section";+import { extractApiErrorMessage } from "@/ui/utils";function AddEditLinkModal({showAddEditLinkModal,@@ -379,7 +380,7 @@ function AddEditLinkModal({}setShowAddEditLinkModal(false);} else {- const error = await res.text();+ const error = await extractApiErrorMessage(res);if (error) {toast.error(error);if (error.toLowerCase().includes("key")) {diff --git a/apps/web/ui/utils.ts b/apps/web/ui/utils.tsindex 7587c2183f..00e49a5b0d 100644--- a/apps/web/ui/utils.ts+++ b/apps/web/ui/utils.ts@@ -1,5 +1,7 @@// Keep this until we have move all error response to new JSON format-export const extractApiErrorMessage = async (response: Response) => {+export const extractApiErrorMessage = async (+ response: Response,+): Promise<string | null> => {if (response.ok) {return null;}@@ -12,6 +14,5 @@ export const extractApiErrorMessage = async (response: Response) => {}// If parsing JSON fails, treat it as plain text error- const errorText = await response.text();- return errorText;+ return await response.text();};