The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add support for QR Analytics
Steven Tey2d1a2f27861f
diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.tsindex 0b3e5423e7..e46739d145 100644--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts@@ -4,7 +4,7 @@ import {exceededLimitError,handleAndReturnErrorResponse,} from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { getDomainOrLink, getWorkspaceViaEdge } from "@/lib/planetscale";import { ratelimit } from "@/lib/upstash";import {diff --git a/apps/web/app/api/auth/account-exists/route.ts b/apps/web/app/api/auth/account-exists/route.tsindex fb6d3a8234..3a86387676 100644--- a/apps/web/app/api/auth/account-exists/route.ts+++ b/apps/web/app/api/auth/account-exists/route.ts@@ -1,5 +1,5 @@-import { getIdentityHash } from "@/lib/edge";import { isWhitelistedEmail } from "@/lib/edge-config";+import { getIdentityHash } from "@/lib/middleware/utils";import { DATABASE_URL, conn } from "@/lib/planetscale";import { ratelimit } from "@/lib/upstash";import { NextRequest, NextResponse } from "next/server";diff --git a/apps/web/app/api/links/iframeable/route.ts b/apps/web/app/api/links/iframeable/route.tsindex 24bba85a1d..73b3085434 100644--- a/apps/web/app/api/links/iframeable/route.ts+++ b/apps/web/app/api/links/iframeable/route.ts@@ -1,5 +1,5 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { getDomainQuerySchema, getUrlQuerySchema } from "@/lib/zod/schemas";import { isIframeable } from "@dub/utils";diff --git a/apps/web/app/api/links/random/route.ts b/apps/web/app/api/links/random/route.tsindex 15e24b76ee..e7400a8a28 100644--- a/apps/web/app/api/links/random/route.ts+++ b/apps/web/app/api/links/random/route.ts@@ -1,5 +1,5 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { getRandomKey } from "@/lib/planetscale";import { ratelimit } from "@/lib/upstash";import { domainKeySchema } from "@/lib/zod/schemas";diff --git a/apps/web/app/api/metatags/route.ts b/apps/web/app/api/metatags/route.tsindex e92bd7ffb4..1096583d7f 100644--- a/apps/web/app/api/metatags/route.ts+++ b/apps/web/app/api/metatags/route.ts@@ -1,5 +1,5 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { getUrlQuerySchema } from "@/lib/zod/schemas";import { getToken } from "next-auth/jwt";diff --git a/apps/web/app/api/providers/route.ts b/apps/web/app/api/providers/route.tsindex e2d33ac1ef..863c9edd87 100644--- a/apps/web/app/api/providers/route.ts+++ b/apps/web/app/api/providers/route.ts@@ -1,5 +1,5 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { getUrlQuerySchema } from "@/lib/zod/schemas";import { fetchWithTimeout } from "@dub/utils";diff --git a/apps/web/app/api/qr/route.tsx b/apps/web/app/api/qr/route.tsxindex 326b6f97ab..139de74abf 100644--- a/apps/web/app/api/qr/route.tsx+++ b/apps/web/app/api/qr/route.tsx@@ -1,5 +1,5 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { QRCodeSVG } from "@/lib/qr/utils";import { ratelimit } from "@/lib/upstash";import { getQRCodeQuerySchema } from "@/lib/zod/schemas";diff --git a/apps/web/app/api/unsplash/search/route.ts b/apps/web/app/api/unsplash/search/route.tsindex cdab93ada2..21fe87cf5e 100644--- a/apps/web/app/api/unsplash/search/route.ts+++ b/apps/web/app/api/unsplash/search/route.ts@@ -1,4 +1,4 @@-import { getIdentityHash } from "@/lib/edge";+import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { NextResponse } from "next/server";import { unsplash } from "../utils";diff --git a/apps/web/lib/api/links/utils.ts b/apps/web/lib/api/links/utils.tsindex 75726cc5ff..c18bc9b120 100644--- a/apps/web/lib/api/links/utils.ts+++ b/apps/web/lib/api/links/utils.ts@@ -136,12 +136,20 @@ export const transformLink = (link: LinkWithTags) => {key: link.key,});+ const qrLink = linkConstructor({+ domain: link.domain,+ key: link.key,+ searchParams: {+ qr: "1",+ },+ });+return {...link,shortLink,tagId: tags?.[0]?.id ?? null, // backwards compatibilitytags,- qrCode: `https://api.dub.co/qr?url=${shortLink}`,+ qrCode: `https://api.dub.co/qr?url=${qrLink}`,workspaceId: `ws_${link.projectId}`,};};diff --git a/apps/web/lib/middleware/utils.ts b/apps/web/lib/middleware/utils.tsdeleted file mode 100644index 554caeefa6..0000000000--- a/apps/web/lib/middleware/utils.ts+++ /dev/null@@ -1,68 +0,0 @@-import { SHORT_DOMAIN } from "@dub/utils";-import { NextRequest } from "next/server";--export const parse = (req: NextRequest) => {- let domain = req.headers.get("host") as string;- // remove www. from domain and convert to lowercase- domain = domain.replace("www.", "").toLowerCase();- if (domain === "dub.localhost:8888" || domain.endsWith(".vercel.app")) {- // for local development and preview URLs- domain = SHORT_DOMAIN;- }-- // path is the path of the URL (e.g. dub.co/stats/github -> /stats/github)- let path = req.nextUrl.pathname;-- // fullPath is the full URL path (along with search params)- const searchParams = req.nextUrl.searchParams.toString();- const fullPath = `${path}${- searchParams.length > 0 ? `?${searchParams}` : ""- }`;-- // Here, we are using decodeURIComponent to handle foreign languages like Hebrew- const key = decodeURIComponent(path.split("/")[1]); // key is the first part of the path (e.g. dub.co/stats/github -> stats)- const fullKey = decodeURIComponent(path.slice(1)); // fullKey is the full path without the first slash (to account for multi-level subpaths, e.g. d.to/github/repo -> github/repo)-- return { domain, path, fullPath, key, fullKey };-};--export const getFinalUrl = (url: string, { req }: { req: NextRequest }) => {- // query is the query string (e.g. d.to/github?utm_source=twitter -> ?utm_source=twitter)- const searchParams = req.nextUrl.searchParams;-- // get the query params of the target url- const urlObj = new URL(url);-- // if there are no query params, then return the target url as is (no need to parse it)- // @ts-ignore – until https://github.com/microsoft/TypeScript/issues/54466 is fixed- if (searchParams.size === 0) return url;-- // if searchParams (type: `URLSearchParams`) has the same key as target url, then overwrite it- for (const [key, value] of searchParams) {- urlObj.searchParams.set(key, value);- }-- // construct final url- const finalUrl = urlObj.toString();-- return finalUrl;-};--export const detectBot = (req: NextRequest) => {- const url = req.nextUrl;- if (url.searchParams.get("bot")) return true;- const ua = req.headers.get("User-Agent");- if (ua) {- /* Note:- * - bot is for most bots & crawlers- * - ChatGPT is for ChatGPT- * - facebookexternalhit is for Facebook crawler- * - WhatsApp is for WhatsApp crawler- * - MetaInspector is for https://metatags.io/- */- return /bot|chatgpt|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector/i.test(- ua,- );- }- return false;-};diff --git a/apps/web/lib/middleware/utils/detect-bot.ts b/apps/web/lib/middleware/utils/detect-bot.tsnew file mode 100644index 0000000000..2fa191c16a--- /dev/null+++ b/apps/web/lib/middleware/utils/detect-bot.ts@@ -0,0 +1,20 @@+import { NextRequest } from "next/server";++export const detectBot = (req: NextRequest) => {+ const url = req.nextUrl;+ if (url.searchParams.get("bot")) return true;+ const ua = req.headers.get("User-Agent");+ if (ua) {+ /* Note:+ * - bot is for most bots & crawlers+ * - ChatGPT is for ChatGPT+ * - facebookexternalhit is for Facebook crawler+ * - WhatsApp is for WhatsApp crawler+ * - MetaInspector is for https://metatags.io/+ */+ return /bot|chatgpt|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector/i.test(+ ua,+ );+ }+ return false;+};diff --git a/apps/web/lib/middleware/utils/detect-qr.ts b/apps/web/lib/middleware/utils/detect-qr.tsnew file mode 100644index 0000000000..b709982305--- /dev/null+++ b/apps/web/lib/middleware/utils/detect-qr.ts@@ -0,0 +1,7 @@+import { NextRequest } from "next/server";++export const detectQr = (req: NextRequest) => {+ const url = req.nextUrl;+ if (url.searchParams.get("qr") === "1") return true;+ return false;+};diff --git a/apps/web/lib/middleware/utils/get-final-url.ts b/apps/web/lib/middleware/utils/get-final-url.tsnew file mode 100644index 0000000000..c3fcf92177--- /dev/null+++ b/apps/web/lib/middleware/utils/get-final-url.ts@@ -0,0 +1,28 @@+import { NextRequest } from "next/server";++export const getFinalUrl = (url: string, { req }: { req: NextRequest }) => {+ // query is the query string (e.g. d.to/github?utm_source=twitter -> ?utm_source=twitter)+ const searchParams = req.nextUrl.searchParams;++ // get the query params of the target url+ const urlObj = new URL(url);++ // if there are no query params, then return the target url as is (no need to parse it)+ // @ts-ignore – until https://github.com/microsoft/TypeScript/issues/54466 is fixed+ if (searchParams.size === 0) return url;++ // if searchParams (type: `URLSearchParams`) has the same key as target url, then overwrite it+ for (const [key, value] of searchParams) {+ urlObj.searchParams.set(key, value);+ }++ if (urlObj.searchParams.get("qr") === "1") {+ // remove qr param from the final url (only used for detectQr function)+ urlObj.searchParams.delete("qr");+ }++ // construct final url+ const finalUrl = urlObj.toString();++ return finalUrl;+};diff --git a/apps/web/lib/edge.ts b/apps/web/lib/middleware/utils/get-identity-hash.tssimilarity index 100%rename from apps/web/lib/edge.tsrename to apps/web/lib/middleware/utils/get-identity-hash.tsdiff --git a/apps/web/lib/middleware/utils/index.ts b/apps/web/lib/middleware/utils/index.tsnew file mode 100644index 0000000000..407c04f109--- /dev/null+++ b/apps/web/lib/middleware/utils/index.ts@@ -0,0 +1,5 @@+export * from "./detect-bot";+export * from "./detect-qr";+export * from "./get-final-url";+export * from "./get-identity-hash";+export * from "./parse";diff --git a/apps/web/lib/middleware/utils/parse.ts b/apps/web/lib/middleware/utils/parse.tsnew file mode 100644index 0000000000..cc68b7f950--- /dev/null+++ b/apps/web/lib/middleware/utils/parse.ts@@ -0,0 +1,27 @@+import { SHORT_DOMAIN } from "@dub/utils";+import { NextRequest } from "next/server";++export const parse = (req: NextRequest) => {+ let domain = req.headers.get("host") as string;+ // remove www. from domain and convert to lowercase+ domain = domain.replace("www.", "").toLowerCase();+ if (domain === "dub.localhost:8888" || domain.endsWith(".vercel.app")) {+ // for local development and preview URLs+ domain = SHORT_DOMAIN;+ }++ // path is the path of the URL (e.g. dub.co/stats/github -> /stats/github)+ let path = req.nextUrl.pathname;++ // fullPath is the full URL path (along with search params)+ const searchParams = req.nextUrl.searchParams.toString();+ const fullPath = `${path}${+ searchParams.length > 0 ? `?${searchParams}` : ""+ }`;++ // Here, we are using decodeURIComponent to handle foreign languages like Hebrew+ const key = decodeURIComponent(path.split("/")[1]); // key is the first part of the path (e.g. dub.co/stats/github -> stats)+ const fullKey = decodeURIComponent(path.slice(1)); // fullKey is the full path without the first slash (to account for multi-level subpaths, e.g. d.to/github/repo -> github/repo)++ return { domain, path, fullPath, key, fullKey };+};diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.tsindex ee911b2b63..9ca809a5ac 100644--- a/apps/web/lib/planetscale.ts+++ b/apps/web/lib/planetscale.ts@@ -1,4 +1,4 @@-import { nanoid } from "@dub/utils";+import { nanoid, punyEncode } from "@dub/utils";import { connect } from "@planetscale/database";import { DomainProps, WorkspaceProps } from "./types";@@ -53,7 +53,7 @@ export const getLinkViaEdge = async (domain: string, key: string) => {const { rows } =(await conn.execute("SELECT * FROM Link WHERE domain = ? AND `key` = ?",- [domain, decodeURIComponent(key)], // we need to make sure that the key is always decoded (cause that's how we store it in MySQL)+ [domain, punyEncode(decodeURIComponent(key))], // we need to make sure that the key is always URI-decoded + punycode-encoded (cause that's how we store it in MySQL))) || {};return rows && Array.isArray(rows) && rows.length > 0diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.tsindex 85815bafb9..7f6233228f 100644--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@ -8,8 +8,7 @@ import {} from "@dub/utils";import { ipAddress } from "@vercel/edge";import { NextRequest, userAgent } from "next/server";-import { getIdentityHash } from "./edge";-import { detectBot } from "./middleware/utils";+import { detectBot, detectQr, getIdentityHash } from "./middleware/utils";import { conn } from "./planetscale";import { LinkProps } from "./types";import { ratelimit } from "./upstash";@@ -30,8 +29,9 @@ export async function recordClick({}) {const isBot = detectBot(req);if (isBot) {- return null;+ return null; // don't record clicks from bots}+ const isQr = detectQr(req);const geo = process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA;const ua = userAgent(req);const referer = req.headers.get("referer");@@ -87,6 +87,7 @@ export async function recordClick({cpu_architecture: ua.cpu?.architecture || "Unknown",ua: ua.ua || "Unknown",bot: ua.isBot,+ qr: isQr,referer: referer? getDomainWithoutWWW(referer) || "(direct)": "(direct)",diff --git a/apps/web/ui/modals/link-qr-modal.tsx b/apps/web/ui/modals/link-qr-modal.tsxindex f1c1d74494..7b8c3cc606 100644--- a/apps/web/ui/modals/link-qr-modal.tsx+++ b/apps/web/ui/modals/link-qr-modal.tsx@@ -80,6 +80,9 @@ export function QRCodePicker({value: linkConstructor({key: props.key,domain: props.domain,+ searchParams: {+ qr: "1",+ },}),bgColor: "#ffffff",fgColor,@@ -190,6 +193,9 @@ export function QRCodePicker({`https://api.dub.co/qr?url=${linkConstructor({key: props.key,domain: props.domain,+ searchParams: {+ qr: "1",+ },})}`,);toast.success("Copied QR code URL to clipboard!");diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex ff88ca5827..e8f500b002 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -1,7 +1,7 @@{"name": "@dub/utils","description": "Utility functions and constants for Dub.co",- "version": "0.0.47",+ "version": "0.0.48","sideEffects": false,"main": "./dist/index.mjs","module": "./dist/index.mjs",diff --git a/packages/utils/src/functions/link-constructor.ts b/packages/utils/src/functions/link-constructor.tsindex 5f40ff173c..5c950dfac8 100644--- a/packages/utils/src/functions/link-constructor.ts+++ b/packages/utils/src/functions/link-constructor.ts@@ -1,22 +1,29 @@import { punycode } from ".";export function linkConstructor({- domain = "dub.sh",+ domain,key,- localhost,pretty,- noDomain,+ searchParams,}: {domain?: string;key?: string;- localhost?: boolean;pretty?: boolean;- noDomain?: boolean;+ searchParams?: Record<string, string>;}) {- const link = `${- localhost ? "http://home.localhost:8888" : `https://${punycode(domain)}`- }${key && key !== "_root" ? `/${punycode(key)}` : ""}`;+ if (!domain) {+ return "";+ }- if (noDomain) return `/${punycode(key)}`;- return pretty ? link.replace(/^https?:\/\//, "") : link;+ let url = `https://${punycode(domain)}${key && key !== "_root" ? `/${punycode(key)}` : ""}`;++ if (searchParams) {+ const search = new URLSearchParams();+ for (const [key, value] of Object.entries(searchParams)) {+ search.set(key, value);+ }+ url += `?${search.toString()}`;+ }++ return pretty ? url.replace(/^https?:\/\//, "") : url;}