Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Remove qstash call from links API, rearrange links API

Steven Tey8d61fffd9f72
diff --git a/apps/web/app/api/cron/links/event/route.ts b/apps/web/app/api/cron/links/event/route.ts
index be9dcb2798..71c499148c 100644
--- a/apps/web/app/api/cron/links/event/route.ts
+++ b/apps/web/app/api/cron/links/event/route.ts
@@ -1,15 +1,7 @@
-import { getAnalytics } from "@/lib/analytics";
-import { qstash, receiver, sendLimitEmail } from "@/lib/cron";
+import { receiver, sendLimitEmail } from "@/lib/cron";
import prisma from "@/lib/prisma";
-import { recordLink } from "@/lib/tinybird";
import { WorkspaceProps } from "@/lib/types";
-import { formatRedisLink, redis } from "@/lib/upstash";
-import {
- APP_DOMAIN_WITH_NGROK,
- GOOGLE_FAVICON_URL,
- getApexDomain,
- log,
-} from "@dub/utils";
+import { GOOGLE_FAVICON_URL, getApexDomain, log } from "@dub/utils";
export async function POST(req: Request) {
const body = await req.json();
@@ -56,26 +48,6 @@ export async function POST(req: Request) {
}
}
- // for public links, delete after 30 mins (if not claimed)
- if (!link.userId) {
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete`,
- // delete after 30 mins
- delay: 30 * 60,
- body: {
- linkId,
- },
- });
- }
-
- // update redis and tinybird
- await Promise.all([
- redis.hset(link.domain, {
- [link.key.toLowerCase()]: await formatRedisLink(link),
- }),
- recordLink({ link }),
- ]);
-
// increment links usage and send alert if needed
if (type === "create" && link.projectId) {
const workspace = await prisma.project.update({
@@ -144,49 +116,5 @@ export async function POST(req: Request) {
}
}
- if (type === "transfer") {
- const oldWorkspaceId = await redis.get<string>(
- `transfer:${linkId}:oldWorkspaceId`,
- );
-
- const linkClicks = await getAnalytics({
- linkId,
- endpoint: "clicks",
- interval: "30d",
- });
-
- // update old and new project usage
- await Promise.all([
- oldWorkspaceId &&
- prisma.project.update({
- where: {
- id: oldWorkspaceId,
- },
- data: {
- usage: {
- decrement: linkClicks,
- },
- linksUsage: {
- decrement: 1,
- },
- },
- }),
- link.projectId &&
- prisma.project.update({
- where: {
- id: link.projectId,
- },
- data: {
- usage: {
- increment: linkClicks,
- },
- linksUsage: {
- increment: 1,
- },
- },
- }),
- ]);
- }
-
return new Response("OK", { status: 200 });
}
diff --git a/apps/web/app/api/cron/links/usage/route.ts b/apps/web/app/api/cron/links/usage/route.ts
new file mode 100644
index 0000000000..8de7b95e41
--- /dev/null
+++ b/apps/web/app/api/cron/links/usage/route.ts
@@ -0,0 +1,29 @@
+import { verifySignature } from "@/lib/cron";
+import { getSearchParams, log } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// Cron to update the links usage of each workspace.
+// Runs once every 5 mins (*/5 * * * *)
+
+export async function GET(req: Request) {
+ const validSignature = await verifySignature(req);
+ if (!validSignature) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ // TODO – we need to check if any workspace exceeded 80% of their links usage
+ // and send a LinkLimitExceeded email
+ const { skip } = getSearchParams(req.url);
+
+ try {
+ return NextResponse.json({
+ response: "success",
+ });
+ } catch (error) {
+ await log({
+ message: "Usage cron failed. Error: " + error.message,
+ type: "errors",
+ });
+ return NextResponse.json({ error: error.message });
+ }
+}
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index bf0fa43542..757cbaaa5f 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -1,11 +1,9 @@
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
import { deleteLink, editLink, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
-import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { LinkWithTagIdsProps } from "@/lib/types";
import { updateLinkBodySchema } from "@/lib/zod/schemas/links";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/links/[linkId] – get a link
@@ -87,22 +85,11 @@ export const PUT = withAuth(async ({ req, headers, workspace, link }) => {
});
}
- const [response, _] = await Promise.allSettled([
- editLink({
- oldDomain: link.domain,
- oldKey: link.key,
- oldImage: link.image || undefined,
- 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 editLink({
+ oldDomain: link.domain,
+ oldKey: link.key,
+ updatedLink: processedLink as any, // TODO: fix types
+ });
return NextResponse.json(response, {
headers,
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index 2b954bb3ff..3013930d0b 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -1,9 +1,11 @@
+import { getAnalytics } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
import { transferLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
-import { redis } from "@/lib/upstash";
+import { recordLink } from "@/lib/tinybird";
+import { formatRedisLink, redis } from "@/lib/upstash";
import z from "@/lib/zod";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
@@ -17,57 +19,127 @@ const transferLinkBodySchema = z.object({
});
// POST /api/links/[linkId]/transfer – transfer a link to another workspace
-export const POST = withAuth(async ({ req, headers, session, link }) => {
- const { newWorkspaceId } = transferLinkBodySchema.parse(await req.json());
+export const POST = withAuth(
+ async ({ req, headers, session, params, workspace }) => {
+ const { newWorkspaceId } = transferLinkBodySchema.parse(await req.json());
- const newWorkspace = await prisma.project.findUnique({
- where: { id: newWorkspaceId },
- select: {
- linksUsage: true,
- linksLimit: true,
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
+ const newWorkspace = await prisma.project.findUnique({
+ where: { id: newWorkspaceId },
+ select: {
+ linksUsage: true,
+ linksLimit: true,
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
},
},
- },
- });
+ });
- if (!newWorkspace || newWorkspace.users.length === 0) {
- throw new DubApiError({
- code: "not_found",
- message: "New workspace not found.",
+ const link = await prisma.link.findUnique({
+ where: {
+ id: params.linkId,
+ },
+ include: {
+ tags: true,
+ },
});
- }
+ // technically this is not needed since the link is already checked in withAuth
+ if (!link) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Link not found.",
+ });
+ }
+
+ if (!newWorkspace || newWorkspace.users.length === 0) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "New workspace not found.",
+ });
+ }
- if (newWorkspace.linksUsage >= newWorkspace.linksLimit) {
- throw new DubApiError({
- code: "forbidden",
- message: "New workspace has reached its link limit.",
+ if (newWorkspace.linksUsage >= newWorkspace.linksLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "New workspace has reached its link limit.",
+ });
+ }
+
+ const linkClicks = await getAnalytics({
+ linkId: link.id,
+ endpoint: "clicks",
+ interval: "30d",
});
- }
- const response = await Promise.all([
- transferLink({
- linkId: link!.id,
- newWorkspaceId,
- }),
- // set this in redis so we can use it in the event cron job
- redis.set(`transfer:${link!.id}:oldWorkspaceId`, link!.projectId),
- ]);
+ const response = await Promise.all([
+ prisma.link.update({
+ where: {
+ id: link.id,
+ },
+ data: {
+ projectId: newWorkspaceId,
+ // remove tags when transferring link
+ tags: {
+ deleteMany: {},
+ },
+ },
+ }),
+ redis.hset(link.domain, {
+ [link.key.toLowerCase()]: await formatRedisLink({
+ ...link,
+ projectId: newWorkspaceId,
+ }),
+ }),
+ recordLink({
+ link: {
+ ...link,
+ projectId: newWorkspaceId,
+ },
+ }),
+ // decrement old workspace usage
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ usage: {
+ decrement: linkClicks,
+ },
+ linksUsage: {
+ decrement: 1,
+ },
+ },
+ }),
+ // increment new workspace usage
+ prisma.project.update({
+ where: {
+ id: newWorkspaceId,
+ },
+ data: {
+ usage: {
+ increment: linkClicks,
+ },
+ linksUsage: {
+ increment: 1,
+ },
+ },
+ }),
+ ]);
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,
- body: {
- linkId: link!.id,
- type: "transfer",
- },
- });
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,
+ body: {
+ linkId: link!.id,
+ type: "transfer",
+ },
+ });
- return NextResponse.json(response, {
- headers,
- });
-});
+ return NextResponse.json(response, {
+ headers,
+ });
+ },
+);
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index fdbc3ba37a..62ad270650 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -1,14 +1,13 @@
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
-import { addLink, getLinksForWorkspace, processLink } from "@/lib/api/links";
+import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
-import { qstash } from "@/lib/cron";
import { LinkWithTagIdsProps } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
import {
createLinkBodySchema,
getLinksQuerySchema,
} from "@/lib/zod/schemas/links";
-import { APP_DOMAIN_WITH_NGROK, LOCALHOST_IP } from "@dub/utils";
+import { LOCALHOST_IP } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/links – get all links for a workspace
@@ -83,15 +82,7 @@ export const POST = withAuth(
});
}
- const response = await addLink(link);
-
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,
- body: {
- linkId: response.id,
- type: "create",
- },
- });
+ const response = await createLink(link);
return NextResponse.json(response, { headers });
},
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
deleted file mode 100644
index 08a113b38f..0000000000
--- a/apps/web/lib/api/links.ts
+++ /dev/null
@@ -1,910 +0,0 @@
-import {
- isBlacklistedDomain,
- isBlacklistedKey,
- isReservedKey,
- isReservedUsername,
-} from "@/lib/edge-config";
-import prisma from "@/lib/prisma";
-import { isStored, storage } from "@/lib/storage";
-import { formatRedisLink, redis } from "@/lib/upstash";
-import {
- getLinksCountQuerySchema,
- getLinksQuerySchema,
-} from "@/lib/zod/schemas/links";
-import {
- DEFAULT_REDIRECTS,
- DUB_DOMAINS,
- SHORT_DOMAIN,
- getDomainWithoutWWW,
- getParamsFromURL,
- getUrlFromString,
- isDubDomain,
- isValidUrl,
- linkConstructor,
- truncate,
- validKeyRegex,
-} from "@dub/utils";
-import { Prisma } from "@prisma/client";
-import { checkIfKeyExists, getRandomKey } from "../planetscale";
-import { recordLink } from "../tinybird";
-import {
- LinkProps,
- LinkWithTagIdsProps,
- RedisLinkProps,
- WorkspaceProps,
-} from "../types";
-import z from "../zod";
-
-export async function getLinksForWorkspace({
- workspaceId,
- domain,
- tagId,
- tagIds,
- search,
- sort = "createdAt",
- page,
- userId,
- showArchived,
- withTags,
-}: z.infer<typeof getLinksQuerySchema> & {
- workspaceId: string;
-}) {
- const combinedTagIds = combineTagIds({ tagId, tagIds });
-
- const links = await prisma.link.findMany({
- where: {
- projectId: workspaceId,
- archived: showArchived ? undefined : false,
- ...(domain && { domain }),
- ...(search && {
- OR: [
- {
- key: { contains: search },
- },
- {
- url: { contains: search },
- },
- ],
- }),
- ...(withTags && {
- tags: {
- some: {},
- },
- }),
- ...(combinedTagIds.length > 0 && {
- tags: { some: { tagId: { in: combinedTagIds } } },
- }),
- ...(userId && { userId }),
- },
- include: {
- user: true,
- tags: {
- include: {
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- },
- },
- },
- },
- },
- orderBy: {
- [sort]: "desc",
- },
- take: 100,
- ...(page && {
- skip: (page - 1) * 100,
- }),
- });
-
- return links.map((link) => {
- const shortLink = linkConstructor({
- domain: link.domain,
- key: link.key,
- });
-
- const tags = link.tags.map(({ tag }) => tag);
-
- return {
- ...link,
- tagId: tags?.[0]?.id ?? null, // backwards compatibility
- tags,
- shortLink,
- qrCode: `https://api.dub.co/qr?url=${shortLink}`,
- workspaceId: `ws_${link.projectId}`,
- };
- });
-}
-
-export async function getLinksCount({
- searchParams,
- workspaceId,
- userId,
-}: {
- searchParams: z.infer<typeof getLinksCountQuerySchema>;
- workspaceId: string;
- userId?: string | null;
-}) {
- const { groupBy, search, domain, tagId, tagIds, showArchived, withTags } =
- searchParams;
-
- const combinedTagIds = combineTagIds({ tagId, tagIds });
-
- const linksWhere = {
- projectId: workspaceId,
- archived: showArchived ? undefined : false,
- ...(userId && { userId }),
- ...(search && {
- OR: [
- {
- key: { contains: search },
- },
- {
- url: { contains: search },
- },
- ],
- }),
- // when filtering by domain, only filter by domain if the filter group is not "Domains"
- ...(domain &&
- groupBy !== "domain" && {
- domain,
- }),
- };
-
- if (groupBy === "tagId") {
- return await prisma.linkTag.groupBy({
- by: ["tagId"],
- where: {
- link: linksWhere,
- },
- _count: true,
- orderBy: {
- _count: {
- tagId: "desc",
- },
- },
- });
- } else {
- const where = {
- ...linksWhere,
- ...(withTags && {
- tags: {
- some: {},
- },
- }),
- ...(combinedTagIds.length > 0 && {
- tags: {
- some: {
- tagId: {
- in: tagIds,
- },
- },
- },
- }),
- };
-
- if (groupBy === "domain") {
- return await prisma.link.groupBy({
- by: [groupBy],
- where,
- _count: true,
- orderBy: {
- _count: {
- [groupBy]: "desc",
- },
- },
- });
- } else {
- return await prisma.link.count({
- where,
- });
- }
- }
-}
-
-export async function keyChecks({
- domain,
- key,
- workspace,
-}: {
- domain: string;
- key: string;
- workspace?: WorkspaceProps;
-}) {
- if (key.length === 0) {
- if (workspace?.plan === "free") {
- return {
- error:
- "You can only set a redirect for your root domain on a Pro plan and above. Upgrade to Pro to unlock this feature.",
- code: "forbidden",
- };
- } else {
- return {
- error:
- "To set a redirect for your root domain, navigate to your Domains tab and click 'Edit' on the domain you want to update.",
- code: "unprocessable_entity",
- };
- }
- }
-
- const link = await checkIfKeyExists(domain, key);
- if (link) {
- return {
- error: "Duplicate key: This short link already exists.",
- code: "conflict",
- };
- }
-
- if (isDubDomain(domain) && process.env.NEXT_PUBLIC_IS_DUB) {
- if (
- domain === SHORT_DOMAIN &&
- (DEFAULT_REDIRECTS[key] || (await isReservedKey(key)))
- ) {
- return {
- error: "Duplicate key: This short link already exists.",
- code: "conflict",
- };
- }
-
- if (key.length <= 3 && (!workspace || workspace.plan === "free")) {
- return {
- error: `You can only use keys that are 3 characters or less on a Pro plan and above. Upgrade to Pro to register a ${key.length}-character key.`,
- code: "forbidden",
- };
- }
- if (
- (await isReservedUsername(key)) &&
- (!workspace || workspace.plan === "free")
- ) {
- return {
- error:
- "This is a premium key. You can only use this key on a Pro plan and above. Upgrade to Pro to register this key.",
- code: "forbidden",
- };
- }
- }
- return {
- error: null,
- };
-}
-
-export function processKey(key: string) {
- if (!validKeyRegex.test(key)) {
- return null;
- }
- // remove all leading and trailing slashes from key
- key = key.replace(/^\/+|\/+$/g, "");
- // replace all special characters
- key = key.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
-
- return key;
-}
-
-export async function processLink({
- payload,
- workspace,
- userId,
- bulk = false,
- skipKeyChecks = false, // only skip when key doesn't change (e.g. when editing a link)
-}: {
- payload: LinkWithTagIdsProps;
- workspace?: WorkspaceProps;
- userId?: string;
- bulk?: boolean;
- skipKeyChecks?: boolean;
-}) {
- let {
- domain,
- key,
- url,
- image,
- proxy,
- password,
- rewrite,
- expiresAt,
- ios,
- android,
- geo,
- } = payload;
-
- const tagIds = combineTagIds(payload);
-
- // url checks
- if (!url) {
- return {
- link: payload,
- error: "Missing destination url.",
- code: "bad_request",
- };
- }
- const processedUrl = getUrlFromString(url);
- if (!isValidUrl(processedUrl)) {
- return {
- link: payload,
- error: "Invalid destination url.",
- code: "unprocessable_entity",
- };
- }
-
- // free plan restrictions
- if (!workspace || workspace.plan === "free") {
- if (proxy || password || rewrite || expiresAt || ios || android || geo) {
- return {
- link: payload,
- error:
- "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.",
- code: "forbidden",
- };
- }
- }
-
- // if domain is not defined, set it to the workspace's primary domain
- if (!domain) {
- domain = workspace?.domains?.find((d) => d.primary)?.slug || SHORT_DOMAIN;
- }
-
- // checks for default short domain
- if (domain === SHORT_DOMAIN) {
- const keyBlacklisted = await isBlacklistedKey(key);
- if (keyBlacklisted) {
- return {
- link: payload,
- error: "Invalid key.",
- code: "unprocessable_entity",
- };
- }
- const domainBlacklisted = await isBlacklistedDomain(url);
- if (domainBlacklisted) {
- return {
- link: payload,
- error: "Invalid url.",
- code: "unprocessable_entity",
- };
- }
-
- // checks for other Dub-owned domains (chatg.pt, spti.fi, etc.)
- } else if (isDubDomain(domain)) {
- // coerce type with ! cause we already checked if it exists
- 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
- .map((d) => `\`${d}\``)
- .join(", ")}.`,
- code: "unprocessable_entity",
- };
- }
-
- // else, check if the domain belongs to the workspace
- } else if (!workspace?.domains?.find((d) => d.slug === domain)) {
- return {
- link: payload,
- error: "Domain does not belong to workspace.",
- code: "forbidden",
- };
- }
-
- if (!key) {
- key = await getRandomKey(domain, payload["prefix"]);
- } else if (!skipKeyChecks) {
- const processedKey = processKey(key);
- if (processedKey === null) {
- return {
- link: payload,
- error: "Invalid key.",
- code: "unprocessable_entity",
- };
- }
- key = processedKey;
-
- const response = await keyChecks({ domain, key, workspace });
- if (response.error) {
- return {
- link: payload,
- ...response,
- };
- }
- }
-
- if (bulk) {
- if (image) {
- return {
- link: payload,
- error: "You cannot set custom social cards with bulk link creation.",
- code: "unprocessable_entity",
- };
- }
- if (rewrite) {
- return {
- link: payload,
- error: "You cannot use link cloaking with bulk link creation.",
- code: "unprocessable_entity",
- };
- }
-
- // only perform tag validity checks if:
- // - not bulk creation (we do that check separately in the route itself)
- // - tagIds are present
- } else if (tagIds.length > 0) {
- const tags = await prisma.tag.findMany({
- select: {
- id: true,
- },
- where: { projectId: workspace?.id, id: { in: tagIds } },
- });
-
- if (tags.length !== tagIds.length) {
- return {
- link: payload,
- error:
- "Invalid tagIds detected: " +
- tagIds
- .filter(
- (tagId) => tags.find(({ id }) => tagId === id) === undefined,
- )
- .join(", "),
- code: "unprocessable_entity",
- };
- }
- }
-
- // custom social media image checks (see if R2 is configured)
- if (proxy && !process.env.STORAGE_SECRET_ACCESS_KEY) {
- return {
- link: payload,
- error: "Missing storage access key.",
- code: "bad_request",
- };
- }
-
- // 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.",
- code: "unprocessable_entity",
- };
- }
- // check if expiresAt is in the future
- if (new Date(expiresAt) < new Date()) {
- return {
- link: payload,
- error: "Expiry date must be in the future.",
- code: "unprocessable_entity",
- };
- }
- }
-
- // remove polyfill attributes from payload
- delete payload["shortLink"];
- delete payload["qrCode"];
- delete payload["prefix"];
-
- return {
- link: {
- ...payload,
- domain,
- key,
- url: processedUrl,
- // make sure projectId is set to the current workspace
- projectId: workspace?.id || null,
- // if userId is passed, set it (we don't change the userId if it's already set, e.g. when editing a link)
- ...(userId && {
- userId,
- }),
- },
- error: null,
- };
-}
-
-export function combineTagIds({
- tagId,
- tagIds,
-}: {
- tagId?: string | null;
- tagIds?: string[];
-}): string[] {
- // Use tagIds if present, fall back to tagId
- if (tagIds && Array.isArray(tagIds) && tagIds.length > 0) {
- return tagIds;
- }
- return tagId ? [tagId] : [];
-}
-
-export async function addLink(link: LinkWithTagIdsProps) {
- let { key, url, expiresAt, title, description, image, proxy, geo } = link;
-
- const combinedTagIds = combineTagIds(link);
-
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(url);
-
- const { tagId, tagIds, ...rest } = link;
-
- const response = await prisma.link.create({
- data: {
- ...rest,
- key,
- title: truncate(title, 120),
- description: truncate(description, 240),
- // if it's an uploaded image, make this null first because we'll update it later
- image: proxy && image && !isStored(image) ? null : image,
- utm_source,
- utm_medium,
- utm_campaign,
- utm_term,
- utm_content,
- expiresAt: expiresAt ? new Date(expiresAt) : null,
- geo: geo || Prisma.JsonNull,
- ...(combinedTagIds.length > 0 && {
- tags: {
- createMany: {
- data: combinedTagIds.map((tagId) => ({ tagId })),
- },
- },
- }),
- },
- include: {
- tags: {
- select: {
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- },
- },
- },
- },
- },
- });
-
- const uploadedImageUrl = `${process.env.STORAGE_BASE_URL}/images/${response.id}`;
-
- if (proxy && image && !isStored(image)) {
- await Promise.all([
- // upload image to R2
- storage.upload(`images/${response.id}`, image, {
- width: 1200,
- height: 630,
- }),
- // update the null image we set earlier to the uploaded image URL
- prisma.link.update({
- where: {
- id: response.id,
- },
- data: {
- image: uploadedImageUrl,
- },
- }),
- ]);
- }
-
- const shortLink = linkConstructor({
- domain: response.domain,
- key: response.key,
- });
- const tags = response.tags.map(({ tag }) => tag);
- return {
- ...response,
- // optimistically set the image URL to the uploaded image URL
- image:
- proxy && image && !isStored(image) ? uploadedImageUrl : response.image,
- tagId: tags?.[0]?.id ?? null, // backwards compatibility
- tags,
- shortLink,
- qrCode: `https://api.dub.co/qr?url=${shortLink}`,
- workspaceId: `ws_${response.projectId}`,
- };
-}
-
-export async function bulkCreateLinks({
- links,
-}: {
- links: LinkWithTagIdsProps[];
-}) {
- if (links.length === 0) return [];
-
- // create links via $transaction (because Prisma doesn't support nested createMany)
- // ref: https://github.com/prisma/prisma/issues/8131#issuecomment-997667070
- const createdLinks = await prisma.$transaction(
- links.map(({ tagId, tagIds, ...link }) => {
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(link.url);
-
- const combinedTagIds = combineTagIds({ tagId, tagIds });
-
- return prisma.link.create({
- data: {
- ...link,
- title: truncate(link.title, 120),
- description: truncate(link.description, 240),
- utm_source,
- utm_medium,
- utm_campaign,
- utm_term,
- utm_content,
- expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
- geo: link.geo || undefined,
- ...(combinedTagIds.length > 0 && {
- tags: {
- createMany: {
- data: combinedTagIds.map((tagId) => ({ tagId })),
- },
- },
- }),
- },
- include: {
- tags: {
- select: {
- tagId: true,
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- },
- },
- },
- },
- },
- });
- }),
- );
-
- await propagateBulkLinkChanges(createdLinks);
-
- return createdLinks.map((link) => {
- const shortLink = linkConstructor({
- domain: link.domain,
- key: link.key,
- });
- const tags = link.tags.map(({ tag }) => tag);
- return {
- ...link,
- shortLink,
- tagId: tags?.[0]?.id ?? null, // backwards compatibility
- tags,
- qrCode: `https://api.dub.co/qr?url=${shortLink}`,
- workspaceId: `ws_${link.projectId}`,
- };
- });
-}
-
-export async function propagateBulkLinkChanges(
- links: (LinkProps & { tags: { tagId: string }[] })[],
-) {
- const pipeline = redis.pipeline();
-
- // split links into domains for better write effeciency in Redis
- const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};
-
- await Promise.all(
- links.map(async (link) => {
- const { domain, key } = link;
-
- if (!linksByDomain[domain]) {
- linksByDomain[domain] = {};
- }
- // this technically will be a synchronous function since isIframeable won't be run for bulk link creation
- const formattedLink = await formatRedisLink(link);
- linksByDomain[domain][key.toLowerCase()] = formattedLink;
-
- // record link in Tinybird
- await recordLink({ link });
- }),
- );
-
- Object.entries(linksByDomain).forEach(([domain, links]) => {
- pipeline.hset(domain, links);
- });
-
- await Promise.all([
- // update Redis
- pipeline.exec(),
- // update links usage for workspace
- prisma.project.update({
- where: {
- id: links[0].projectId!, // this will always be present
- },
- data: {
- linksUsage: {
- increment: links.length,
- },
- },
- }),
- ]);
-}
-
-export async function editLink({
- oldDomain = SHORT_DOMAIN,
- oldKey,
- oldImage,
- updatedLink,
-}: {
- oldDomain?: string;
- oldKey: string;
- oldImage?: string;
- updatedLink: LinkWithTagIdsProps;
-}) {
- let {
- id,
- domain,
- key,
- url,
- expiresAt,
- title,
- description,
- image,
- proxy,
- geo,
- } = updatedLink;
- const changedKey = key.toLowerCase() !== oldKey.toLowerCase();
- const changedDomain = domain !== oldDomain;
-
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(url);
-
- // exclude fields that should not be updated
- const {
- id: _,
- clicks,
- lastClicked,
- updatedAt,
- tagId,
- tagIds,
- ...rest
- } = updatedLink;
-
- const combinedTagIds = combineTagIds({ tagId, tagIds });
-
- if (proxy && image && !isStored(image)) {
- // only upload image if proxy is true and image is not stored in R2
- await storage.upload(`images/${id}`, image, {
- width: 1200,
- height: 630,
- });
- }
-
- const [response, ..._effects] = await Promise.all([
- prisma.link.update({
- where: {
- id,
- },
- data: {
- ...rest,
- key,
- title: truncate(title, 120),
- description: truncate(description, 240),
- image:
- proxy && image && !isStored(image)
- ? `${process.env.STORAGE_BASE_URL}/images/${id}`
- : image,
- utm_source,
- utm_medium,
- utm_campaign,
- utm_term,
- utm_content,
- expiresAt: expiresAt ? new Date(expiresAt) : null,
- geo: geo || Prisma.JsonNull,
- tags: {
- deleteMany: {
- tagId: {
- notIn: combinedTagIds,
- },
- },
- connectOrCreate: combinedTagIds.map((tagId) => ({
- where: { linkId_tagId: { linkId: id, tagId } },
- create: { tagId },
- })),
- },
- },
- include: {
- tags: {
- select: {
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- },
- },
- },
- },
- },
- }),
- // if key is changed: delete the old key in Redis
- (changedDomain || changedKey) &&
- redis.hdel(oldDomain, oldKey.toLowerCase()),
- ]);
-
- const shortLink = linkConstructor({
- domain: response.domain,
- key: response.key,
- });
-
- const tags = response.tags.map(({ tag }) => tag);
-
- return {
- ...response,
- tagId: tags?.[0]?.id ?? null, // backwards compatibility
- tags,
- shortLink,
- qrCode: `https://api.dub.co/qr?url=${shortLink}`,
- workspaceId: `ws_${response.projectId}`,
- };
-}
-
-export async function deleteLink(linkId: string) {
- const link = await prisma.link.delete({
- where: {
- id: linkId,
- },
- include: {
- tags: true,
- },
- });
- return await Promise.allSettled([
- // if the image is stored in Cloudflare R2, delete it
- link.proxy &&
- link.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`images/${link.id}`),
- redis.hdel(link.domain, link.key.toLowerCase()),
- recordLink({ link, deleted: true }),
- link.projectId &&
- prisma.project.update({
- where: {
- id: link.projectId,
- },
- data: {
- linksUsage: {
- decrement: 1,
- },
- },
- }),
- ]);
-}
-
-export async function archiveLink({
- linkId,
- archived,
-}: {
- linkId: string;
- archived: boolean;
-}) {
- return await prisma.link.update({
- where: {
- id: linkId,
- },
- data: {
- archived,
- },
- });
-}
-
-export async function transferLink({
- linkId,
- newWorkspaceId,
-}: {
- linkId: string;
- newWorkspaceId: string;
-}) {
- return await prisma.link.update({
- where: {
- id: linkId,
- },
- data: {
- projectId: newWorkspaceId,
- // remove tags when transferring link
- tags: {
- deleteMany: {},
- },
- },
- });
-}
diff --git a/apps/web/lib/api/links/archive-link.ts b/apps/web/lib/api/links/archive-link.ts
new file mode 100644
index 0000000000..0dbf42efbc
--- /dev/null
+++ b/apps/web/lib/api/links/archive-link.ts
@@ -0,0 +1,18 @@
+import prisma from "@/lib/prisma";
+
+export async function archiveLink({
+ linkId,
+ archived,
+}: {
+ linkId: string;
+ archived: boolean;
+}) {
+ return await prisma.link.update({
+ where: {
+ id: linkId,
+ },
+ data: {
+ archived,
+ },
+ });
+}
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.ts
new file mode 100644
index 0000000000..004f548567
--- /dev/null
+++ b/apps/web/lib/api/links/bulk-create-links.ts
@@ -0,0 +1,157 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds, keyChecks, processKey } from "./utils";
+
+export async function bulkCreateLinks({
+ links,
+}: {
+ links: LinkWithTagIdsProps[];
+}) {
+ if (links.length === 0) return [];
+
+ // create links via $transaction (because Prisma doesn't support nested createMany)
+ // ref: https://github.com/prisma/prisma/issues/8131#issuecomment-997667070
+ const createdLinks = await prisma.$transaction(
+ links.map(({ tagId, tagIds, ...link }) => {
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(link.url);
+
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
+
+ return prisma.link.create({
+ data: {
+ ...link,
+ title: truncate(link.title, 120),
+ description: truncate(link.description, 240),
+ utm_source,
+ utm_medium,
+ utm_campaign,
+ utm_term,
+ utm_content,
+ expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
+ geo: link.geo || undefined,
+ ...(combinedTagIds.length > 0 && {
+ tags: {
+ createMany: {
+ data: combinedTagIds.map((tagId) => ({ tagId })),
+ },
+ },
+ }),
+ },
+ include: {
+ tags: {
+ select: {
+ tagId: true,
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ },
+ });
+ }),
+ );
+
+ await propagateBulkLinkChanges(createdLinks);
+
+ return createdLinks.map((link) => {
+ const shortLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+ const tags = link.tags.map(({ tag }) => tag);
+ return {
+ ...link,
+ shortLink,
+ tagId: tags?.[0]?.id ?? null, // backwards compatibility
+ tags,
+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,
+ workspaceId: `ws_${link.projectId}`,
+ };
+ });
+}
+
+export async function propagateBulkLinkChanges(
+ links: (LinkProps & { tags: { tagId: string }[] })[],
+) {
+ const pipeline = redis.pipeline();
+
+ // split links into domains for better write effeciency in Redis
+ const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};
+
+ await Promise.all(
+ links.map(async (link) => {
+ const { domain, key } = link;
+
+ if (!linksByDomain[domain]) {
+ linksByDomain[domain] = {};
+ }
+ // this technically will be a synchronous function since isIframeable won't be run for bulk link creation
+ const formattedLink = await formatRedisLink(link);
+ linksByDomain[domain][key.toLowerCase()] = formattedLink;
+
+ // record link in Tinybird
+ await recordLink({ link });
+ }),
+ );
+
+ Object.entries(linksByDomain).forEach(([domain, links]) => {
+ pipeline.hset(domain, links);
+ });
+
+ await Promise.all([
+ // update Redis
+ pipeline.exec(),
+ // update links usage for workspace
+ prisma.project.update({
+ where: {
+ id: links[0].projectId!, // this will always be present
+ },
+ data: {
+ linksUsage: {
+ increment: links.length,
+ },
+ },
+ }),
+ ]);
+}
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
new file mode 100644
index 0000000000..4efe1c467e
--- /dev/null
+++ b/apps/web/lib/api/links/create-link.ts
@@ -0,0 +1,164 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds } from "./utils";
+
+export async function createLink(link: LinkWithTagIdsProps) {
+ let { key, url, expiresAt, title, description, image, proxy, geo } = link;
+
+ const combinedTagIds = combineTagIds(link);
+
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(url);
+
+ const { tagId, tagIds, ...rest } = link;
+
+ const response = await prisma.link.create({
+ data: {
+ ...rest,
+ key,
+ title: truncate(title, 120),
+ description: truncate(description, 240),
+ // if it's an uploaded image, make this null first because we'll update it later
+ image: proxy && image && !isStored(image) ? null : image,
+ utm_source,
+ utm_medium,
+ utm_campaign,
+ utm_term,
+ utm_content,
+ expiresAt: expiresAt ? new Date(expiresAt) : null,
+ geo: geo || Prisma.JsonNull,
+ ...(combinedTagIds.length > 0 && {
+ tags: {
+ createMany: {
+ data: combinedTagIds.map((tagId) => ({ tagId })),
+ },
+ },
+ }),
+ },
+ include: {
+ tags: {
+ select: {
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const uploadedImageUrl = `${process.env.STORAGE_BASE_URL}/images/${response.id}`;
+
+ const effects = await Promise.all([
+ // record link in Redis
+ redis.hset(link.domain, {
+ [link.key.toLowerCase()]: await formatRedisLink(response),
+ }),
+ // record link in Tinybird
+ recordLink({
+ link: {
+ ...response,
+ tags: response.tags.map(({ tag }) => ({
+ tagId: tag.id,
+ })),
+ },
+ }),
+ // if proxy image is set, upload image to R2 and update the link with the uploaded image URL
+ ...(proxy && image && !isStored(image)
+ ? [
+ // upload image to R2
+ storage.upload(`images/${response.id}`, image, {
+ width: 1200,
+ height: 630,
+ }),
+ // update the null image we set earlier to the uploaded image URL
+ prisma.link.update({
+ where: {
+ id: response.id,
+ },
+ data: {
+ image: uploadedImageUrl,
+ },
+ }),
+ ]
+ : []),
+ // delete public links after 30 mins
+ !response.userId &&
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete`,
+ // delete after 30 mins
+ delay: 30 * 60,
+ body: {
+ linkId: response.id,
+ },
+ }),
+ // update links usage for workspace
+ link.projectId &&
+ prisma.project.update({
+ where: {
+ id: link.projectId,
+ },
+ data: {
+ linksUsage: {
+ increment: 1,
+ },
+ },
+ }),
+ ]);
+
+ const shortLink = linkConstructor({
+ domain: response.domain,
+ key: response.key,
+ });
+ const tags = response.tags.map(({ tag }) => tag);
+ return {
+ ...response,
+ // optimistically set the image URL to the uploaded image URL
+ image:
+ proxy && image && !isStored(image) ? uploadedImageUrl : response.image,
+ tagId: tags?.[0]?.id ?? null, // backwards compatibility
+ tags,
+ shortLink,
+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,
+ workspaceId: `ws_${response.projectId}`,
+ };
+}
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
new file mode 100644
index 0000000000..4bcdcaf19f
--- /dev/null
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -0,0 +1,69 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds, keyChecks, processKey } from "./utils";
+
+export async function deleteLink(linkId: string) {
+ const link = await prisma.link.delete({
+ where: {
+ id: linkId,
+ },
+ include: {
+ tags: true,
+ },
+ });
+ return await Promise.allSettled([
+ // if the image is stored in Cloudflare R2, delete it
+ link.proxy &&
+ link.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
+ storage.delete(`images/${link.id}`),
+ redis.hdel(link.domain, link.key.toLowerCase()),
+ recordLink({ link, deleted: true }),
+ link.projectId &&
+ prisma.project.update({
+ where: {
+ id: link.projectId,
+ },
+ data: {
+ linksUsage: {
+ decrement: 1,
+ },
+ },
+ }),
+ ]);
+}
diff --git a/apps/web/lib/api/links/edit-link.ts b/apps/web/lib/api/links/edit-link.ts
new file mode 100644
index 0000000000..00b9553255
--- /dev/null
+++ b/apps/web/lib/api/links/edit-link.ts
@@ -0,0 +1,169 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds, keyChecks, processKey } from "./utils";
+
+export async function editLink({
+ oldDomain = SHORT_DOMAIN,
+ oldKey,
+ updatedLink,
+}: {
+ oldDomain?: string;
+ oldKey: string;
+ updatedLink: LinkWithTagIdsProps;
+}) {
+ let {
+ id,
+ domain,
+ key,
+ url,
+ expiresAt,
+ title,
+ description,
+ image,
+ proxy,
+ geo,
+ } = updatedLink;
+ const changedKey = key.toLowerCase() !== oldKey.toLowerCase();
+ const changedDomain = domain !== oldDomain;
+
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(url);
+
+ // exclude fields that should not be updated
+ const {
+ id: _,
+ clicks,
+ lastClicked,
+ updatedAt,
+ tagId,
+ tagIds,
+ ...rest
+ } = updatedLink;
+
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
+
+ if (proxy && image && !isStored(image)) {
+ // only upload image if proxy is true and image is not stored in R2
+ await storage.upload(`images/${id}`, image, {
+ width: 1200,
+ height: 630,
+ });
+ }
+
+ const [response, ..._effects] = await Promise.all([
+ prisma.link.update({
+ where: {
+ id,
+ },
+ data: {
+ ...rest,
+ key,
+ title: truncate(title, 120),
+ description: truncate(description, 240),
+ image:
+ proxy && image && !isStored(image)
+ ? `${process.env.STORAGE_BASE_URL}/images/${id}`
+ : image,
+ utm_source,
+ utm_medium,
+ utm_campaign,
+ utm_term,
+ utm_content,
+ expiresAt: expiresAt ? new Date(expiresAt) : null,
+ geo: geo || Prisma.JsonNull,
+ tags: {
+ deleteMany: {
+ tagId: {
+ notIn: combinedTagIds,
+ },
+ },
+ connectOrCreate: combinedTagIds.map((tagId) => ({
+ where: { linkId_tagId: { linkId: id, tagId } },
+ create: { tagId },
+ })),
+ },
+ },
+ include: {
+ tags: {
+ select: {
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ },
+ }),
+ // record link in Redis
+ redis.hset(updatedLink.domain, {
+ [updatedLink.key.toLowerCase()]: await formatRedisLink(updatedLink),
+ }),
+ // record link in Tinybird
+ recordLink({
+ link: {
+ ...updatedLink,
+ tags: updatedLink.tagIds.map((tagId) => ({
+ tagId,
+ })),
+ },
+ }),
+ // if key is changed: delete the old key in Redis
+ (changedDomain || changedKey) &&
+ redis.hdel(oldDomain, oldKey.toLowerCase()),
+ ]);
+
+ const shortLink = linkConstructor({
+ domain: response.domain,
+ key: response.key,
+ });
+
+ const tags = response.tags.map(({ tag }) => tag);
+
+ return {
+ ...response,
+ tagId: tags?.[0]?.id ?? null, // backwards compatibility
+ tags,
+ shortLink,
+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,
+ workspaceId: `ws_${response.projectId}`,
+ };
+}
diff --git a/apps/web/lib/api/links/get-links-count.ts b/apps/web/lib/api/links/get-links-count.ts
new file mode 100644
index 0000000000..1b1252c3db
--- /dev/null
+++ b/apps/web/lib/api/links/get-links-count.ts
@@ -0,0 +1,125 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds } from "./utils";
+
+export async function getLinksCount({
+ searchParams,
+ workspaceId,
+ userId,
+}: {
+ searchParams: z.infer<typeof getLinksCountQuerySchema>;
+ workspaceId: string;
+ userId?: string | null;
+}) {
+ const { groupBy, search, domain, tagId, tagIds, showArchived, withTags } =
+ searchParams;
+
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
+
+ const linksWhere = {
+ projectId: workspaceId,
+ archived: showArchived ? undefined : false,
+ ...(userId && { userId }),
+ ...(search && {
+ OR: [
+ {
+ key: { contains: search },
+ },
+ {
+ url: { contains: search },
+ },
+ ],
+ }),
+ // when filtering by domain, only filter by domain if the filter group is not "Domains"
+ ...(domain &&
+ groupBy !== "domain" && {
+ domain,
+ }),
+ };
+
+ if (groupBy === "tagId") {
+ return await prisma.linkTag.groupBy({
+ by: ["tagId"],
+ where: {
+ link: linksWhere,
+ },
+ _count: true,
+ orderBy: {
+ _count: {
+ tagId: "desc",
+ },
+ },
+ });
+ } else {
+ const where = {
+ ...linksWhere,
+ ...(withTags && {
+ tags: {
+ some: {},
+ },
+ }),
+ ...(combinedTagIds.length > 0 && {
+ tags: {
+ some: {
+ tagId: {
+ in: tagIds,
+ },
+ },
+ },
+ }),
+ };
+
+ if (groupBy === "domain") {
+ return await prisma.link.groupBy({
+ by: [groupBy],
+ where,
+ _count: true,
+ orderBy: {
+ _count: {
+ [groupBy]: "desc",
+ },
+ },
+ });
+ } else {
+ return await prisma.link.count({
+ where,
+ });
+ }
+ }
+}
diff --git a/apps/web/lib/api/links/get-links-for-workspace.ts b/apps/web/lib/api/links/get-links-for-workspace.ts
new file mode 100644
index 0000000000..9bf7758003
--- /dev/null
+++ b/apps/web/lib/api/links/get-links-for-workspace.ts
@@ -0,0 +1,122 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds } from "./utils";
+
+export async function getLinksForWorkspace({
+ workspaceId,
+ domain,
+ tagId,
+ tagIds,
+ search,
+ sort = "createdAt",
+ page,
+ userId,
+ showArchived,
+ withTags,
+}: z.infer<typeof getLinksQuerySchema> & {
+ workspaceId: string;
+}) {
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
+
+ const links = await prisma.link.findMany({
+ where: {
+ projectId: workspaceId,
+ archived: showArchived ? undefined : false,
+ ...(domain && { domain }),
+ ...(search && {
+ OR: [
+ {
+ key: { contains: search },
+ },
+ {
+ url: { contains: search },
+ },
+ ],
+ }),
+ ...(withTags && {
+ tags: {
+ some: {},
+ },
+ }),
+ ...(combinedTagIds.length > 0 && {
+ tags: { some: { tagId: { in: combinedTagIds } } },
+ }),
+ ...(userId && { userId }),
+ },
+ include: {
+ user: true,
+ tags: {
+ include: {
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ },
+ orderBy: {
+ [sort]: "desc",
+ },
+ take: 100,
+ ...(page && {
+ skip: (page - 1) * 100,
+ }),
+ });
+
+ return links.map((link) => {
+ const shortLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+
+ const tags = link.tags.map(({ tag }) => tag);
+
+ return {
+ ...link,
+ tagId: tags?.[0]?.id ?? null, // backwards compatibility
+ tags,
+ shortLink,
+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,
+ workspaceId: `ws_${link.projectId}`,
+ };
+ });
+}
diff --git a/apps/web/lib/api/links/index.ts b/apps/web/lib/api/links/index.ts
new file mode 100644
index 0000000000..154a594431
--- /dev/null
+++ b/apps/web/lib/api/links/index.ts
@@ -0,0 +1,10 @@
+export * from "./archive-link";
+export * from "./bulk-create-links";
+export * from "./create-link";
+export * from "./delete-link";
+export * from "./edit-link";
+export * from "./get-links-count";
+export * from "./get-links-for-workspace";
+export * from "./process-link";
+export * from "./transfer-link";
+export * from "./utils";
diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.ts
new file mode 100644
index 0000000000..758fef36c6
--- /dev/null
+++ b/apps/web/lib/api/links/process-link.ts
@@ -0,0 +1,260 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+import { combineTagIds, keyChecks, processKey } from "./utils";
+
+export async function processLink({
+ payload,
+ workspace,
+ userId,
+ bulk = false,
+ skipKeyChecks = false, // only skip when key doesn't change (e.g. when editing a link)
+}: {
+ payload: LinkWithTagIdsProps;
+ workspace?: WorkspaceProps;
+ userId?: string;
+ bulk?: boolean;
+ skipKeyChecks?: boolean;
+}) {
+ let {
+ domain,
+ key,
+ url,
+ image,
+ proxy,
+ password,
+ rewrite,
+ expiresAt,
+ ios,
+ android,
+ geo,
+ } = payload;
+
+ const tagIds = combineTagIds(payload);
+
+ // url checks
+ if (!url) {
+ return {
+ link: payload,
+ error: "Missing destination url.",
+ code: "bad_request",
+ };
+ }
+ const processedUrl = getUrlFromString(url);
+ if (!isValidUrl(processedUrl)) {
+ return {
+ link: payload,
+ error: "Invalid destination url.",
+ code: "unprocessable_entity",
+ };
+ }
+
+ // free plan restrictions
+ if (!workspace || workspace.plan === "free") {
+ if (proxy || password || rewrite || expiresAt || ios || android || geo) {
+ return {
+ link: payload,
+ error:
+ "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.",
+ code: "forbidden",
+ };
+ }
+ }
+
+ // if domain is not defined, set it to the workspace's primary domain
+ if (!domain) {
+ domain = workspace?.domains?.find((d) => d.primary)?.slug || SHORT_DOMAIN;
+ }
+
+ // checks for default short domain
+ if (domain === SHORT_DOMAIN) {
+ const keyBlacklisted = await isBlacklistedKey(key);
+ if (keyBlacklisted) {
+ return {
+ link: payload,
+ error: "Invalid key.",
+ code: "unprocessable_entity",
+ };
+ }
+ const domainBlacklisted = await isBlacklistedDomain(url);
+ if (domainBlacklisted) {
+ return {
+ link: payload,
+ error: "Invalid url.",
+ code: "unprocessable_entity",
+ };
+ }
+
+ // checks for other Dub-owned domains (chatg.pt, spti.fi, etc.)
+ } else if (isDubDomain(domain)) {
+ // coerce type with ! cause we already checked if it exists
+ 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
+ .map((d) => `\`${d}\``)
+ .join(", ")}.`,
+ code: "unprocessable_entity",
+ };
+ }
+
+ // else, check if the domain belongs to the workspace
+ } else if (!workspace?.domains?.find((d) => d.slug === domain)) {
+ return {
+ link: payload,
+ error: "Domain does not belong to workspace.",
+ code: "forbidden",
+ };
+ }
+
+ if (!key) {
+ key = await getRandomKey(domain, payload["prefix"]);
+ } else if (!skipKeyChecks) {
+ const processedKey = processKey(key);
+ if (processedKey === null) {
+ return {
+ link: payload,
+ error: "Invalid key.",
+ code: "unprocessable_entity",
+ };
+ }
+ key = processedKey;
+
+ const response = await keyChecks({ domain, key, workspace });
+ if (response.error) {
+ return {
+ link: payload,
+ ...response,
+ };
+ }
+ }
+
+ if (bulk) {
+ if (image) {
+ return {
+ link: payload,
+ error: "You cannot set custom social cards with bulk link creation.",
+ code: "unprocessable_entity",
+ };
+ }
+ if (rewrite) {
+ return {
+ link: payload,
+ error: "You cannot use link cloaking with bulk link creation.",
+ code: "unprocessable_entity",
+ };
+ }
+
+ // only perform tag validity checks if:
+ // - not bulk creation (we do that check separately in the route itself)
+ // - tagIds are present
+ } else if (tagIds.length > 0) {
+ const tags = await prisma.tag.findMany({
+ select: {
+ id: true,
+ },
+ where: { projectId: workspace?.id, id: { in: tagIds } },
+ });
+
+ if (tags.length !== tagIds.length) {
+ return {
+ link: payload,
+ error:
+ "Invalid tagIds detected: " +
+ tagIds
+ .filter(
+ (tagId) => tags.find(({ id }) => tagId === id) === undefined,
+ )
+ .join(", "),
+ code: "unprocessable_entity",
+ };
+ }
+ }
+
+ // custom social media image checks (see if R2 is configured)
+ if (proxy && !process.env.STORAGE_SECRET_ACCESS_KEY) {
+ return {
+ link: payload,
+ error: "Missing storage access key.",
+ code: "bad_request",
+ };
+ }
+
+ // 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.",
+ code: "unprocessable_entity",
+ };
+ }
+ // check if expiresAt is in the future
+ if (new Date(expiresAt) < new Date()) {
+ return {
+ link: payload,
+ error: "Expiry date must be in the future.",
+ code: "unprocessable_entity",
+ };
+ }
+ }
+
+ // remove polyfill attributes from payload
+ delete payload["shortLink"];
+ delete payload["qrCode"];
+ delete payload["prefix"];
+
+ return {
+ link: {
+ ...payload,
+ domain,
+ key,
+ url: processedUrl,
+ // make sure projectId is set to the current workspace
+ projectId: workspace?.id || null,
+ // if userId is passed, set it (we don't change the userId if it's already set, e.g. when editing a link)
+ ...(userId && {
+ userId,
+ }),
+ },
+ error: null,
+ };
+}
diff --git a/apps/web/lib/api/links/transfer-link.ts b/apps/web/lib/api/links/transfer-link.ts
new file mode 100644
index 0000000000..849335cf08
--- /dev/null
+++ b/apps/web/lib/api/links/transfer-link.ts
@@ -0,0 +1,22 @@
+import prisma from "@/lib/prisma";
+
+export async function transferLink({
+ linkId,
+ newWorkspaceId,
+}: {
+ linkId: string;
+ newWorkspaceId: string;
+}) {
+ return await prisma.link.update({
+ where: {
+ id: linkId,
+ },
+ data: {
+ projectId: newWorkspaceId,
+ // remove tags when transferring link
+ tags: {
+ deleteMany: {},
+ },
+ },
+ });
+}
diff --git a/apps/web/lib/api/links/utils.ts b/apps/web/lib/api/links/utils.ts
new file mode 100644
index 0000000000..1394f83ae5
--- /dev/null
+++ b/apps/web/lib/api/links/utils.ts
@@ -0,0 +1,130 @@
+import {
+ isBlacklistedDomain,
+ isBlacklistedKey,
+ isReservedKey,
+ isReservedUsername,
+} from "@/lib/edge-config";
+import prisma from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
+import { formatRedisLink, redis } from "@/lib/upstash";
+import {
+ getLinksCountQuerySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas/links";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DEFAULT_REDIRECTS,
+ DUB_DOMAINS,
+ SHORT_DOMAIN,
+ getDomainWithoutWWW,
+ getParamsFromURL,
+ getUrlFromString,
+ isDubDomain,
+ isValidUrl,
+ linkConstructor,
+ truncate,
+ validKeyRegex,
+} from "@dub/utils";
+import { Prisma } from "@prisma/client";
+import { checkIfKeyExists, getRandomKey } from "@/lib/planetscale";
+import { recordLink } from "@/lib/tinybird";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ RedisLinkProps,
+ WorkspaceProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import { qstash } from "@/lib/cron";
+
+export function combineTagIds({
+ tagId,
+ tagIds,
+}: {
+ tagId?: string | null;
+ tagIds?: string[];
+}): string[] {
+ // Use tagIds if present, fall back to tagId
+ if (tagIds && Array.isArray(tagIds) && tagIds.length > 0) {
+ return tagIds;
+ }
+ return tagId ? [tagId] : [];
+}
+
+export async function keyChecks({
+ domain,
+ key,
+ workspace,
+}: {
+ domain: string;
+ key: string;
+ workspace?: WorkspaceProps;
+}) {
+ if (key.length === 0) {
+ if (workspace?.plan === "free") {
+ return {
+ error:
+ "You can only set a redirect for your root domain on a Pro plan and above. Upgrade to Pro to unlock this feature.",
+ code: "forbidden",
+ };
+ } else {
+ return {
+ error:
+ "To set a redirect for your root domain, navigate to your Domains tab and click 'Edit' on the domain you want to update.",
+ code: "unprocessable_entity",
+ };
+ }
+ }
+
+ const link = await checkIfKeyExists(domain, key);
+ if (link) {
+ return {
+ error: "Duplicate key: This short link already exists.",
+ code: "conflict",
+ };
+ }
+
+ if (isDubDomain(domain) && process.env.NEXT_PUBLIC_IS_DUB) {
+ if (
+ domain === SHORT_DOMAIN &&
+ (DEFAULT_REDIRECTS[key] || (await isReservedKey(key)))
+ ) {
+ return {
+ error: "Duplicate key: This short link already exists.",
+ code: "conflict",
+ };
+ }
+
+ if (key.length <= 3 && (!workspace || workspace.plan === "free")) {
+ return {
+ error: `You can only use keys that are 3 characters or less on a Pro plan and above. Upgrade to Pro to register a ${key.length}-character key.`,
+ code: "forbidden",
+ };
+ }
+ if (
+ (await isReservedUsername(key)) &&
+ (!workspace || workspace.plan === "free")
+ ) {
+ return {
+ error:
+ "This is a premium key. You can only use this key on a Pro plan and above. Upgrade to Pro to register this key.",
+ code: "forbidden",
+ };
+ }
+ }
+ return {
+ error: null,
+ };
+}
+
+export function processKey(key: string) {
+ if (!validKeyRegex.test(key)) {
+ return null;
+ }
+ // remove all leading and trailing slashes from key
+ key = key.replace(/^\/+|\/+$/g, "");
+ // replace all special characters
+ key = key.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
+
+ return key;
+}
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 4f4a5c2434..ec2ded9cd6 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -7,6 +7,10 @@
{
"path": "/api/cron/usage",
"schedule": "0 14 * * *"
+ },
+ {
+ "path": "/api/links/usage",
+ "schedule": "*/5 * * * *"
}
],
"functions": {