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.

stop on-demand importer

Steven Tey20f8c35ea76c
diff --git a/apps/web/app/api/links/crawl/bitly/[domain]/[key]/route.ts b/apps/web/app/api/links/crawl/bitly/[domain]/[key]/route.ts
new file mode 100644
index 0000000000..2b8a950b53
--- /dev/null
+++ b/apps/web/app/api/links/crawl/bitly/[domain]/[key]/route.ts
@@ -0,0 +1,113 @@
+import { redis } from "@/lib/upstash";
+import z from "@/lib/zod";
+import { DUB_HEADERS, getUrlFromStringIfValid } from "@dub/utils";
+import { NextRequest, NextResponse } from "next/server";
+
+// GET /api/links/crawl/bitly – crawl a bitly link and redirect to the destination if exists
+export const GET = async (_req: NextRequest, { params }) => {
+ const { domain, key } = z
+ .object({
+ domain: z.string(),
+ key: z.string(),
+ })
+ .parse(params);
+
+ // bitly doesn't support the following characters: ` ~ , . < > ; ‘ : “ / \ [ ] ^ { } ( ) = + ! * @ & $ £ ? % # |
+ // @see: https://support.bitly.com/hc/en-us/articles/360030780892-What-characters-are-supported-when-customizing-links
+ const invalidBitlyKeyRegex = /[`~,.<>;':"/\\[\]^{}()=+!*@&$£?%#|]/;
+
+ if (key && !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,
+ });
+ }
+ }
+ }
+
+ return NextResponse.redirect("https://buffer.com", {
+ headers: DUB_HEADERS,
+ status: 302,
+ });
+};
+
+async function crawlBitlyLink({
+ domain,
+ key,
+}: {
+ domain: string;
+ key: string;
+}) {
+ const response = await fetch(`https://bit.ly/${key}`, {
+ method: "HEAD",
+ redirect: "manual",
+ headers: {
+ Host: domain,
+ "User-Agent":
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
+ },
+ });
+
+ // If the link is not found, fallback to the API
+ if (!response.ok && response.status !== 301 && response.status !== 302) {
+ console.error(
+ `[Bitly] Link ${domain}/${key} not found. Falling back to API...`,
+ );
+ return await fetchBitlyLink({ domain, key });
+ }
+
+ const destinationUrl = response.headers.get("location");
+ if (!destinationUrl) {
+ console.error(`[Bitly] No redirect URL found for ${domain}/${key}`);
+ return null;
+ }
+
+ console.log(`[Bitly] Found link ${domain}/${key} -> ${destinationUrl}`);
+
+ return {
+ id: `${domain}/${key}`,
+ long_url: destinationUrl,
+ created_at: new Date().toISOString(),
+ };
+}
+
+// buffer's workspace ID
+const workspaceId = "cm05wnnpo000711ztj05wwdbu";
+
+async function fetchBitlyLink({
+ domain,
+ key,
+}: {
+ domain: string;
+ key: string;
+}) {
+ const apiKey = await redis.get<string>(`import:bitly:${workspaceId}`);
+
+ if (!apiKey) {
+ console.error(`[Bitly] No API key found for workspace ${workspaceId}`);
+ return null;
+ }
+
+ const response = await fetch(
+ `https://api-ssl.bitly.com/v4/bitlinks/${domain}/${key}`,
+ {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ },
+ );
+
+ if (!response.ok) {
+ console.log(
+ `[Bitly] Hit rate limit, returning 404 for ${domain}/${key} for now...`,
+ );
+ return null;
+ }
+
+ return await response.json();
+}
diff --git a/apps/web/app/api/links/crawl/bitly/route.ts b/apps/web/app/api/links/crawl/bitly/route.ts
deleted file mode 100644
index 5eefb3998c..0000000000
--- a/apps/web/app/api/links/crawl/bitly/route.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import { createId } from "@/lib/api/create-id";
-import { ExpandedLink } from "@/lib/api/links";
-import { conn } from "@/lib/planetscale";
-import { recordLink } from "@/lib/tinybird/record-link";
-import { redis } from "@/lib/upstash";
-import { getUrlFromStringIfValid, linkConstructorSimple } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { NextResponse } from "next/server";
-import { z } from "zod";
-
-// POST /api/links/crawl/bitly – crawl a bitly link
-export const POST = async (req: Request) => {
- const body = await req.json();
-
- 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 });
- }
-
- // bitly doesn't support the following characters: ` ~ , . < > ; ‘ : “ / \ [ ] ^ { } ( ) = + ! * @ & $ £ ? % # |
- // @see: https://support.bitly.com/hc/en-us/articles/360030780892-What-characters-are-supported-when-customizing-links
- const invalidBitlyKeyRegex = /[`~,.<>;':"/\\[\]^{}()=+!*@&$£?%#|]/;
- if (invalidBitlyKeyRegex.test(key)) {
- return NextResponse.json({ error: "Not found" }, { status: 404 });
- }
-
- const workspaceId = "cm05wnnpo000711ztj05wwdbu";
- const userId = "cm05wnd49000411ztg2xbup0i";
- const folderId = "fold_LIZsdjTgFVbQVGYSUmYAi5vT";
-
- 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 });
- }
-
- 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,
- ],
- );
-
- waitUntil(
- recordLink({
- ...newLink,
- tenantId: null,
- programId: null,
- partnerId: null,
- tags: [],
- } as unknown as ExpandedLink),
- );
-
- 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",
- redirect: "manual",
- headers: {
- Host: domain,
- "User-Agent":
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
- },
- });
-
- // If the link is not found, fallback to the API
- if (!response.ok && response.status !== 301 && response.status !== 302) {
- console.error(
- `[Bitly] Link ${domain}/${key} not found. Falling back to API...`,
- );
- return await fetchBitlyLink({ domain, key, workspaceId });
- }
-
- const destinationUrl = response.headers.get("location");
- if (!destinationUrl) {
- console.error(`[Bitly] No redirect URL found for ${domain}/${key}`);
- return null;
- }
-
- console.log(`[Bitly] Found link ${domain}/${key} -> ${destinationUrl}`);
-
- return {
- id: `${domain}/${key}`,
- long_url: destinationUrl,
- created_at: new Date().toISOString(),
- };
-}
-
-async function fetchBitlyLink({
- domain,
- key,
- workspaceId,
-}: {
- domain: string;
- key: string;
- workspaceId: string;
-}) {
- const apiKey = await redis.get<string>(`import:bitly:${workspaceId}`);
-
- if (!apiKey) {
- console.error(`[Bitly] No API key found for workspace ${workspaceId}`);
- return null;
- }
-
- const response = await fetch(
- `https://api-ssl.bitly.com/v4/bitlinks/${domain}/${key}`,
- {
- headers: {
- Authorization: `Bearer ${apiKey}`,
- },
- },
- );
-
- if (!response.ok) {
- console.log(
- `[Bitly] Hit rate limit, returning 404 for ${domain}/${key} for now...`,
- );
- return null;
- }
-
- return await response.json();
-}
diff --git a/apps/web/lib/middleware/bitly.ts b/apps/web/lib/middleware/bitly.ts
deleted file mode 100644
index 8c11bdbcba..0000000000
--- a/apps/web/lib/middleware/bitly.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { APP_DOMAIN } from "@dub/utils";
-import { EdgeLinkProps } from "../planetscale";
-
-// Create a new Bitly-hosted link to Dub on-demand (e.g. buff.ly)
-export const importBitlyLink = async ({
- domain,
- key,
-}: {
- domain: string;
- key: string;
-}) => {
- try {
- const result = await fetch(`${APP_DOMAIN}/api/links/crawl/bitly`, {
- method: "POST",
- body: JSON.stringify({ domain, key }),
- });
-
- if (result.status === 404) {
- return null;
- }
-
- return (await result.json()) as EdgeLinkProps;
- } catch (e) {
- console.error("[Bitly] Error crawling Bitly link", e);
- return null;
- }
-};
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index d20b50c9f0..9af6b9a5b6 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -26,7 +26,6 @@ import {
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,8 +74,10 @@ export default async function LinkMiddleware(
let linkData = await getLinkViaEdge(domain, key);
if (!linkData) {
- if (domain === "buff.ly" || domain === "dev.buff.ly") {
- linkData = await importBitlyLink({ domain, key: originalKey });
+ if (domain === "buff.ly") {
+ return NextResponse.redirect(
+ new URL(`/api/links/crawl/bitly/${domain}/${key}`, req.url),
+ );
}
if (!linkData) {