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.

Add "Expired Link" page for expired links

Steven Tey9e5ea4576dad
diff --git a/apps/web/app/api/callback/expire/route.ts b/apps/web/app/api/callback/expire/route.ts
new file mode 100644
index 0000000000..d599832550
--- /dev/null
+++ b/apps/web/app/api/callback/expire/route.ts
@@ -0,0 +1,57 @@
+import { receiver } from "@/lib/cron";
+import prisma from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+
+export async function POST(req: Request) {
+ const body = await req.json();
+ if (process.env.VERCEL === "1") {
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(body),
+ });
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
+ const { linkId } = body;
+ if (!linkId) {
+ return new Response("Missing link ID", { status: 200 });
+ }
+
+ console.log({ linkId });
+
+ const link = await prisma.link.findUnique({
+ where: {
+ id: linkId,
+ },
+ select: {
+ domain: true,
+ key: true,
+ expiresAt: true,
+ },
+ });
+
+ if (!link) {
+ return new Response("Link not found", { status: 200 });
+ }
+
+ if (!link.expiresAt || link.expiresAt < new Date()) {
+ return new Response("Link already expired", { status: 200 });
+ }
+
+ const { domain, key } = link;
+
+ const redisLink = await redis.get(`${domain}:${key}`);
+
+ if (!redisLink) {
+ return new Response("Link not found", { status: 404 });
+ }
+
+ await redis.set(`${domain}:${key}`, {
+ ...redisLink,
+ expired: true,
+ });
+
+ return new Response("Successfully expired link", { status: 200 });
+}
diff --git a/apps/web/app/expired/[domain]/[key]/page.tsx b/apps/web/app/expired/[domain]/[key]/page.tsx
new file mode 100644
index 0000000000..b9c99c24a1
--- /dev/null
+++ b/apps/web/app/expired/[domain]/[key]/page.tsx
@@ -0,0 +1,54 @@
+import { getLinkViaEdge } from "@/lib/planetscale";
+import { Background, Footer, Nav } from "@dub/ui";
+import { constructMetadata } from "@dub/utils";
+import { TimerOff } from "lucide-react";
+import { notFound } from "next/navigation";
+
+export const runtime = "edge";
+
+export const metadata = constructMetadata({
+ title: "Expired Link – Dub.co",
+ description:
+ "This link has expired. Please contact the owner of this link to get a new one.",
+ noIndex: true,
+});
+
+export default async function ExpiredPage({
+ params,
+}: {
+ params: { domain: string; key: string };
+}) {
+ const domain = params.domain;
+ const key = decodeURIComponent(params.key);
+
+ const data = await getLinkViaEdge(domain, key);
+
+ // if the link doesn't exist
+ if (!data) {
+ notFound();
+ }
+
+ return (
+ <main className="flex min-h-screen flex-col justify-between">
+ <Nav />
+ <div className="mx-2 my-10 flex max-w-md flex-col items-center space-y-5 px-2.5 text-center sm:mx-auto sm:max-w-lg sm:px-0 lg:mb-16">
+ <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full border border-gray-300 bg-white/30">
+ <TimerOff className="h-6 w-6 text-gray-400" />
+ </div>
+ <h1 className="font-display text-5xl font-bold">Expired Link</h1>
+ <p className="text-lg text-gray-600">
+ This link has expired. Please contact the owner of this link to get a
+ new one.
+ </p>
+ <a
+ href="https://dub.co"
+ className="rounded-full bg-gray-800 px-10 py-2 font-medium text-white transition-colors hover:bg-black"
+ >
+ Create Your Free Branded Link
+ </a>
+ </div>
+ <Footer />
+ <Background />
+ </main>
+ );
+}
diff --git a/apps/web/app/protected/[domain]/[key]/page.tsx b/apps/web/app/protected/[domain]/[key]/page.tsx
index 39ca061b8e..fd54450c2e 100644
--- a/apps/web/app/protected/[domain]/[key]/page.tsx
+++ b/apps/web/app/protected/[domain]/[key]/page.tsx
@@ -4,7 +4,7 @@ import prisma from "@/lib/prisma";
import PasswordForm from "./form";
import { notFound, redirect } from "next/navigation";
-const title = "Password Required";
+const title = "Password Required – Dub.co";
const description =
"This link is password protected. Please enter the password to view it.";
const image = "https://dub.co/_static/password-protected.png";
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index d11e32abba..9348bd9453 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -7,6 +7,7 @@ import {
import prisma from "@/lib/prisma";
import { redis } from "@/lib/upstash";
import {
+ APP_DOMAIN_WITH_NGROK,
DEFAULT_REDIRECTS,
DUB_DOMAINS,
DUB_PROJECT_ID,
@@ -23,7 +24,7 @@ import cloudinary from "cloudinary";
import { isIframeable } from "../middleware/utils";
import { LinkProps, ProjectProps } from "../types";
import { Session } from "../auth";
-import { SetCommandOptions } from "@upstash/redis";
+import { qstash } from "../cron";
export async function getLinksForProject({
projectId,
@@ -221,7 +222,7 @@ export async function processLink({
session?: Session;
bulk?: boolean;
}) {
- let { domain, key, url, image, rewrite, geo } = payload;
+ let { domain, key, url, image, rewrite, expiresAt, geo } = payload;
// url checks
if (!url) {
@@ -390,6 +391,13 @@ export async function processLink({
status: 422,
};
}
+ if (expiresAt) {
+ return {
+ link: payload,
+ error: "You cannot set expiry dates with bulk link creation.",
+ status: 422,
+ };
+ }
const exists = await checkIfKeyExists(domain, key);
if (exists) {
return {
@@ -469,14 +477,14 @@ export async function addLink(link: LinkProps) {
rewrite: true,
iframeable: await isIframeable({ url, requestDomain: domain }),
}),
+ expired: expiresAt && new Date(expiresAt) < new Date(),
...(ios && { ios }),
...(android && { android }),
...(geo && { geo }),
},
{
nx: true,
- ...(expiresAt && { exat: new Date(expiresAt).getTime() / 1000 }),
- } as SetCommandOptions,
+ },
),
]);
@@ -496,13 +504,24 @@ export async function addLink(link: LinkProps) {
},
});
}
+
+ // if link expires, schedule a job to expire it
+ if (expiresAt && new Date(expiresAt) > new Date()) {
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/callback/expire`,
+ delay: new Date(expiresAt).getTime() - new Date().getTime(),
+ body: {
+ linkId: response.id,
+ },
+ });
+ }
return response;
}
export async function bulkCreateLinks(links: LinkProps[]) {
if (links.length === 0) return [];
const pipeline = redis.pipeline();
- links.forEach(({ domain, key, url, expiresAt, password }) => {
+ links.forEach(({ domain, key, url, password }) => {
const hasPassword = password && password.length > 0 ? true : false;
pipeline.set(
`${domain}:${key}`,
@@ -512,8 +531,7 @@ export async function bulkCreateLinks(links: LinkProps[]) {
},
{
nx: true,
- ...(expiresAt && { exat: new Date(expiresAt).getTime() / 1000 }),
- } as SetCommandOptions,
+ },
);
});
@@ -628,24 +646,30 @@ export async function editLink({
: cloudinary.v2.uploader.destroy(`${domain}/${key}`, {
invalidate: true,
}),
- redis.set(
- `${domain}:${key}`,
- {
- url: encodeURIComponent(url),
- password: hasPassword,
- proxy,
- ...(rewrite && {
- rewrite: true,
- iframeable: await isIframeable({ url, requestDomain: domain }),
- }),
- ...(ios && { ios }),
- ...(android && { android }),
- ...(geo && { geo }),
- },
- {
- ...(expiresAt && { exat: new Date(expiresAt).getTime() / 1000 }),
- } as SetCommandOptions,
- ),
+ redis.set(`${domain}:${key}`, {
+ url: encodeURIComponent(url),
+ password: hasPassword,
+ proxy,
+ ...(rewrite && {
+ rewrite: true,
+ iframeable: await isIframeable({ url, requestDomain: domain }),
+ }),
+ expired: expiresAt && new Date(expiresAt) < new Date(),
+ ...(ios && { ios }),
+ ...(android && { android }),
+ ...(geo && { geo }),
+ }),
+ ...(expiresAt && new Date(expiresAt) > new Date()
+ ? [
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/callback/expire`,
+ delay: new Date(expiresAt).getTime() - new Date().getTime(),
+ body: {
+ linkId: id,
+ },
+ }),
+ ]
+ : []),
// if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name
...(changedDomain || changedKey
? [
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index f57647d5bb..28aa47408d 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -48,6 +48,7 @@ export default async function LinkMiddleware(
proxy?: boolean;
rewrite?: boolean;
iframeable?: boolean;
+ expired?: boolean;
ios?: string;
android?: string;
geo?: object;
@@ -62,19 +63,21 @@ export default async function LinkMiddleware(
proxy,
rewrite,
iframeable,
+ expired,
ios,
android,
geo,
} = response || {};
if (target) {
- // only show inspect model if the link is not password protected
+ // 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");
@@ -92,6 +95,13 @@ export default async function LinkMiddleware(
}
}
+ // if the link has expired
+ if (expired) {
+ return NextResponse.rewrite(
+ new URL(`/expired/${domain}/${encodeURIComponent(key)}`, req.url),
+ );
+ }
+
// only track the click when there is no `dub-no-track` header
if (!req.headers.get("dub-no-track")) {
ev.waitUntil(recordClick({ req, domain, key }));
diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsx
index c61e2473b7..8466f2e65a 100644
--- a/apps/web/ui/links/link-card.tsx
+++ b/apps/web/ui/links/link-card.tsx
@@ -40,6 +40,7 @@ import {
EyeOff,
MessageCircle,
QrCode,
+ TimerOff,
} from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
@@ -59,6 +60,7 @@ export default function LinkCard({
domain,
url,
rewrite,
+ expiresAt,
createdAt,
lastClicked,
archived,
@@ -123,6 +125,8 @@ export default function LinkCard({
},
});
+ const expired = expiresAt && new Date(expiresAt) < new Date();
+
const { setShowArchiveLinkModal, ArchiveLinkModal } = useArchiveLinkModal({
props,
archived: !archived,
@@ -225,10 +229,20 @@ export default function LinkCard({
)}
<div className="relative flex items-center justify-between">
<div className="relative flex shrink items-center">
- {archived ? (
- <Tooltip content="This link is archived. It will still work, but won't be shown in your dashboard.">
+ {archived || expired ? (
+ <Tooltip
+ content={
+ archived
+ ? "This link is archived. It will still work, but won't be shown in your dashboard."
+ : "This link has expired. It will still show up in your dashboard, but users will get an 'Expired' page when they click on it."
+ }
+ >
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-300 px-0 sm:h-10 sm:w-10">
- <Archive className="h-4 w-4 text-gray-500 sm:h-5 sm:w-5" />
+ {archived ? (
+ <Archive className="h-4 w-4 text-gray-500 sm:h-5 sm:w-5" />
+ ) : (
+ <TimerOff className="h-4 w-4 text-gray-500 sm:h-5 sm:w-5" />
+ )}
</div>
</Tooltip>
) : (
@@ -269,7 +283,7 @@ export default function LinkCard({
className={cn(
"w-full max-w-[140px] truncate text-sm font-semibold text-blue-800 sm:max-w-[300px] sm:text-base md:max-w-[360px] xl:max-w-[500px]",
{
- "text-gray-500": archived,
+ "text-gray-500": archived || expired,
},
)}
href={linkConstructor({ key, domain })}