The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
remove on-demand importer
Steven Teya738fb0cbe7f
diff --git a/apps/web/app/api/links/crawl/bitly/route.ts b/apps/web/app/api/links/crawl/bitly/route.tsindex 05f6de8ef2..8d026298cc 100644--- a/apps/web/app/api/links/crawl/bitly/route.ts+++ b/apps/web/app/api/links/crawl/bitly/route.ts@@ -1,106 +1,47 @@-import { encodeKeyIfCaseSensitive } from "@/lib/api/case-sensitive-short-links";-import { createId } from "@/lib/api/create-id";-import { conn } from "@/lib/planetscale";import { redis } from "@/lib/upstash";-import { getUrlFromStringIfValid, linkConstructorSimple } from "@dub/utils";-import { NextResponse } from "next/server";+import { DUB_HEADERS, getUrlFromStringIfValid } from "@dub/utils";+import { NextRequest, NextResponse } from "next/server";import { z } from "zod";-const workspaceId = "cm05wnnpo000711ztj05wwdbu";-const userId = "cm05wnd49000411ztg2xbup0i";-const folderId = "fold_LIZsdjTgFVbQVGYSUmYAi5vT";--// POST /api/links/crawl/bitly – crawl a bitly link-export const POST = async (req: Request) => {- const body = await req.json();-- let { domain, key } = z+// GET /api/links/crawl/bitly – crawl a bitly link and redirect to the destination if exists+export const GET = async (req: NextRequest) => {+ const { domain, key } = z.object({domain: z.string(),key: z.string(),})- .parse(body);-- if (domain !== "buff.ly") {- return NextResponse.json({ error: "Not found" }, { status: 404 });- }+ .parse(req.nextUrl.searchParams);// bitly doesn't support the following characters: ` ~ , . < > ; ‘ : “ / \ [ ] ^ { } ( ) = + ! * @ & $ £ ? % # |// @see: https://support.bitly.com/hc/en-us/articles/360030780892-What-characters-are-supported-when-customizing-linksconst invalidBitlyKeyRegex = /[`~,.<>;':"/\\[\]^{}()=+!*@&$£?%#|]/;- if (invalidBitlyKeyRegex.test(key)) {- return NextResponse.json({ error: "Not found" }, { status: 404 });- }-- const link = await crawlBitlyLink({ domain, key, workspaceId });-- if (!link) {- return NextResponse.json({ error: "Not found" }, { status: 404 });- }- const sanitizedUrl = getUrlFromStringIfValid(link.long_url);-- if (!sanitizedUrl) {- return NextResponse.json({ error: "Not found" }, { status: 404 });+ if (domain === "buff.ly" && !invalidBitlyKeyRegex.test(key)) {+ const link = await crawlBitlyLink({ domain, key });+ if (link) {+ const sanitizedUrl = getUrlFromStringIfValid(link.long_url);++ if (sanitizedUrl) {+ return NextResponse.redirect(sanitizedUrl, {+ headers: DUB_HEADERS,+ status: 302,+ });+ }+ }}- key = encodeKeyIfCaseSensitive({- domain,- key,+ return NextResponse.redirect("https://buffer.com", {+ headers: DUB_HEADERS,+ status: 302,});-- const newLink = {- id: createId({ prefix: "link_" }),- projectId: workspaceId,- userId,- domain,- key,- url: sanitizedUrl,- shortLink: linkConstructorSimple({- domain,- key,- }),- archived: false,- folderId,- createdAt: new Date(link.created_at),- updatedAt: new Date(link.created_at),- };-- console.log("[Bitly] Creating link", newLink);-- try {- await conn.execute(- "INSERT INTO Link (id, projectId, userId, domain, `key`, url, shortLink, archived, folderId, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",- [- newLink.id,- newLink.projectId,- newLink.userId,- newLink.domain,- newLink.key,- newLink.url,- newLink.shortLink,- newLink.archived,- newLink.folderId,- newLink.createdAt,- newLink.updatedAt,- ],- );-- return NextResponse.json(newLink);- } catch (error) {- console.error("[Bitly] Error creating link", error);- return NextResponse.json({ error: "Not found" }, { status: 404 });- }};async function crawlBitlyLink({domain,key,- workspaceId,}: {domain: string;key: string;- workspaceId: string;}) {const response = await fetch(`https://bit.ly/${key}`, {method: "HEAD",@@ -117,7 +58,7 @@ async function crawlBitlyLink({console.error(`[Bitly] Link ${domain}/${key} not found. Falling back to API...`,);- return await fetchBitlyLink({ domain, key, workspaceId });+ return await fetchBitlyLink({ domain, key });}const destinationUrl = response.headers.get("location");@@ -135,14 +76,15 @@ async function crawlBitlyLink({};}+// buffer's workspace ID+const workspaceId = "cm05wnnpo000711ztj05wwdbu";+async function fetchBitlyLink({domain,key,- workspaceId,}: {domain: string;key: string;- workspaceId: string;}) {const apiKey = await redis.get<string>(`import:bitly:${workspaceId}`);diff --git a/apps/web/lib/api/case-sensitive-short-links.ts b/apps/web/lib/api/case-sensitive-short-links.tsindex c95c9934aa..7c795ef76b 100644--- a/apps/web/lib/api/case-sensitive-short-links.ts+++ b/apps/web/lib/api/case-sensitive-short-links.ts@@ -1,6 +1,6 @@import { LinkProps } from "../types";-export const CASE_SENSITIVE_DOMAINS = ["buff.ly", "getacme.link"];+export const CASE_SENSITIVE_DOMAINS = ["buff.ly", "dub-internal-test.com"];// This is not actually a secret key, it's just a string that we XOR with the key to make it case sensitiveconst SECRET_KEY = "58ff90c0dc372ded858cbf8fb2306066";diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex a41d2e975b..82fd65df7f 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -27,7 +27,6 @@ import { isCaseSensitiveDomain } from "../api/case-sensitive-short-links";import { linkCache } from "../api/links/cache";import { getLinkViaEdge } from "../planetscale";import { getDomainViaEdge } from "../planetscale/get-domain-via-edge";-import { importBitlyLink } from "./bitly";import { hasEmptySearchParams } from "./utils/has-empty-search-params";export default async function LinkMiddleware(@@ -75,22 +74,22 @@ export default async function LinkMiddleware(});}- let link = await linkCache.get({ domain, key });+ let cachedLink = await linkCache.get({ domain, key });- if (!link) {- let linkData = await getLinkViaEdge({ domain, key });+ if (!cachedLink) {+ let linkData = await getLinkViaEdge({+ domain,+ key,+ });if (!linkData) {- if (domain === "buff.ly" || domain === "dev.buff.ly") {- linkData = await getLinkViaEdge({- domain,- key: originalKey,- caseSensitive: false,- });-- if (!linkData) {- linkData = await importBitlyLink({ domain, key: originalKey });- }+ if (domain === "buff.ly") {+ return NextResponse.rewrite(+ new URL(+ `/api/links/crawl/bitly?domain=${domain}&key=${key}`,+ req.url,+ ),+ );}if (!linkData) {@@ -118,7 +117,7 @@ export default async function LinkMiddleware(}// format link to fit the RedisLinkProps interface- link = formatRedisLink(linkData as any);+ cachedLink = formatRedisLink(linkData as any);ev.waitUntil(linkCache.set(linkData as any));}@@ -138,7 +137,7 @@ export default async function LinkMiddleware(doIndex,webhookIds,projectId: workspaceId,- } = link;+ } = cachedLink;// by default, we only index default dub domain links (e.g. dub.sh)// everything else is not indexed by default, unless the user has explicitly set it to be indexed@@ -183,7 +182,7 @@ export default async function LinkMiddleware(}// if the link is banned- if (link.projectId === LEGAL_WORKSPACE_ID) {+ if (workspaceId === LEGAL_WORKSPACE_ID) {return NextResponse.rewrite(new URL("/banned", req.url), {headers: {...DUB_HEADERS,diff --git a/apps/web/lib/planetscale/get-link-via-edge.ts b/apps/web/lib/planetscale/get-link-via-edge.tsindex 55d8ea34f7..41679385d5 100644--- a/apps/web/lib/planetscale/get-link-via-edge.ts+++ b/apps/web/lib/planetscale/get-link-via-edge.ts@@ -1,7 +1,7 @@import { punyEncode } from "@dub/utils";import {- decodeKeyIfCaseSensitive,decodeLinkIfCaseSensitive,+ encodeKeyIfCaseSensitive,} from "../api/case-sensitive-short-links";import { conn } from "./connection";import { EdgeLinkProps } from "./types";@@ -9,23 +9,19 @@ import { EdgeLinkProps } from "./types";export const getLinkViaEdge = async ({domain,key,- caseSensitive = true,}: {domain: string;key: string;- caseSensitive?: boolean;}) => {- const decodedKey = caseSensitive- ? decodeKeyIfCaseSensitive({- domain,- key,- })- : key;+ const keyToQuery = encodeKeyIfCaseSensitive({+ domain,+ key,+ });const { rows } =(await conn.execute("SELECT * FROM Link WHERE domain = ? AND `key` = ?",- [domain, punyEncode(decodeURIComponent(decodedKey))], // we need to make sure that the key is always URI-decoded + punycode-encoded (cause that's how we store it in MySQL)+ [domain, punyEncode(decodeURIComponent(keyToQuery))], // we need to make sure that the key is always URI-decoded + punycode-encoded (cause that's how we store it in MySQL))) || {};const link =@@ -33,5 +29,5 @@ export const getLinkViaEdge = async ({? (rows[0] as EdgeLinkProps): null;- return link ? (caseSensitive ? decodeLinkIfCaseSensitive(link) : link) : null;+ return link ? decodeLinkIfCaseSensitive(link) : null;};diff --git a/apps/web/scripts/buffer/migrate-to-case-sensitive.ts b/apps/web/scripts/buffer/migrate-to-case-sensitive.tsindex fd038cac50..60d0d6615e 100644--- a/apps/web/scripts/buffer/migrate-to-case-sensitive.ts+++ b/apps/web/scripts/buffer/migrate-to-case-sensitive.ts@@ -4,7 +4,7 @@ import "dotenv-flow/config";import { encodeKeyIfCaseSensitive } from "../../lib/api/case-sensitive-short-links";import { linkCache } from "../../lib/api/links/cache";-const domain = "getacme.link";+const domain = "dub-internal-test.com";async function main() {const links = await prisma.link.findMany({@@ -13,8 +13,6 @@ async function main() {// TODO:// Fetch the links created using the Dub API},- take: 0,- skip: 0,});if (!links.length) {diff --git a/packages/email/src/templates/clicks-summary.tsx b/packages/email/src/templates/clicks-summary.tsxindex cb37d06ae1..e862740f7f 100644--- a/packages/email/src/templates/clicks-summary.tsx+++ b/packages/email/src/templates/clicks-summary.tsx@@ -34,7 +34,7 @@ export function ClicksSummary({clicks: 2187,},{- link: "getacme.link",+ link: "acme.com",clicks: 1552,},{