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.

improved error handling

Steven Tey34df40e43760
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 39ff7e81a9..58eb1d0e9b 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -1,7 +1,7 @@
+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 { DubApiError, ErrorCodes } from "@/lib/api/errors";
import { LinkWithTagIdsProps } from "@/lib/types";
import { updateLinkBodySchema } from "@/lib/zod/schemas/links";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -38,6 +38,10 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {
} = await processLink({
payload: updatedLink as LinkWithTagIdsProps,
project,
+ // if domain and key are the same, we don't need to check if the key exists
+ skipKeyChecks:
+ link!.domain === updatedLink.domain &&
+ link!.key.toLowerCase() === updatedLink.key?.toLowerCase(),
});
if (error) {
@@ -64,13 +68,6 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {
// @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.",
- });
- }
-
return NextResponse.json(response, {
headers,
});
diff --git a/apps/web/app/api/links/exists/route.ts b/apps/web/app/api/links/exists/route.ts
deleted file mode 100644
index ba3fd31b38..0000000000
--- a/apps/web/app/api/links/exists/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { checkIfKeyExists } from "@/lib/api/links";
-import { withAuth } from "@/lib/auth";
-import { domainKeySchema } from "@/lib/zod";
-import { NextResponse } from "next/server";
-
-// GET /api/links/exists – check if a link exists
-export const GET = withAuth(
- async ({ headers, searchParams }) => {
- const { domain, key } = domainKeySchema.parse(searchParams);
- const response = await checkIfKeyExists(domain, key);
- return NextResponse.json(response, {
- headers,
- });
- },
- { skipLinkChecks: true },
-);
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index ab38bfaac3..a50778a768 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -74,13 +74,6 @@ export const POST = withAuth(
const response = await addLink(link);
- 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: {
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index d35475be15..717847ee8b 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -24,7 +24,7 @@ import {
validKeyRegex,
} from "@dub/utils";
import cloudinary from "cloudinary";
-import { getLinkViaEdge } from "../planetscale";
+import { checkIfKeyExists } from "../planetscale";
import { recordLink } from "../tinybird";
import {
LinkProps,
@@ -197,20 +197,53 @@ export async function getLinksCount({
}
}
-export async function checkIfKeyExists(domain: string, key: string) {
- // reserved keys for default short domain
- if (domain === SHORT_DOMAIN) {
- if ((await isReservedKey(key)) || DEFAULT_REDIRECTS[key]) {
- return true;
+export async function keyChecks({
+ domain,
+ key,
+ project,
+}: {
+ domain: string;
+ key: string;
+ project?: ProjectProps;
+}) {
+ 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 it's a default Dub domain, check if the key is a reserved key
- } else if (isDubDomain(domain)) {
- if (await isReservedUsername(key)) {
- return true;
+
+ if (key.length <= 3 && (!project || project.plan === "free")) {
+ return {
+ error: `You can only use keys shorter than 3 characters on a Pro plan and above. Upgrade to Pro to register a ${key.length}-character key.`,
+ code: "forbidden",
+ };
+ }
+ if (
+ (await isReservedUsername(key)) &&
+ (!project || project.plan === "free")
+ ) {
+ return {
+ error: `This is a premium username. You can only use this username on a Pro plan and above. Upgrade to Pro to register this username.`,
+ code: "forbidden",
+ };
}
}
- const link = await getLinkViaEdge(domain, key);
- return !!link;
+ return {
+ error: null,
+ };
}
export async function getRandomKey(
@@ -222,8 +255,8 @@ export async function getRandomKey(
if (prefix) {
key = `${prefix.replace(/^\/|\/$/g, "")}/${key}`;
}
- const response = await checkIfKeyExists(domain, key);
- if (response) {
+ const response = await keyChecks({ domain, key });
+ if (response.error) {
// by the off chance that key already exists
return getRandomKey(domain, prefix);
} else {
@@ -248,11 +281,13 @@ export async function processLink({
project,
userId,
bulk = false,
+ skipKeyChecks = false, // only skip when key doesn't change (e.g. when editing a link)
}: {
payload: LinkWithTagIdsProps;
project?: ProjectProps;
userId?: string;
bulk?: boolean;
+ skipKeyChecks?: boolean;
}) {
let {
domain,
@@ -349,18 +384,24 @@ export async function processLink({
if (!key) {
key = await getRandomKey(domain, payload["prefix"]);
+ } else if (!skipKeyChecks) {
+ const processedKey = processKey(key);
+ if (!processedKey) {
+ return {
+ link: payload,
+ error: "Invalid key.",
+ code: "unprocessable_entity",
+ };
+ }
+ key = processedKey;
- // restrict key length to at least 4 characters for free plan
- } else if (
- isDubDomain(domain) &&
- key.length <= 3 &&
- (!project || project.plan === "free")
- ) {
- return {
- link: payload,
- error: `You can only use keys shorter than 3 characters on a Pro plan and above. Upgrade to Pro to register a ${key.length}-character key.`,
- code: "forbidden",
- };
+ const response = await keyChecks({ domain, key, project });
+ if (response.error) {
+ return {
+ link: payload,
+ ...response,
+ };
+ }
}
if (bulk) {
@@ -378,16 +419,6 @@ export async function processLink({
code: "unprocessable_entity",
};
}
- // we check if a key exists in bulk creation because
- // for regular creation we check it in the addLink function
- const exists = await checkIfKeyExists(domain, key);
- if (exists) {
- return {
- link: payload,
- error: `Link already exists.`,
- code: "conflict",
- };
- }
// only perform tag validity checks if:
// - not bulk creation (we do that check in bulkCreateLinks)
@@ -486,9 +517,6 @@ export async function addLink(link: LinkWithTagIdsProps) {
link;
const uploadedImage = image && image.startsWith("data:image") ? true : false;
- const exists = await checkIfKeyExists(domain, key);
- if (exists) return null;
-
const combinedTagIds = combineTagIds(link);
const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
@@ -711,10 +739,6 @@ export async function editLink({
const changedDomain = domain !== oldDomain;
const uploadedImage = image && image.startsWith("data:image") ? true : false;
- if (changedDomain || changedKey) {
- const exists = await checkIfKeyExists(domain, key);
- if (exists) return null;
- }
const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
getParamsFromURL(url);
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index bdb6ae6171..c31683d512 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -30,6 +30,18 @@ export const getDomainViaEdge = async (domain: string) => {
: null;
};
+export const checkIfKeyExists = async (domain: string, key: string) => {
+ if (!process.env.DATABASE_URL) return null;
+
+ const { rows } =
+ (await conn.execute(
+ "SELECT 1 FROM Link WHERE domain = ? AND `key` = ? LIMIT 1",
+ [domain, decodeURIComponent(key)], // we need to make sure that the key is always decoded (cause that's how we store it in MySQL)
+ )) || {};
+
+ return rows && Array.isArray(rows) && rows.length > 0;
+};
+
export const getLinkViaEdge = async (domain: string, key: string) => {
if (!process.env.DATABASE_URL) return null;
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index e775d33e99..8bd1262cf1 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -101,32 +101,6 @@ function AddEditLinkModal({
const { domain, key, url, password, proxy } = data;
- const [debouncedKey] = useDebounce(key, 500);
- useEffect(() => {
- /**
- * Only check if key exists if:
- * - modal is open
- * - key is not empty
- * - key is not the same as the original key
- **/
- if (
- showAddEditLinkModal &&
- debouncedKey.length > 0 &&
- debouncedKey.toLowerCase() !== props?.key.toLowerCase()
- ) {
- fetch(
- `/api/links/exists?domain=${domain}&key=${debouncedKey}&projectSlug=${slug}`,
- ).then(async (res) => {
- if (res.status === 200) {
- const exists = await res.json();
- setKeyError(
- exists ? "Duplicate key: This short link already exists." : null,
- );
- }
- });
- }
- }, [debouncedKey, domain]);
-
const generateRandomKey = useCallback(async () => {
setKeyError(null);
setGeneratingKey(true);
@@ -553,11 +527,23 @@ function AddEditLinkModal({
</div>
)}
</div>
- {keyError && (
- <p className="mt-2 text-sm text-red-600" id="key-error">
- {keyError}
- </p>
- )}
+ {keyError &&
+ (keyError.includes("Upgrade to Pro") ? (
+ <p className="mt-2 text-sm text-red-600" id="key-error">
+ {keyError.split("Upgrade to Pro")[0]}
+ <span
+ className="cursor-pointer underline"
+ onClick={() => queryParams({ set: { upgrade: "pro" } })}
+ >
+ Upgrade to Pro
+ </span>
+ {keyError.split("Upgrade to Pro")[1]}
+ </p>
+ ) : (
+ <p className="mt-2 text-sm text-red-600" id="key-error">
+ {keyError}
+ </p>
+ ))}
</div>
</div>