The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Added iOS & Android targeting, renamed customOG to proxy
Steven Teyb9eb49711026
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsxindex 730f836ba9..fefbc74fcf 100644--- a/components/app/links/link-card.tsx+++ b/components/app/links/link-card.tsx@@ -34,7 +34,7 @@ import {import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";export default function LinkCard({ props }: { props: LinkProps }) {- const { key, url, customOg, createdAt, archived, expiresAt } = props;+ const { key, url, proxy, createdAt, archived, expiresAt } = props;const apexDomain = getApexDomain(url);@@ -147,7 +147,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {<span className="ml-1 hidden sm:inline-block">clicks</span></p></Link>- {customOg && (+ {proxy && (<ahref={`https://${domain || "dub.sh"}/_proxy/${domain || "dub.sh"@@ -156,7 +156,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {rel="noreferrer"className="group rounded-full bg-gray-100 p-1.5 transition-all duration-75 hover:scale-105 hover:bg-blue-100 active:scale-95">- <Eye className="text-gray-700 transition-all group-hover:text-blue-800" />+ <Eye className="h-3 w-3 text-gray-700 transition-all group-hover:text-blue-800" /></a>)}</div>diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsxindex 52c6a36ff1..26ecbc7ed8 100644--- a/components/app/modals/add-edit-link-modal/index.tsx+++ b/components/app/modals/add-edit-link-modal/index.tsx@@ -6,7 +6,6 @@ import {useCallback,useEffect,useMemo,- useRef,useState,} from "react";import { mutate } from "swr";@@ -34,6 +33,7 @@ import ExpirationSection from "./expiration-section";import OGSection from "./og-section";import PasswordSection from "./password-section";import UTMSection from "./utm-section";+import IOSSection from "./ios-section";import Preview from "./preview";function AddEditLinkModal({@@ -68,15 +68,17 @@ function AddEditLinkModal({title: null,description: null,image: null,+ ios: null,+ android: null,clicks: 0,userId: "",createdAt: new Date(),- customOg: false,+ proxy: false,},);- const { key, url, password, customOg } = data;+ const { key, url, password, proxy } = data;const [debouncedKey] = useDebounce(key, 500);useEffect(() => {@@ -148,7 +150,7 @@ function AddEditLinkModal({**/if (showAddEditLinkModal &&- (!customOg || debouncedUrl !== getUrlWithoutUTMParams(props?.url))+ (!proxy || debouncedUrl !== getUrlWithoutUTMParams(props?.url))) {setData((prev) => ({...prev,@@ -173,7 +175,7 @@ function AddEditLinkModal({} else {setGeneratingMetatags(false);}- }, [debouncedUrl, password, showAddEditLinkModal, customOg]);+ }, [debouncedUrl, password, showAddEditLinkModal, proxy]);const logo = useMemo(() => {if (password || (!debouncedUrl && !props)) {@@ -449,6 +451,7 @@ function AddEditLinkModal({<UTMSection {...{ props, data, setData }} /><PasswordSection {...{ props, data, setData }} /><ExpirationSection {...{ props, data, setData }} />+ <IOSSection {...{ props, data, setData }} /></div><div className="sticky bottom-0 bg-gray-50 px-4 py-8 sm:px-16">diff --git a/components/app/modals/add-edit-link-modal/ios-section.tsx b/components/app/modals/add-edit-link-modal/ios-section.tsxnew file mode 100644index 0000000000..ed7731c358--- /dev/null+++ b/components/app/modals/add-edit-link-modal/ios-section.tsx@@ -0,0 +1,58 @@+import { Dispatch, SetStateAction, useEffect, useState } from "react";+import { LinkProps } from "@/lib/types";+import Switch from "@/components/shared/switch";+import { motion } from "framer-motion";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";++export default function IOSSection({+ props,+ data,+ setData,+}: {+ props: LinkProps;+ data: LinkProps;+ setData: Dispatch<SetStateAction<LinkProps>>;+}) {+ const { ios } = data;+ const [enabled, setEnabled] = useState(!!ios);+ useEffect(() => {+ if (enabled) {+ // if enabling, add previous ios link if exists+ setData({+ ...data,+ ios: props?.ios || ios,+ });+ } else {+ // if disabling, remove ios link+ setData({ ...data, ios: null });+ }+ }, [enabled]);++ return (+ <div className="border-b border-gray-200 pb-5">+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-gray-900">iOS Targeting</h2>+ <Switch fn={() => setEnabled(!enabled)} checked={enabled} />+ </div>+ {enabled && (+ <motion.div+ className="mt-3 flex rounded-md shadow-sm"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <input+ name="ios-url"+ id="ios-url"+ type="url"+ placeholder="https://apps.apple.com/app/1611158928"+ value={ios}+ onChange={(e) => {+ setData({ ...data, ios: e.target.value });+ }}+ className="block w-full rounded-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"+ aria-invalid="true"+ />+ </motion.div>+ )}+ </div>+ );+}diff --git a/components/app/modals/add-edit-link-modal/og-section.tsx b/components/app/modals/add-edit-link-modal/og-section.tsxindex 019ba065b0..35928dda8e 100644--- a/components/app/modals/add-edit-link-modal/og-section.tsx+++ b/components/app/modals/add-edit-link-modal/og-section.tsx@@ -24,7 +24,7 @@ export default function OGSection({setData: Dispatch<SetStateAction<LinkProps>>;generatingMetatags: boolean;}) {- const { title, description, image, customOg } = data;+ const { title, description, image, proxy } = data;const [fileSizeTooBig, setFileSizeTooBig] = useState(false);@@ -48,7 +48,7 @@ export default function OGSection({);useEffect(() => {- if (customOg && props) {+ if (proxy && props) {// if custom OG is enabledsetData((prev) => ({...prev,@@ -57,7 +57,7 @@ export default function OGSection({image: props.image || image,}));}- }, [customOg, props]);+ }, [proxy, props]);const randomIdx = Math.floor(Math.random() * 100);@@ -68,12 +68,12 @@ export default function OGSection({Custom Social Media Cards</h2><Switch- fn={() => setData((prev) => ({ ...prev, customOg: !customOg }))}- checked={customOg}+ fn={() => setData((prev) => ({ ...prev, proxy: !proxy }))}+ checked={proxy}/></div>- {customOg && (+ {proxy && (<motion.divkey="og-options"{...FADE_IN_ANIMATION_SETTINGS}@@ -136,12 +136,10 @@ export default function OGSection({</div><div>- <label- htmlFor={`title-${randomIdx}`}- className="block text-sm font-medium text-gray-700"- >- Title- </label>+ <div className="flex items-center justify-between">+ <p className="block text-sm font-medium text-gray-700">Title</p>+ <p className="text-sm text-gray-500">{title?.length || 0}/120</p>+ </div><div className="relative mt-1 flex rounded-md shadow-sm">{generatingMetatags && (<div className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white">@@ -165,12 +163,14 @@ export default function OGSection({</div><div>- <label- htmlFor={`description-${randomIdx}`}- className="block text-sm font-medium text-gray-700"- >- Description- </label>+ <div className="flex items-center justify-between">+ <p className="block text-sm font-medium text-gray-700">+ Description+ </p>+ <p className="text-sm text-gray-500">+ {description?.length || 0}/240+ </p>+ </div><div className="relative mt-1 flex rounded-md shadow-sm">{generatingMetatags && (<div className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white">@@ -181,15 +181,14 @@ export default function OGSection({name="description"id={`description-${randomIdx}`}minRows={3}- maxLength={280}+ maxLength={240}className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"placeholder="Dub is open-source link management tool for modern marketing teams to create, share, and track short links."value={description || ""}onChange={(e) => {setData({...data,- description:- e.target.value.length > 0 ? e.target.value : undefined,+ description: e.target.value,});}}aria-invalid="true"diff --git a/components/app/modals/add-edit-link-modal/password-section.tsx b/components/app/modals/add-edit-link-modal/password-section.tsxindex 045e113301..52e0547338 100644--- a/components/app/modals/add-edit-link-modal/password-section.tsx+++ b/components/app/modals/add-edit-link-modal/password-section.tsx@@ -3,6 +3,7 @@ import { LinkProps } from "@/lib/types";import Switch from "@/components/shared/switch";import { motion } from "framer-motion";import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";+import { Eye, EyeOff } from "@/components/shared/icons";export default function PasswordSection({props,@@ -27,6 +28,9 @@ export default function PasswordSection({setData({ ...data, password: null });}}, [enabled]);++ const [showPassword, setShowPassword] = useState(false);+return (<div className="border-b border-gray-200 pb-5"><div className="flex items-center justify-between">@@ -37,13 +41,13 @@ export default function PasswordSection({</div>{enabled && (<motion.div- className="mt-3 flex rounded-md shadow-sm"+ className="relative mt-3 rounded-md shadow-sm"{...FADE_IN_ANIMATION_SETTINGS}><inputname="password"id="password"- type="password"+ type={showPassword ? "text" : "password"}className="block w-full rounded-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"value={password || ""}placeholder="Enter password"@@ -52,6 +56,17 @@ export default function PasswordSection({}}aria-invalid="true"/>+ <button+ type="button"+ onClick={() => setShowPassword(!showPassword)}+ className="absolute inset-y-0 right-0 flex items-center pr-3"+ >+ {showPassword ? (+ <Eye className="h-4 w-4 text-gray-400" aria-hidden="true" />+ ) : (+ <EyeOff className="h-4 w-4 text-gray-400" aria-hidden="true" />+ )}+ </button></motion.div>)}</div>diff --git a/components/shared/icons/eye-off.tsx b/components/shared/icons/eye-off.tsxnew file mode 100644index 0000000000..f62b01ef76--- /dev/null+++ b/components/shared/icons/eye-off.tsx@@ -0,0 +1,19 @@+export default function EyeOff({ className }: { className: string }) {+ return (+ <svg+ fill="none"+ shapeRendering="geometricPrecision"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ viewBox="0 0 24 24"+ width="24"+ height="24"+ className={className}+ >+ <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24" />+ <path d="M1 1l22 22" />+ </svg>+ );+}diff --git a/components/shared/icons/eye.tsx b/components/shared/icons/eye.tsxindex bf420cf459..46cefa2e18 100644--- a/components/shared/icons/eye.tsx+++ b/components/shared/icons/eye.tsx@@ -8,12 +8,12 @@ export default function Eye({ className }: { className: string }) {strokeLinejoin="round"strokeWidth="1.5"viewBox="0 0 24 24"- width="14"- height="14"+ width="24"+ height="24"className={className}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />- <circle cx="12" cy="12" r="3" />{" "}+ <circle cx="12" cy="12" r="3" /></svg>);}diff --git a/components/shared/icons/index.tsx b/components/shared/icons/index.tsxindex ee5b24b0f8..144a2aa3bc 100644--- a/components/shared/icons/index.tsx+++ b/components/shared/icons/index.tsx@@ -47,6 +47,7 @@ export { default as Save } from "./save";export { default as Photo } from "./photo";export { default as Users } from "./users";export { default as Eye } from "./eye";+export { default as EyeOff } from "./eye-off";export { default as Heart } from "./heart";export { default as Repeat } from "./repeat";export { default as Message } from "./message";diff --git a/lib/api/links.ts b/lib/api/links.tsindex 5a638abfe9..794a3268a4 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -3,7 +3,7 @@ import { DEFAULT_REDIRECTS, RESERVED_KEYS } from "@/lib/constants";import prisma from "@/lib/prisma";import { LinkProps } from "@/lib/types";import { redis } from "@/lib/upstash";-import { getParamsFromURL, nanoid } from "@/lib/utils";+import { getParamsFromURL, nanoid, truncate } from "@/lib/utils";const getFiltersFromStatus = (status: string) => {if (status === "all" || status === "none") {@@ -126,7 +126,19 @@ export async function checkIfKeyExists(domain: string, key: string) {}export async function addLink(link: LinkProps) {- const { domain, key, url, expiresAt, password, image, customOg } = link;+ const {+ domain,+ key,+ url,+ expiresAt,+ password,+ title,+ description,+ image,+ proxy,+ ios,+ android,+ } = link;const hasPassword = password && password.length > 0 ? true : false;const exat = expiresAt ? new Date(expiresAt).getTime() / 1000 : null;const uploadedImage = image && image.startsWith("data:image") ? true : false;@@ -141,6 +153,8 @@ export async function addLink(link: LinkProps) {prisma.link.create({data: {...link,+ title: truncate(title, 120),+ description: truncate(description, 240),image: uploadedImage ? undefined : image,utm_source,utm_medium,@@ -154,7 +168,9 @@ export async function addLink(link: LinkProps) {{url,password: hasPassword,- proxy: customOg,+ proxy,+ ios,+ android,},{nx: true,@@ -163,7 +179,7 @@ export async function addLink(link: LinkProps) {},),]);- if (customOg && image) {+ if (proxy && image) {const { secure_url } = await cloudinary.v2.uploader.upload(image, {public_id: key,folder: domain,@@ -187,7 +203,20 @@ export async function editLink(oldKey: string,projectSlug: string,) {- const { id, domain, key, url, expiresAt, password, image, customOg } = link;+ const {+ id,+ domain,+ key,+ url,+ expiresAt,+ password,+ title,+ description,+ image,+ proxy,+ ios,+ android,+ } = link;const hasPassword = password && password.length > 0 ? true : false;const exat = expiresAt ? new Date(expiresAt).getTime() : null;const changedKey = key !== oldKey;@@ -207,6 +236,8 @@ export async function editLink(},data: {...link,+ title: truncate(title, 120),+ description: truncate(description, 240),image: uploadedImage ? undefined : image,utm_source,utm_medium,@@ -215,8 +246,8 @@ export async function editLink(utm_content,},}),- // only upload image to cloudinary if customOg is true and there's an image- customOg && image+ // only upload image to cloudinary if proxy is true and there's an image+ proxy && image? cloudinary.v2.uploader.upload(image, {public_id: key,folder: domain,@@ -231,7 +262,9 @@ export async function editLink({url,password: hasPassword,- proxy: customOg,+ proxy,+ ios,+ android,},{// if the key has an expiry, set exat@@ -253,13 +286,13 @@ export async function editLink(]: []),// if this link has custom OG tags and the key is the same, update the proxy cache- customOg &&+ proxy &&!changedKey &&(await fetch(`https://dub.sh/api/projects/${projectSlug}/domains/${domain}/links/${oldKey}/revalidate?secret=${process.env.REVALIDATE_TOKEN}`,)),]);- if (customOg && image) {+ if (proxy && image) {const { secure_url } = effects[0];response.image = secure_url;await prisma.link.update({diff --git a/lib/constants/index.ts b/lib/constants/index.tsindex 691c3370c9..be0186ac6b 100644--- a/lib/constants/index.ts+++ b/lib/constants/index.ts@@ -32,6 +32,7 @@ export const HOME_HOSTNAMES = new Set(["dub.sh","preview.dub.sh","localhost:3000",+ "c623-2600-1700-b5e4-b50-d083-66f5-64b2-e8bb.ngrok.io",]);export const RESERVED_KEYS = new Set([diff --git a/lib/middleware/link.ts b/lib/middleware/link.tsindex cc4d10df38..13514e373e 100644--- a/lib/middleware/link.ts+++ b/lib/middleware/link.ts@@ -1,4 +1,9 @@-import { NextFetchEvent, NextRequest, NextResponse } from "next/server";+import {+ NextFetchEvent,+ NextRequest,+ NextResponse,+ userAgent,+} from "next/server";import { detectBot, parse } from "@/lib/middleware/utils";import { recordClick, redis } from "@/lib/upstash";@@ -17,8 +22,10 @@ export default async function LinkMiddleware(url: string;password?: boolean;proxy?: boolean;+ ios?: string;+ android?: string;}>(`${domain}:${key}`);- const { url: target, password, proxy } = response || {};+ const { url: target, password, proxy, ios, android } = response || {};if (target) {// special case for link health monitoring with planetfall.io :)@@ -35,6 +42,12 @@ export default async function LinkMiddleware(if (isBot && proxy) {// rewrite to proxy page (/_proxy/[domain]/[key]) if it's a botreturn NextResponse.rewrite(new URL(`/_proxy/${domain}/${key}`, req.url));+ } else if (ios && userAgent(req).os?.name === "iOS") {+ // redirect to iOS link if it is specified and the user is on an iOS device+ return NextResponse.redirect(ios);+ } else if (android && userAgent(req).os?.name === "Android") {+ // redirect to Android link if it is specified and the user is on an Android device+ return NextResponse.redirect(android);} else {return NextResponse.redirect(target);}diff --git a/lib/types.ts b/lib/types.tsindex 823d51c939..cb3088caf3 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -12,11 +12,14 @@ export interface LinkProps {expiresAt: Date | null;password: string | null;- customOg: boolean;+ proxy: boolean;title: string | null;description: string | null;image: string | null;+ ios: string | null;+ android: string | null;+clicks: number;userId: string;diff --git a/lib/upstash.ts b/lib/upstash.tsindex 469e7bb300..94d3d508f7 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -2,7 +2,6 @@ import { NextRequest, userAgent } from "next/server";import { Ratelimit } from "@upstash/ratelimit";import { Redis } from "@upstash/redis";import { LOCALHOST_GEO_DATA } from "@/lib/constants";-import { LinkProps } from "@/lib/types";import { nanoid } from "@/lib/utils";// Initiate Redis instancediff --git a/prisma/schema.prisma b/prisma/schema.prismaindex fdca92ccf9..ac431525e3 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -134,9 +134,9 @@ model Link {expiresAt DateTime? // when the link expires – stored on Redis via ttlpassword String? // password to access the link – also stored on Redis- customOg Boolean @default(false) // Custom OG tags – if false, will use OG tags from target url- title String? // OG title for the link (e.g. Dub - Open-Source Bitly Alternative)- description String? // OG description for the link (e.g. An open-source link management tool for modern marketing teams to create, share, and track short links.)+ proxy Boolean @default(false) // Proxy to use custom OG tags – if false, will use OG tags from target url+ title String? @db.VarChar(120) // OG title for the link (e.g. Dub - Open-Source Bitly Alternative)+ description String? @db.VarChar(240) // OG description for the link (e.g. An open-source link management tool for modern marketing teams to create, share, and track short links.)image String? // OG image for the link (e.g. https://dub.sh/og-image.png)// UTM parameters@@ -145,6 +145,10 @@ model Link {utm_campaign String? // UTM campaign for the link (e.g. summer-sale)utm_term String? // UTM term for the link (e.g. dub)utm_content String? // UTM content for the link (e.g. description)++ // Custom device targeting+ ios String? @db.LongText // custom link for iOS devices+ android String? @db.LongText // custom link for Android devicesclicks Int @default(0) // number of clicks (updated every day via cron + real-time when user views links)clicksUpdatedAt DateTime @default(now()) // last time clicks was updated