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.

added `customOG` attribute in database (boolean)

Steven Teyc665e814b152
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index baef75adbf..730f836ba9 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -34,16 +34,7 @@ import {
import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
export default function LinkCard({ props }: { props: LinkProps }) {
- const {
- key,
- url,
- title,
- description,
- image,
- createdAt,
- archived,
- expiresAt,
- } = props;
+ const { key, url, customOg, createdAt, archived, expiresAt } = props;
const apexDomain = getApexDomain(url);
@@ -156,7 +147,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<span className="ml-1 hidden sm:inline-block">clicks</span>
</p>
</Link>
- {title && description && image && (
+ {customOg && (
<a
href={`https://${domain || "dub.sh"}/_proxy/${
domain || "dub.sh"
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 50f6a35e48..f4ae2fc4c5 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -24,7 +24,12 @@ import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
import useUsage from "@/lib/swr/use-usage";
import { LinkProps } from "@/lib/types";
-import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";
+import {
+ getApexDomain,
+ getQueryString,
+ getUrlWithoutUTMParams,
+ linkConstructor,
+} from "@/lib/utils";
import ExpirationSection from "./expiration-section";
import OGSection from "./og-section";
import PasswordSection from "./password-section";
@@ -52,32 +57,26 @@ function AddEditLinkModal({
const [saving, setSaving] = useState(false);
const [data, setData] = useState<LinkProps>(
- props
- ? {
- ...props,
- ogEnabled:
- props.title && props.description && props.image ? true : false,
- }
- : {
- domain: domain || "",
- key: "",
- url: "",
- archived: false,
- expiresAt: null,
- password: null,
+ props || {
+ domain: domain || "",
+ key: "",
+ url: "",
+ archived: false,
+ expiresAt: null,
+ password: null,
- title: null,
- description: null,
- image: null,
+ title: null,
+ description: null,
+ image: null,
- clicks: 0,
- userId: "",
- createdAt: new Date(),
+ clicks: 0,
+ userId: "",
+ createdAt: new Date(),
- ogEnabled: false,
- },
+ customOg: false,
+ },
);
- const { key, url, password, ogEnabled } = data;
+ const { key, url, password, customOg } = data;
const [debouncedKey] = useDebounce(key, 500);
useEffect(() => {
@@ -129,7 +128,7 @@ function AddEditLinkModal({
// }, [onPaste]);
const [generatingMetatags, setGeneratingMetatags] = useState(false);
- const [debouncedUrl] = useDebounce(url.split("?")[0], 500);
+ const [debouncedUrl] = useDebounce(getUrlWithoutUTMParams(url), 500);
useEffect(() => {
// if there's a password, no need to generate metatags
if (password) {
@@ -145,18 +144,18 @@ function AddEditLinkModal({
/**
* Only generate metatags if:
* - modal is open
- * - there's no image or the url has changed
+ * - custom OG is not enabled or the url has changed
**/
- if (showAddEditLinkModal && !ogEnabled) {
- // using a setTimeout to delay until the loading screen fades in (0.2 delay in framer motion as well)
- setTimeout(() => {
- setData((prev) => ({
- ...prev,
- title: null,
- description: null,
- image: null,
- }));
- }, 200);
+ if (
+ showAddEditLinkModal &&
+ (!customOg || debouncedUrl !== getUrlWithoutUTMParams(props?.url))
+ ) {
+ setData((prev) => ({
+ ...prev,
+ title: null,
+ description: null,
+ image: null,
+ }));
try {
// if url is valid, continue to generate metatags, else return null
new URL(debouncedUrl);
@@ -171,8 +170,10 @@ function AddEditLinkModal({
} catch (e) {
console.log("not a valid url");
}
+ } else {
+ setGeneratingMetatags(false);
}
- }, [props, debouncedUrl, password]);
+ }, [debouncedUrl, password, showAddEditLinkModal, customOg]);
const logo = useMemo(() => {
if (password || (!debouncedUrl && !props)) {
@@ -227,7 +228,7 @@ function AddEditLinkModal({
keyExistsError ||
urlError ||
(props &&
- Object.entries(props).every(([key, value]) => value === data[key]))
+ Object.entries(props).every(([key, value]) => data[key] === value))
) {
return true;
} else {
@@ -284,18 +285,12 @@ function AddEditLinkModal({
onSubmit={async (e) => {
e.preventDefault();
setSaving(true);
- const { ogEnabled, ...rest } = data;
fetch(endpoint.url, {
method: endpoint.method,
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({
- ...rest,
- title: ogEnabled ? rest.title : null,
- description: ogEnabled ? rest.description : null,
- image: ogEnabled ? rest.image : null,
- }),
+ body: JSON.stringify(data),
}).then((res) => {
setSaving(false);
if (res.status === 200) {
@@ -448,7 +443,7 @@ function AddEditLinkModal({
<div className="grid gap-5 px-4 sm:px-16">
<OGSection
- {...{ data, setData }}
+ {...{ props, data, setData }}
generatingMetatags={generatingMetatags}
/>
<UTMSection {...{ props, data, setData }} />
diff --git a/components/app/modals/add-edit-link-modal/og-section.tsx b/components/app/modals/add-edit-link-modal/og-section.tsx
index b3b20ef87e..6db22eda98 100644
--- a/components/app/modals/add-edit-link-modal/og-section.tsx
+++ b/components/app/modals/add-edit-link-modal/og-section.tsx
@@ -1,4 +1,10 @@
-import { Dispatch, SetStateAction, useCallback, useState } from "react";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useState,
+} from "react";
import { motion } from "framer-motion";
import TextareaAutosize from "react-textarea-autosize";
import BlurImage from "@/components/shared/blur-image";
@@ -8,15 +14,17 @@ import Switch from "@/components/shared/switch";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
export default function OGSection({
+ props,
data,
setData,
generatingMetatags,
}: {
+ props: LinkProps;
data: LinkProps;
setData: Dispatch<SetStateAction<LinkProps>>;
generatingMetatags: boolean;
}) {
- const { title, description, image, ogEnabled } = data;
+ const { title, description, image, customOg } = data;
const [fileSizeTooBig, setFileSizeTooBig] = useState(false);
@@ -39,6 +47,18 @@ export default function OGSection({
[setData],
);
+ useEffect(() => {
+ if (customOg && props) {
+ // if custom OG is enabled
+ setData((prev) => ({
+ ...prev,
+ title: props.title || title,
+ description: props.description || description,
+ image: props.image || image,
+ }));
+ }
+ }, [customOg, props]);
+
const randomIdx = Math.floor(Math.random() * 100);
return (
@@ -48,8 +68,8 @@ export default function OGSection({
Custom Social Media Cards
</h2>
<Switch
- fn={() => setData((prev) => ({ ...prev, ogEnabled: !ogEnabled }))}
- checked={ogEnabled}
+ fn={() => setData((prev) => ({ ...prev, customOg: !customOg }))}
+ checked={customOg}
/>
</div>
{/* <p className="mt-2 block text-sm text-gray-500">
@@ -60,7 +80,7 @@ export default function OGSection({
, or the default OG tags of the target URL will be used.
</p> */}
- {ogEnabled && (
+ {customOg && (
<motion.div
key="og-options"
{...FADE_IN_ANIMATION_SETTINGS}
@@ -80,12 +100,9 @@ export default function OGSection({
className="group relative mt-1 flex h-[14rem] cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"
>
{generatingMetatags && (
- <motion.div
- className="absolute flex h-full w-full items-center justify-center rounded-md bg-white"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
+ <div className="absolute flex h-full w-full items-center justify-center rounded-md bg-white">
<LoadingCircle />
- </motion.div>
+ </div>
)}
{image ? (
image.startsWith("https://res.cloudinary.com") ? (
@@ -134,12 +151,9 @@ export default function OGSection({
</label>
<div className="relative mt-1 flex rounded-md shadow-sm">
{generatingMetatags && (
- <motion.div
- className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
+ <div className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white">
<LoadingCircle />
- </motion.div>
+ </div>
)}
<TextareaAutosize
name="title"
@@ -166,12 +180,9 @@ export default function OGSection({
</label>
<div className="relative mt-1 flex rounded-md shadow-sm">
{generatingMetatags && (
- <motion.div
- className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
+ <div className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white">
<LoadingCircle />
- </motion.div>
+ </div>
)}
<TextareaAutosize
name="description"
diff --git a/components/app/modals/add-edit-link-modal/preview.tsx b/components/app/modals/add-edit-link-modal/preview.tsx
index d36f404785..42569cf8f0 100644
--- a/components/app/modals/add-edit-link-modal/preview.tsx
+++ b/components/app/modals/add-edit-link-modal/preview.tsx
@@ -64,7 +64,7 @@ export default function Preview({
</div>
);
}
- }, [image]);
+ }, [image, generatingMetatags]);
return (
<div className="h-[1200px]">
diff --git a/components/app/modals/add-edit-link-modal/utm-section.tsx b/components/app/modals/add-edit-link-modal/utm-section.tsx
index 5bf7d794d3..00403ceb18 100644
--- a/components/app/modals/add-edit-link-modal/utm-section.tsx
+++ b/components/app/modals/add-edit-link-modal/utm-section.tsx
@@ -1,18 +1,15 @@
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
import { LinkProps } from "@/lib/types";
import { motion } from "framer-motion";
-import { constructURLFromUTMParams, getParamsFromURL } from "@/lib/utils";
+import {
+ constructURLFromUTMParams,
+ getParamsFromURL,
+ paramsMetadata,
+ getUrlWithoutUTMParams,
+} from "@/lib/utils";
import Switch from "@/components/shared/switch";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-const paramsMetadata = [
- { display: "UTM Source", key: "utm_source", examples: "twitter, facebook" },
- { display: "UTM Medium", key: "utm_medium", examples: "social, email" },
- { display: "UTM Campaign", key: "utm_campaign", examples: "summer_sale" },
- { display: "UTM Term", key: "utm_term", examples: "blue_shoes" },
- { display: "UTM Content", key: "utm_content", examples: "logolink" },
-];
-
export default function UTMSection({
props,
data,
@@ -43,22 +40,13 @@ export default function UTMSection({
useEffect(() => {
if (enabled) {
// if enabling, add all params from props if exists
- setData((prev) => ({
- ...prev,
+ setData({
+ ...data,
url: props?.url || url,
- }));
+ });
} else {
// if disabling, remove all UTM params
- let newURL;
- try {
- newURL = new URL(url);
- paramsMetadata.forEach((param) =>
- newURL.searchParams.delete(param.key),
- );
- setData((prev) => ({ ...prev, url: newURL.toString() }));
- } catch (e) {
- setData((prev) => ({ ...prev, url }));
- }
+ setData({ ...data, url: getUrlWithoutUTMParams(url) });
}
}, [enabled]);
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 21cbca88c0..e9d484a480 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -126,10 +126,8 @@ export async function checkIfKeyExists(domain: string, key: string) {
}
export async function addLink(link: LinkProps) {
- const { domain, key, url, expiresAt, password, title, description, image } =
- link;
+ const { domain, key, url, expiresAt, password, image, customOg } = link;
const hasPassword = password && password.length > 0 ? true : false;
- const proxy = title && description && image ? true : false;
const exat = expiresAt ? new Date(expiresAt).getTime() / 1000 : null;
const exists = await checkIfKeyExists(domain, key);
@@ -142,8 +140,6 @@ export async function addLink(link: LinkProps) {
prisma.link.create({
data: {
...link,
- // can't upload base64 image string to mysql, need to upload to cloudinary first
- image: undefined,
utm_source,
utm_medium,
utm_campaign,
@@ -156,7 +152,7 @@ export async function addLink(link: LinkProps) {
{
url,
password: hasPassword,
- proxy,
+ proxy: customOg,
},
{
nx: true,
@@ -165,7 +161,7 @@ export async function addLink(link: LinkProps) {
},
),
]);
- if (image) {
+ if (customOg && image) {
const { secure_url } = await cloudinary.v2.uploader.upload(image, {
public_id: key,
folder: domain,
@@ -189,22 +185,10 @@ export async function editLink(
oldKey: string,
projectSlug: string,
) {
- const {
- id,
- domain,
- key,
- url,
- expiresAt,
- password,
- title,
- description,
- image,
- } = link;
+ const { id, domain, key, url, expiresAt, password, image, customOg } = link;
const hasPassword = password && password.length > 0 ? true : false;
- const proxy = title && description && image ? true : false;
const exat = expiresAt ? new Date(expiresAt).getTime() : null;
const changedKey = key !== oldKey;
- const uploadedImage = image && image.startsWith("data:image");
if (changedKey) {
const exists = await checkIfKeyExists(domain, key);
@@ -220,8 +204,6 @@ export async function editLink(
},
data: {
...link,
- // if it's an uploaded image (base64 URI), need to upload to cloudinary first
- image: uploadedImage ? undefined : image,
utm_source,
utm_medium,
utm_campaign,
@@ -229,8 +211,9 @@ export async function editLink(
utm_content,
},
}),
- // only upload image to cloudinary if it's changed
- uploadedImage &&
+ // only upload image to cloudinary if customOg is true and there's an image
+ customOg &&
+ image &&
cloudinary.v2.uploader.upload(image, {
public_id: key,
folder: domain,
@@ -242,7 +225,7 @@ export async function editLink(
{
url,
password: hasPassword,
- proxy,
+ proxy: customOg,
},
{
// if the key has an expiry, set exat
@@ -264,13 +247,13 @@ export async function editLink(
]
: []),
// if this link has custom OG tags and the key is the same, update the proxy cache
- proxy &&
+ customOg &&
!changedKey &&
(await fetch(
`https://dub.sh/api/projects/${projectSlug}/domains/${domain}/links/${oldKey}/revalidate?secret=${process.env.REVALIDATE_TOKEN}`,
)),
]);
- if (uploadedImage) {
+ if (customOg && image) {
const { secure_url } = effects[0];
response.image = secure_url;
await prisma.link.update({
diff --git a/lib/types.ts b/lib/types.ts
index a1a5f9552b..823d51c939 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -12,6 +12,7 @@ export interface LinkProps {
expiresAt: Date | null;
password: string | null;
+ customOg: boolean;
title: string | null;
description: string | null;
image: string | null;
@@ -20,9 +21,6 @@ export interface LinkProps {
userId: string;
createdAt: Date;
-
- // only used on client-side
- ogEnabled?: boolean;
}
export interface ProjectProps {
diff --git a/lib/utils.ts b/lib/utils.ts
index 92ea28ab53..f9a0dee371 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -216,22 +216,38 @@ export const constructURLFromUTMParams = (
) => {
if (!url) return "";
try {
- const params = new URL(url).searchParams;
+ const newURL = new URL(url);
for (const [key, value] of Object.entries(utmParams)) {
if (value === "") {
- params.delete(key);
+ newURL.searchParams.delete(key);
} else {
- params.set(key, value);
+ newURL.searchParams.set(key, value);
}
}
- return `${url.split("?")[0]}${
- params.toString() ? `?${params.toString()}` : ""
- }`;
+ return newURL.toString();
} catch (e) {
return "";
}
};
+export const paramsMetadata = [
+ { display: "UTM Source", key: "utm_source", examples: "twitter, facebook" },
+ { display: "UTM Medium", key: "utm_medium", examples: "social, email" },
+ { display: "UTM Campaign", key: "utm_campaign", examples: "summer_sale" },
+ { display: "UTM Term", key: "utm_term", examples: "blue_shoes" },
+ { display: "UTM Content", key: "utm_content", examples: "logolink" },
+];
+
+export const getUrlWithoutUTMParams = (url: string) => {
+ try {
+ const newURL = new URL(url);
+ paramsMetadata.forEach((param) => newURL.searchParams.delete(param.key));
+ return newURL.toString();
+ } catch (e) {
+ return url;
+ }
+};
+
export const isValidUrl = (url: string) => {
try {
new URL(url);
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 2f84bb0628..fdca92ccf9 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -134,7 +134,7 @@ model Link {
expiresAt DateTime? // when the link expires – stored on Redis via ttl
password String? // password to access the link – also stored on Redis
- // Custom OG tags – if not set, will use OG tags from target url
+ 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.)
image String? // OG image for the link (e.g. https://dub.sh/og-image.png)