The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Merge branch 'main' into clicks-migration
Steven Tey289328bbac7e
diff --cc apps/web/app/api/stats/[endpoint]/route.tsindex 1934d5eb76,901a327137..3d213934e4--- a/apps/web/app/api/stats/[endpoint]/route.ts+++ b/apps/web/app/api/stats/[endpoint]/route.ts@@@ -1,7 -1,5 +1,6 @@@import { withAuth } from "@/lib/auth";+import { getDomainViaEdge, getLinkViaEdge } from "@/lib/planetscale";import { getStats } from "@/lib/stats";- import { DUB_PROJECT_ID, isDubDomain } from "@dub/utils";import { NextResponse } from "next/server";// GET /api/stats/[endpoint] – get stats for a specific endpoint@@@ -18,18 -21,12 +17,18 @@@ export const GET = withAuthreturn new Response(`Require higher plan`, { status: 403 });}+ const linkId = link+ ? link.id+ : domain && key === "_root"+ ? await getDomainViaEdge(domain).then((d) => d?.id)+ : null;+const response = await getStats({projectId: project.id,++ ...(linkId && { linkId }),domain,- key,endpoint,interval,- ...(linkId && { linkId }),...searchParams,});return NextResponse.json(response);diff --cc apps/web/lib/middleware/link.tsindex 470df374b7,7ae830970c..d34d39a3bd--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@@ -60,115 -88,94 +88,103 @@@ export default async function LinkMiddlandroid,geo,projectId,- banned,- } = response || {};+ } = link;- if (url) {- // only show inspect modal if the link is not password protected- if (inspectMode && !password) {- return NextResponse.rewrite(- new URL(`/inspect/${domain}/${encodeURIComponent(key)}`, req.url),- );- }+ // only show inspect modal if the link is not password protected+ if (inspectMode && !password) {+ return NextResponse.rewrite(+ new URL(`/inspect/${domain}/${encodeURIComponent(key)}+`, req.url),+ );+ }- // if the link is password protected- if (password) {- const pw = req.nextUrl.searchParams.get("pw");-- // rewrite to auth page (/protected/[domain]/[key]) if:- // - no `pw` param is provided- // - the `pw` param is incorrect- // this will also ensure that no clicks are tracked unless the password is correct- if (!pw || (await getLinkViaEdge(domain, key))?.password !== pw) {- return NextResponse.rewrite(- new URL(`/protected/${domain}/${encodeURIComponent(key)}`, req.url),- );- } else if (pw) {- // strip it from the URL if it's correct- req.nextUrl.searchParams.delete("pw");- }- }+ // if the link is password protected+ if (password) {+ const pw = req.nextUrl.searchParams.get("pw");- // if the link is banned- if (banned) {+ // rewrite to auth page (/protected/[domain]/[key]) if:+ // - no `pw` param is provided+ // - the `pw` param is incorrect+ // this will also ensure that no clicks are tracked unless the password is correct+ if (!pw || (await getLinkViaEdge(domain, key))?.password !== pw) {return NextResponse.rewrite(- new URL(`/banned/${domain}/${encodeURIComponent(key)}`, req.url),+ new URL(`/protected/${domain}/${encodeURIComponent(key)}`, req.url),);+ } else if (pw) {+ // strip it from the URL if it's correct+ req.nextUrl.searchParams.delete("pw");}+ }- // if the link has expired- if (expiresAt && new Date(expiresAt) < new Date()) {- return NextResponse.rewrite(- new URL(`/expired/${domain}/${encodeURIComponent(key)}`, req.url),- );- }+ // if the link is banned+ if (link.projectId === LEGAL_PROJECT_ID) {+ return NextResponse.rewrite(new URL("/banned", req.url));+ }- const searchParams = req.nextUrl.searchParams;- // only track the click when:- // - the `dub-no-track` header is not set- // - the `__dub_no_track` query param is not set- if (- !(- req.headers.get("dub-no-track") ||- searchParams.get("__dub_no_track") === "1"- )- ) {- ev.waitUntil(- recordClick({- req,- domain,- key,- url: getFinalUrl(url, { req }),- id,- projectId,- }),- );- }+ // if the link has expired+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return NextResponse.rewrite(new URL("/expired", req.url));+ }- const isBot = detectBot(req);+ const searchParams = req.nextUrl.searchParams;+ // only track the click when there is no `dub-no-track` header or query param+ if (+ !(+ req.headers.get("dub-no-track") ||+ searchParams.get("dub-no-track") === "1"+ )+ ) {- ev.waitUntil(recordClick({ req, id, domain, key, projectId }));++ ev.waitUntil(++ recordClick({++ req,++ id,++ domain,++ key,++ url: getFinalUrl(url, { req }),++ projectId,++ }),++ );+ }- const { country } =- process.env.VERCEL === "1" && req.geo ? req.geo : LOCALHOST_GEO_DATA;+ const isBot = detectBot(req);- // rewrite to proxy page (/_proxy/[domain]/[key]) if it's a bot and proxy is enabled- if (isBot && proxy) {- return NextResponse.rewrite(- new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),- );+ const { country } =+ process.env.VERCEL === "1" && req.geo ? req.geo : LOCALHOST_GEO_DATA;- // rewrite to destination URL if link cloaking is enabled- } else if (rewrite) {- if (iframeable) {- return NextResponse.rewrite(- new URL(`/rewrite/${url}`, req.url),- DUB_HEADERS,- );- } else {- // if link is not iframeable, use Next.js rewrite instead- return NextResponse.rewrite(decodeURIComponent(url), DUB_HEADERS);- }-- // redirect to iOS link if it is specified and the user is on an iOS device- } else if (ios && userAgent(req).os?.name === "iOS") {- return NextResponse.redirect(getFinalUrl(ios, { req }), DUB_HEADERS);-- // redirect to Android link if it is specified and the user is on an Android device- } else if (android && userAgent(req).os?.name === "Android") {- return NextResponse.redirect(getFinalUrl(android, { req }), DUB_HEADERS);-- // redirect to geo-specific link if it is specified and the user is in the specified country- } else if (geo && country && country in geo) {- return NextResponse.redirect(- getFinalUrl(geo[country], { req }),+ // rewrite to proxy page (/proxy/[domain]/[key]) if it's a bot and proxy is enabled+ if (isBot && proxy) {+ return NextResponse.rewrite(+ new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),+ );++ // rewrite to target URL if link cloaking is enabled+ } else if (rewrite) {+ if (iframeable) {+ return NextResponse.rewrite(+ new URL(`/rewrite/${encodeURIComponent(url)}`, req.url),DUB_HEADERS,);-- // regular redirect} else {- return NextResponse.redirect(getFinalUrl(url, { req }), DUB_HEADERS);+ // if link is not iframeable, use Next.js rewrite instead+ return NextResponse.rewrite(url, DUB_HEADERS);}++ // redirect to iOS link if it is specified and the user is on an iOS device+ } else if (ios && userAgent(req).os?.name === "iOS") {+ return NextResponse.redirect(getFinalUrl(ios, { req }), DUB_HEADERS);++ // redirect to Android link if it is specified and the user is on an Android device+ } else if (android && userAgent(req).os?.name === "Android") {+ return NextResponse.redirect(getFinalUrl(android, { req }), DUB_HEADERS);++ // redirect to geo-specific link if it is specified and the user is in the specified country+ } else if (geo && country && country in geo) {+ return NextResponse.redirect(+ getFinalUrl(geo[country], { req }),+ DUB_HEADERS,+ );++ // regular redirect} else {- // short link not found, redirect to root- return NextResponse.redirect(new URL("/", req.url), DUB_HEADERS);+ return NextResponse.redirect(getFinalUrl(url, { req }), DUB_HEADERS);}}diff --cc apps/web/lib/middleware/root.tsindex cc1c57fede,30e72ac322..6081390078--- a/apps/web/lib/middleware/root.ts+++ b/apps/web/lib/middleware/root.ts@@@ -45,26 -36,27 +36,29 @@@ export default async function RootMiddl);}- if (target) {- if (rewrite) {- if (iframeable) {- // note: there's a discrepancy between the implementation here and for- // link rewriting in `lib/api/links` – here we do `encodeURIComponent` but for links we- // don't need to. This is because link targets are already encoded, while root targets- // are not. TODO: standardize this in the future.- return NextResponse.rewrite(- new URL(`/rewrite/${encodeURIComponent(target)}`, req.url),- DUB_HEADERS,- );- } else {- // if link is not iframeable, use Next.js rewrite instead- return NextResponse.rewrite(target, DUB_HEADERS);- }+ const { id, url, rewrite, iframeable, projectId } = link;++ // record clicks on root page- ev.waitUntil(recordClick({ req, id, domain, projectId }));++ ev.waitUntil(++ recordClick({ req, id, domain, ...(url && { url }), projectId }),++ );++ if (!url) {+ // rewrite to placeholder page unless the user defines a site to redirect to+ return NextResponse.rewrite(new URL(`/${domain}`, req.url));+ }++ if (rewrite) {+ if (iframeable) {+ return NextResponse.rewrite(+ new URL(`/rewrite/${encodeURIComponent(url)}`, req.url),+ DUB_HEADERS,+ );} else {- return NextResponse.redirect(target, DUB_HEADERS);+ // if link is not iframeable, use Next.js rewrite instead+ return NextResponse.rewrite(url, DUB_HEADERS);}} else {- // rewrite to root page unless the user defines a site to redirect to- return NextResponse.rewrite(new URL(`/${domain}`, req.url));+ return NextResponse.redirect(url, DUB_HEADERS);}}diff --cc apps/web/lib/tinybird.tsindex 53e10a5e99,e455ec0822..bd218d4f84--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@@ -16,17 -16,15 +16,17 @@@ import { detectBot } from "./middleware**/export async function recordClick({req,+ id,domain,key,+ url,- id,projectId,}: {req: NextRequest;- id?: string;++ id: string;domain: string;key?: string;+ url?: string;- id?: string;projectId?: string;}) {const isBot = detectBot(req);@@@ -37,33 -35,15 +37,17 @@@const ua = userAgent(req);const referer = req.headers.get("referer");const ip = ipAddress(req) || LOCALHOST_IP;- // deduplicate clicks from the same IP, domain and key – only record 1 click per hour- const { success } = await ratelimit(2, "1 h").limit(- `recordClick:${ip}:${domain.toLowerCase()}:${- key?.toLowerCase() || "_root"- }`,- );- if (!success) {- return null;+ // if in production / preview env, deduplicate clicks from the same IP, domain and key – only record 1 click per hour+ if (process.env.VERCEL === "1") {+ const { success } = await ratelimit(2, "1 h").limit(+ `recordClick:${ip}:${domain.toLowerCase()}:${+ key?.toLowerCase() || "_root"+ }`,+ );+ if (!success) {+ return null;+ }}- let updateRedis = false;-- if (id || !projectId) {- if (key) {- const linkData = await getLinkViaEdge(domain, key);- id = linkData?.id;- projectId = linkData?.projectId || undefined;- } else {- const domainData = await getDomainViaEdge(domain);- id = domainData?.id;- projectId = domainData?.projectId || undefined;- }- updateRedis = true;- }-- console.log({ id, projectId, domain, key, url });return await Promise.allSettled([fetch(diff --cc apps/web/lib/types.tsindex 8f9bcab887,2287375900..84860c7b97--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@@ -25,25 -25,8 +25,24 @@@ export interface RedisLinkPropsandroid?: string;geo?: object;projectId?: string;- banned?: boolean;}+export interface EdgeLinkProps {+ id: string;+ domain: string;+ key: string;+ url: string;+ proxy: boolean;+ title: string;+ description: string;+ image: string;+ password: string;+ clicks: number;+ publicStats: boolean;+ userId: string;+ projectId: string;+}+export interface TagProps {id: string;name: string;diff --cc apps/web/ui/links/link-card.tsxindex eda198a411,fc30d4e063..e8d6e817bf--- a/apps/web/ui/links/link-card.tsx+++ b/apps/web/ui/links/link-card.tsx@@@ -43,10 -43,11 +43,11 @@@ import} from "lucide-react";import Link from "next/link";import { useParams } from "next/navigation";-import Linkify from "linkify-react";import punycode from "punycode/";import { useEffect, useMemo, useRef, useState } from "react";- import useSWR from "swr";+ import useSWR, { mutate } from "swr";+ import { toast } from "sonner";+import { LinkifyTooltipContent } from "@dub/ui/src/tooltip";export default function LinkCard({props,diff --cc packages/utils/src/constants/index.tsindex 34a1ca09c7,36b810c8a9..ec7af8ef39--- a/packages/utils/src/constants/index.ts+++ b/packages/utils/src/constants/index.ts@@@ -109,6 -109,10 +109,11 @@@ export const DUB_LOGO = "https://d2vwwcexport const DUB_THUMBNAIL ="https://d2vwwcvoksz7ty.cloudfront.net/thumbnail.png";++export const DEMO_LINK_ID = "clqo10sum0006js08vutzfxt3";+ export const DUB_PROJECT_ID = "cl7pj5kq4006835rbjlt2ofka";+ export const LEGAL_PROJECT_ID = "clrflia0j0000vs7sqfhz9c7q";+ export const LEGAL_USER_ID = "clqei1lgc0000vsnzi01pbf47";+export const HIDE_BACKGROUND_SEGMENTS = ["stats","changelog",diff --cc pnpm-lock.yamlindex 9aab28539d,20373b7fdd..2ff882db5d--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@@ -18246,9 -18248,20 +18246,9 @@@ packagesschema-utils: 3.3.0serialize-javascript: 6.0.2terser: 5.27.0- webpack: 5.89.0(@swc/[email protected])([email protected])+ webpack: 5.90.0(@swc/[email protected])([email protected])dev: false- resolution: {integrity: sha512-WtnFKrxu9kaoXuiZFSGrcAvvBqAdmKx0SFNmVNYdJamMu9yyN3I/QF0FbH4QcqJQ+y1CJnzxGIKH0cSj+FGYRw==}- engines: {node: '>=10'}- hasBin: true- dependencies:- '@jridgewell/source-map': 0.3.5- acorn: 8.10.0- commander: 2.20.3- source-map-support: 0.5.21- dev: false-resolution: {integrity: sha512-bi1HRwVRskAjheeYl291n3JC4GgO/Ty4z1nVs5AAsmonJulGxpSektecnNedrwK9C7vpvVtcX3cw00VSLt7U2A==}engines: {node: '>=10'}