The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add bulk link creation
Steven Teybbbb3aadf074
diff --git a/apps/docs/api-reference/endpoint/bulk-create-links.mdx b/apps/docs/api-reference/endpoint/bulk-create-links.mdxnew file mode 100644index 0000000000..cc93a4deb6--- /dev/null+++ b/apps/docs/api-reference/endpoint/bulk-create-links.mdx@@ -0,0 +1,15 @@+---+openapi: post /projects/{slug}/links/bulk+---++<Note>+ Bulk link creation is only available on the [Pro plan](https://dub.sh/pro) and+ above.+</Note>++<Warning>+ Bulk link creation does not support the following features: [Link+ cloaking](https://dub.co/help/article/how-to-create-link#link-cloaking),+ [Custom social media+ cards](https://dub.co/help/article/how-to-create-link#custom-social-media-cards)+</Warning>diff --git a/apps/docs/api-reference/endpoint/create-a-new-tag.mdx b/apps/docs/api-reference/endpoint/create-a-new-tag.mdxnew file mode 100644index 0000000000..13522528d4--- /dev/null+++ b/apps/docs/api-reference/endpoint/create-a-new-tag.mdx@@ -0,0 +1,3 @@+---+openapi: post /projects/{slug}/tags+---diff --git a/apps/docs/api-reference/endpoint/retrieve-a-list-of-projects.mdx b/apps/docs/api-reference/endpoint/retrieve-a-list-of-projects.mdxnew file mode 100644index 0000000000..32bb16b4b0--- /dev/null+++ b/apps/docs/api-reference/endpoint/retrieve-a-list-of-projects.mdx@@ -0,0 +1,3 @@+---+openapi: get /projects+---diff --git a/apps/docs/api-reference/endpoint/retrieve-a-list-of-tags.mdx b/apps/docs/api-reference/endpoint/retrieve-a-list-of-tags.mdxnew file mode 100644index 0000000000..e7f1cd2eda--- /dev/null+++ b/apps/docs/api-reference/endpoint/retrieve-a-list-of-tags.mdx@@ -0,0 +1,3 @@+---+openapi: get /projects/{slug}/tags+---diff --git a/apps/docs/api-reference/endpoint/retrieve-a-project.mdx b/apps/docs/api-reference/endpoint/retrieve-a-project.mdxnew file mode 100644index 0000000000..807c586c16--- /dev/null+++ b/apps/docs/api-reference/endpoint/retrieve-a-project.mdx@@ -0,0 +1,3 @@+---+openapi: get /projects/{slug}+---diff --git a/apps/docs/api-reference/errors.mdx b/apps/docs/api-reference/errors.mdxdeleted file mode 100644index 6c5d1e0b82..0000000000--- a/apps/docs/api-reference/errors.mdx+++ /dev/null@@ -1,22 +0,0 @@-----title: "Errors"-description: "Possible errors and how to handle them"------Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et eros iaculis tortor dapibus cursus. Curabitur quis sapien nec tortor dictum gravida.--```bash-'Authorization': 'Token <team_token>'-```--## API Tokens--Nullam convallis mauris at nunc consectetur, ac imperdiet leo rutrum. Maecenas cursus purus a pellentesque blandit. Pellentesque vitae lacinia libero, non mollis metus.--Nam id ullamcorper urna, at rutrum enim. [Maecenas vulputate](/introduction) vehicula libero, vitae sodales augue pretium nec. Quisque a magna tempor, semper risus vel, fermentum nunc. Pellentesque fermentum interdum ex, eu convallis massa blandit sed. Aliquam bibendum ipsum vel laoreet auctor.--### Permissions--Etiam lobortis ut odio ut fermentum. Nunc odio velit, sollicitudin at consectetur id, tristique eget turpis. Aliquam at risus vitae dolor sodales venenatis. In hac habitasse platea dictumst.--Aenean consequat diam eget mollis fermentum. [Quisque eu malesuada](/introduction) felis, non dignissim libero.diff --git a/apps/docs/mint.json b/apps/docs/mint.jsonindex 5bafe46744..3c741a2a04 100644--- a/apps/docs/mint.json+++ b/apps/docs/mint.json@@ -1,6 +1,6 @@{"$schema": "https://mintlify.com/schema.json",- "name": "Docs",+ "name": "Dub.co Docs","logo": {"dark": "/logos/logotype-dark.svg","light": "/logos/logotype.svg",@@ -59,7 +59,22 @@"api-reference/endpoint/retrieve-a-link","api-reference/endpoint/edit-a-link","api-reference/endpoint/delete-a-link",- "api-reference/endpoint/retrieve-a-list-of-links"+ "api-reference/endpoint/retrieve-a-list-of-links",+ "api-reference/endpoint/bulk-create-links"+ ]+ },+ {+ "group": "Projects",+ "pages": [+ "api-reference/endpoint/retrieve-a-project",+ "api-reference/endpoint/retrieve-a-list-of-projects"+ ]+ },+ {+ "group": "Tags",+ "pages": [+ "api-reference/endpoint/create-a-new-tag",+ "api-reference/endpoint/retrieve-a-list-of-tags"]},{diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 61ae61ecb6..d80f49939c 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -1,7 +1,6 @@import { withAuth } from "@/lib/auth";-import { deleteLink, editLink, processKey, processLink } from "@/lib/api/links";+import { deleteLink, editLink, processLink } from "@/lib/api/links";import { NextResponse } from "next/server";-import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";import { GOOGLE_FAVICON_URL, getApexDomain, log } from "@dub/utils";// PUT /api/projects/[slug]/links/[linkId] – update a linkdiff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsnew file mode 100644index 0000000000..024be9e033--- /dev/null+++ b/apps/web/app/api/links/bulk/route.ts@@ -0,0 +1,59 @@+import { bulkCreateLinks, processLink } from "@/lib/api/links";+import { withAuth } from "@/lib/auth";+import { NextResponse } from "next/server";++// POST /api/links/bulk – bulk create up to 100 links+export const POST = withAuth(async ({ req, headers, session, project }) => {+ if (!project) {+ return new Response(+ "Missing project. Bulk link creation is only available for custom domain projects.",+ { status: 400, headers },+ );+ }+ let links = [];+ try {+ links = await req.json();+ if (!Array.isArray(links)) {+ throw new Error("Invalid request body.");+ }+ } catch (e) {+ return new Response("Invalid request body.", { status: 400, headers });+ }+ if (!project || project.plan === "free") {+ return new Response(+ "You can only use bulk link creation on a Pro plan and above.",+ { status: 403, headers },+ );+ }+ if (links.length === 0) {+ return new Response("No links created.", { status: 304, headers });+ }+ if (links.length > 100) {+ return new Response("You can only create up to 100 links at a time.", {+ status: 400,+ headers,+ });+ }++ const processedLinks = await Promise.all(+ links.map(async (link) =>+ processLink({ payload: link, project, session, bulk: true }),+ ),+ );++ const validLinks = processedLinks+ .filter(({ error }) => !error)+ .map(({ link }) => link);++ const errors = processedLinks+ .filter(({ error }) => error)+ .map(({ link, error }) => ({+ link,+ error,+ }));++ const validLinksResponse =+ validLinks.length > 0 ? await bulkCreateLinks(validLinks) : [];++ return NextResponse.json([...validLinksResponse, ...errors]);+});diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex 1ed3a7c19a..b8ffa1829b 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -1,12 +1,5 @@-import {- addLink,- getLinksForProject,- getRandomKey,- processKey,- processLink,-} from "@/lib/api/links";+import { addLink, getLinksForProject, processLink } from "@/lib/api/links";import { withAuth } from "@/lib/auth";-import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";import {DUB_PROJECT_ID,GOOGLE_FAVICON_URL,@@ -57,6 +50,7 @@ export const POST = withAuth(const { link, error, status } = await processLink({payload: body,project,+ session,});if (!link) {@@ -64,11 +58,7 @@ export const POST = withAuth(}const [response, invalidFavicon] = await Promise.allSettled([- addLink({- ...link,- projectId: project?.id || DUB_PROJECT_ID,- userId: session.user.id,- }),+ addLink(link),...(!project? [fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(link.url)}`).then(diff --git a/apps/web/app/api/projects/[slug]/links/bulk/route.ts b/apps/web/app/api/projects/[slug]/links/bulk/route.tsnew file mode 100644index 0000000000..60859cceed--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/bulk/route.ts@@ -0,0 +1 @@+export * from "../../../../links/bulk/route";diff --git a/apps/web/app/api/route.ts b/apps/web/app/api/route.tsindex db800b7a41..e4a7bd141d 100644--- a/apps/web/app/api/route.ts+++ b/apps/web/app/api/route.ts@@ -25,10 +25,76 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},],paths: {+ "/projects": {+ get: {+ description:+ "Retrieve a list of projects for the authenticated user.",+ operationId: "getProjects",+ security: [+ {+ bearerToken: [],+ },+ ],+ summary: "Retrieve a list of projects",+ responses: {+ "200": {+ description: "A list of projects",+ content: {+ "application/json": {+ schema: {+ type: "array",+ items: {+ $ref: "#/components/schemas/Project",+ },+ },+ },+ },+ },+ },+ },+ },+ "/projects/{slug}": {+ get: {+ description: "Retrieve a project for the authenticated user.",+ operationId: "getProject",+ security: [+ {+ bearerToken: [],+ },+ ],+ summary: "Retrieve a project",+ parameters: [+ {+ name: "slug",+ description:+ "The slug for the project to retrieve. E.g. for app.dub.co/acme, the slug is 'acme'.",+ in: "path",+ required: true,+ schema: {+ description:+ "The slug for the project to retrieve. E.g. for app.dub.co/acme, the slug is 'acme'.",+ type: "string",+ },+ },+ ],+ responses: {+ "200": {+ description: "The retrieved project",+ content: {+ "application/json": {+ schema: {+ $ref: "#/components/schemas/ProjectDetails",+ },+ },+ },+ },+ },+ },+ },"/projects/{slug}/links": {get: {description:- "Retrieve a list of links for the authenticated user or project. The list will be paginated and the provided query parameters allow filtering the returned links.",+ "Retrieve a list of links for the authenticated project. The list will be paginated and the provided query parameters allow filtering the returned links.",operationId: "getLinks",security: [{@@ -150,8 +216,7 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},post: {- description:- "Create a new link for the authenticated user or project.",+ description: "Create a new link for the authenticated project.",operationId: "createLink",security: [{@@ -264,7 +329,7 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},"/projects/{slug}/links/{linkId}": {put: {- description: "Edit link for the authenticated user or project.",+ description: "Edit link for the authenticated project.",operationId: "editLink",security: [{@@ -323,7 +388,7 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},delete: {- description: "Delete a link for the authenticated user or project.",+ description: "Delete a link for the authenticated project.",operationId: "deleteLink",security: [{@@ -371,6 +436,156 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},},+ "/projects/{slug}/links/bulk": {+ post: {+ description:+ "Bulk create up to 100 links for the authenticated project.",+ operationId: "bulkCreateLinks",+ security: [+ {+ bearerToken: [],+ },+ ],+ summary: "Bulk create links",+ parameters: [+ {+ name: "slug",+ description:+ "The slug for the project to create links for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ in: "path",+ required: true,+ schema: {+ description:+ "The slug for the project to create links for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ type: "string",+ },+ },+ ],+ requestBody: {+ description: "Details of the links to create.",+ required: true,+ content: {+ "application/json": {+ schema: {+ type: "array",+ items: {+ $ref: "#/components/schemas/LinkBody",+ },+ },+ },+ },+ },+ responses: {+ "200": {+ description: "The created links",+ content: {+ "application/json": {+ schema: {+ type: "array",+ items: {+ $ref: "#/components/schemas/Link",+ },+ },+ },+ },+ },+ },+ },+ },+ "/projects/{slug}/tags": {+ get: {+ description: "Retrieve a list of tags for the authenticated project.",+ operationId: "getTags",+ security: [+ {+ bearerToken: [],+ },+ ],+ summary: "Retrieve a list of tags",+ parameters: [+ {+ name: "slug",+ description:+ "The slug for the project to retrieve tags for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ in: "path",+ required: true,+ schema: {+ description:+ "The slug for the project to retrieve tags for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ type: "string",+ },+ },+ ],+ responses: {+ "200": {+ description: "A list of tags",+ content: {+ "application/json": {+ schema: {+ type: "array",+ items: {+ $ref: "#/components/schemas/Tag",+ },+ },+ },+ },+ },+ },+ },+ post: {+ description: "Create a new tag for the authenticated project.",+ operationId: "createTag",+ security: [+ {+ bearerToken: [],+ },+ ],+ summary: "Create a new tag",+ parameters: [+ {+ name: "slug",+ description:+ "The slug for the project to create tags for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ in: "path",+ required: true,+ schema: {+ description:+ "The slug for the project to create tags for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ type: "string",+ },+ },+ ],+ requestBody: {+ description: "Details of the tag to create.",+ required: true,+ content: {+ "application/json": {+ schema: {+ type: "object",+ properties: {+ tag: {+ type: "string",+ description: "The name of the tag to create.",+ },+ },+ },+ },+ },+ },+ responses: {+ "200": {+ description: "The created tag",+ content: {+ "application/json": {+ schema: {+ $ref: "#/components/schemas/Tag",+ },+ },+ },+ },+ },+ },+ },},components: {schemas: {@@ -581,6 +796,130 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},},+ Project: {+ type: "object",+ properties: {+ id: {+ type: "string",+ format: "cuid",+ description: "The unique ID of the project.",+ },+ name: {+ type: "string",+ description: "The name of the project.",+ },+ slug: {+ type: "string",+ description: "The slug of the project.",+ },+ logo: {+ type: "string",+ description: "The logo of the project.",+ default: null,+ nullable: true,+ },+ usage: {+ type: "number",+ description: "The usage of the project.",+ default: 0,+ readOnly: true,+ },+ usageLimit: {+ type: "number",+ description: "The usage limit of the project.",+ default: 0,+ readOnly: true,+ },+ plan: {+ type: "string",+ description: "The plan of the project.",+ default: "free",+ readOnly: true,+ },+ stripeId: {+ type: "string",+ description: "The Stripe ID of the project.",+ default: null,+ nullable: true,+ readOnly: true,+ },+ billingCycleStart: {+ type: "number",+ description:+ "The date and time when the billing cycle starts for the project.",+ default: null,+ nullable: true,+ readOnly: true,+ },+ createdAt: {+ type: "string",+ format: "date-time",+ description: "The date and time when the project was created.",+ readOnly: true,+ },+ },+ },+ ProjectDetails: {+ allOf: [+ {+ $ref: "#/components/schemas/Project",+ },+ {+ type: "object",+ properties: {+ users: {+ type: "array",+ items: {+ type: "object",+ properties: {+ role: {+ type: "string",+ description:+ "The role of the authenticated user in the project.",+ },+ },+ description:+ "The role of the authenticated user in the project.",+ },+ description:+ "The role of the authenticated user in the project.",+ },+ domains: {+ type: "array",+ items: {+ type: "object",+ properties: {+ slug: {+ type: "string",+ description: "The domain of the project.",+ },+ },+ description: "The domains of the project.",+ },+ description: "The domains of the project.",+ },+ },+ },+ ],+ },+ Tag: {+ type: "object",+ properties: {+ id: {+ type: "string",+ format: "cuid",+ description: "The unique ID of the tag.",+ },+ name: {+ type: "string",+ description: "The name of the tag.",+ },+ color: {+ type: "string",+ description: "The color of the tag.",+ },+ },+ },},securitySchemes: {bearerToken: {diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 6ef4e83fbd..9548c9ace9 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -7,6 +7,7 @@ import prisma from "@/lib/prisma";import { redis } from "@/lib/upstash";import {DEFAULT_REDIRECTS,+ DUB_PROJECT_ID,getParamsFromURL,nanoid,truncate,@@ -15,6 +16,7 @@ import {import cloudinary from "cloudinary";import { isIframeable } from "../middleware/utils";import { LinkProps, ProjectProps } from "../types";+import { Session } from "../auth";export async function getLinksForProject({projectId,@@ -199,22 +201,26 @@ export function processKey(key: string) {export async function processLink({payload,project,+ session,+ bulk = false,}: {payload: LinkProps;project: ProjectProps | null;+ session?: Session;+ bulk?: boolean;}) {- let { domain, key, url, rewrite, geo } = payload;+ let { domain, key, url, image, rewrite, geo } = payload;if (!url) {return {- link: null,+ link: payload,error: "Missing destination url.",status: 400,};}if (!domain) {return {- link: null,+ link: payload,error: "Missing short link domain.",status: 400,};@@ -223,7 +229,7 @@ export async function processLink({if (project) {if (!project.domains?.find((d) => d.slug === domain)) {return {- link: null,+ link: payload,error: "Domain does not belong to project.",status: 403,};@@ -232,14 +238,14 @@ export async function processLink({} else {if (domain !== "dub.sh") {return {- link: null,+ link: payload,error: "Invalid domain",status: 403,};}if (key.includes("/")) {return {- link: null,+ link: payload,error:"Key cannot contain '/'. You can only use this with a custom domain.",status: 422,@@ -248,7 +254,7 @@ export async function processLink({const keyBlacklisted = await isBlacklistedKey(key);if (keyBlacklisted) {return {- link: null,+ link: payload,error: "Invalid key.",status: 422,};@@ -256,14 +262,14 @@ export async function processLink({const domainBlacklisted = await isBlacklistedDomain(url);if (domainBlacklisted) {return {- link: null,+ link: payload,error: "Invalid url.",status: 422,};}if (rewrite) {return {- link: null,+ link: payload,error: "You can only use link cloaking on a custom domain.",status: 403,};@@ -271,11 +277,11 @@ export async function processLink({}// free plan restrictions- if ((!project || project.plan === "free") && geo) {+ if (!project || project.plan === "free") {if (geo) {return {- link: null,- error: "You can only use geo targeting on a Pro plan.",+ link: payload,+ error: "You can only use geo targeting on a Pro plan and above.",status: 403,};}@@ -285,10 +291,41 @@ export async function processLink({key = await getRandomKey(domain);}+ if (bulk) {+ if (image) {+ return {+ link: payload,+ error: "You cannot set custom social cards with bulk link creation.",+ status: 422,+ };+ }+ if (rewrite) {+ return {+ link: payload,+ error: "You cannot use link cloaking with bulk link creation.",+ status: 422,+ };+ }+ const exists = await checkIfKeyExists(domain, key);+ if (exists) {+ return {+ link: payload,+ error: `Link already exists.`,+ status: 409,+ };+ }+ }+return {link: {...payload,key,+ // make sure projectId is set to the current project (or Dub's if there's no project)+ projectId: project?.id || DUB_PROJECT_ID,+ // if session is passed, set userId to the current user's id (we don't change the userId if it's already set, e.g. when editing a link)+ ...(session && {+ userId: session.user.id,+ }),},error: null,status: 200,@@ -377,6 +414,63 @@ export async function addLink(link: LinkProps) {return response;}+export async function bulkCreateLinks(links: LinkProps[]) {+ const pipeline = redis.pipeline();+ links.forEach(({ domain, key, url, expiresAt, password }) => {+ const hasPassword = password && password.length > 0 ? true : false;+ const exat = expiresAt ? new Date(expiresAt).getTime() / 1000 : null;+ pipeline.set(+ `${domain}:${key}`,+ {+ url: encodeURIComponent(url),+ password: hasPassword,+ },+ {+ nx: true,+ ...(exat && { exat: exat as any }),+ },+ );+ });++ await Promise.all([+ prisma.link.createMany({+ data: links.map((link) => {+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =+ getParamsFromURL(link.url);+ return {+ ...link,+ title: truncate(link.title, 120),+ description: truncate(link.description, 240),+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ geo: link.geo || undefined,+ };+ }),+ skipDuplicates: true,+ }),+ pipeline.exec(),+ ]);++ const createdLinks = await Promise.all(+ links.map(async (link) => {+ const { key, domain } = link;+ return await prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ });+ }),+ );++ return createdLinks;+}+export async function editLink({domain: oldDomain = "dub.sh",key: oldKey,diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.tsindex 5ea36f2052..4ac065c03a 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -90,15 +90,6 @@ export const withAuth =}const apiKey = authorizationHeader.replace("Bearer ", "");- if (!slug) {- return new Response(- "API access is only available for projects with custom domains.",- {- status: 403,- },- );- }-const url = new URL(req.url || "", API_DOMAIN);if (url.pathname.includes("/stats/")) {@@ -107,6 +98,15 @@ export const withAuth =});}+ if (!slug && url.pathname.includes("/links/")) {+ return new Response(+ "API access is only available for projects with custom domains.",+ {+ status: 403,+ },+ );+ }+const hashedKey = hashToken(apiKey, {noSecret: true,});diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prismaindex 349d314108..b40b621277 100644--- a/apps/web/prisma/schema.prisma+++ b/apps/web/prisma/schema.prisma@@ -181,7 +181,7 @@ model Link {url String @db.LongText // target url (e.g. https://github.com/steven-tey/dub) – also stored on Redisarchived Boolean @default(false) // whether the link is archived or notexpiresAt DateTime? // when the link expires – stored on Redis via ttl- password String? // password to access the link – also stored on Redis+ password String? // password to access the linkproxy Boolean @default(false) // Proxy to use custom OG tags (stored on redis) – if false, will use OG tags from target urltitle String? // OG title for the link (e.g. Dub - Open-Source Bitly Alternative)