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.

Converted homepage demo to use server actions 🔥

Steven Tey1ac807f51351
diff --git a/app/dub.sh/stats/[key]/page.tsx b/app/dub.sh/stats/[key]/page.tsx
index be7598136d..ce893d241b 100644
--- a/app/dub.sh/stats/[key]/page.tsx
+++ b/app/dub.sh/stats/[key]/page.tsx
@@ -3,28 +3,35 @@ import Stats from "#/ui/stats";
import { Suspense } from "react";
import { getLinkViaEdge } from "#/lib/planetscale";
import { constructMetadata } from "#/lib/utils";
+import { redis } from "#/lib/upstash";
export const runtime = "edge";
export async function generateMetadata({
params,
}: {
- params: { domain: string; key: string };
+ params: { key: string };
}) {
- const data = await getLinkViaEdge(params.domain, params.key);
+ if (params.key !== "github") {
+ const data = await getLinkViaEdge("dub.sh", params.key);
- // if the link is explicitly private (publicStats === false)
- // (we allow !data because that means it's an ephemeral dub.sh demo link that doesn't exist in the db)
- if (data?.publicStats === 0) {
- return;
+ // if the link doesn't exist in MySQL DB
+ if (!data) {
+ // check if it's an ephemeral demo link in Redis
+ const ephemeralLink = await redis.get(`dub.sh:${params.key}`);
+ if (!ephemeralLink) {
+ return;
+ }
+ // if the link is explicitly private (publicStats === false)
+ } else if (data?.publicStats === 0) {
+ return;
+ }
}
return constructMetadata({
- title: `Stats for ${params.domain}/${params.key} - Dub`,
- description: `Stats page for ${params.domain}/${params.key}${
- data?.url ? `, which redirects to ${data.url}` : ""
- }.`,
- image: `https://${params.domain}/api/og/stats?domain=${params.domain}&key=${params.key}`,
+ title: `Stats for dub.sh/${params.key} - Dub`,
+ description: `Dub is an open-source link management tool for modern marketing teams to create, share, and track short links.`,
+ image: `https://dub.sh/api/og/stats?domain=dub.sh&key=${params.key}`,
});
}
@@ -40,18 +47,24 @@ export async function generateStaticParams() {
export default async function StatsPage({
params,
}: {
- params: { domain: string; key: string };
+ params: { key: string };
}) {
- const data = await getLinkViaEdge(params.domain, params.key);
-
- if (data?.publicStats === 0) {
- notFound();
+ if (params.key !== "github") {
+ const data = await getLinkViaEdge("dub.sh", params.key);
+ if (!data) {
+ const ephemeralLink = await redis.get(`dub.sh:${params.key}`);
+ if (!ephemeralLink) {
+ notFound();
+ }
+ } else if (data?.publicStats === 0) {
+ notFound();
+ }
}
return (
<div className="bg-gray-50">
<Suspense fallback={<div className="h-screen w-full bg-gray-50" />}>
- <Stats staticDomain={params.domain} />
+ <Stats staticDomain="dub.sh" />
</Suspense>
</div>
);
diff --git a/app/ui/home/action.ts b/app/ui/home/action.ts
new file mode 100644
index 0000000000..e738c3cae4
--- /dev/null
+++ b/app/ui/home/action.ts
@@ -0,0 +1,32 @@
+"use server";
+
+import { setRandomKey } from "#/lib/upstash";
+import { isBlacklistedDomain } from "#/lib/utils";
+
+export async function createLink(data: FormData) {
+ const url = data.get("url") as string | undefined;
+
+ if (!url) {
+ return {
+ error: "Missing URL",
+ };
+ }
+ const domainBlacklisted = await isBlacklistedDomain(url);
+ if (domainBlacklisted) {
+ return {
+ error: "Invalid URL",
+ };
+ }
+ const { response, key } = await setRandomKey(url);
+ if (response === "OK") {
+ // if key was successfully added
+ return {
+ key,
+ url,
+ };
+ } else {
+ return {
+ error: "Failed to create link",
+ };
+ }
+}
diff --git a/app/ui/home/demo.tsx b/app/ui/home/demo.tsx
index fc9aa04967..f7ae212885 100644
--- a/app/ui/home/demo.tsx
+++ b/app/ui/home/demo.tsx
@@ -1,43 +1,43 @@
"use client";
import { useState } from "react";
+import { experimental_useFormStatus as useFormStatus } from "react-dom";
import { motion } from "framer-motion";
import LinkCard from "#/ui/home/link-card";
import PlaceholderCard from "#/ui/home/placeholder-card";
-import { LoadingDots } from "#/ui/icons";
+import { LoadingSpinner } from "#/ui/icons";
import { Link2 } from "lucide-react";
import Tooltip, { TooltipContent } from "#/ui/tooltip";
import { FRAMER_MOTION_LIST_ITEM_VARIANTS } from "#/lib/constants";
import useLocalStorage from "#/lib/hooks/use-local-storage";
import { SimpleLinkProps } from "#/lib/types";
import { toast } from "sonner";
+import { createLink } from "./action";
-const Demo = () => {
- const [saving, setSaving] = useState(false);
- const [url, setUrl] = useState("");
+export default function Demo() {
const [hashes, setHashes] = useLocalStorage<SimpleLinkProps[]>("hashes", []);
const [showDefaultLink, setShowDefaultLink] = useState(true);
return (
<div className="mx-auto w-full max-w-md px-2.5 sm:px-0">
<form
- onSubmit={async (e) => {
- e.preventDefault();
- setSaving(true);
- fetch(`/api/edge/links?url=${encodeURIComponent(url)}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- }).then(async (response) => {
- setSaving(false);
- if (response.ok) {
- const json = await response.json();
- setHashes([...hashes, json]);
- setUrl("");
+ action={(data) => {
+ createLink(data).then((res) => {
+ if (res.error) {
+ toast.error(res.error);
+ } else if (!res.key || !res.url) {
+ toast.error("Something went wrong. Please try again.");
+ } else {
+ setHashes([
+ ...hashes,
+ {
+ key: res.key,
+ url: res.url,
+ },
+ ]);
// auto copy to clipboard
navigator.clipboard
- .writeText(`https://dub.sh/${json.key}`)
+ .writeText(`https://dub.sh/${res.key}`)
.then(() => {
toast.success("Copied shortlink to clipboard!");
});
@@ -69,26 +69,14 @@ const Demo = () => {
<div className="relative flex items-center">
<Link2 className="absolute inset-y-0 left-0 my-2 ml-3 w-5 text-gray-400" />
<input
+ name="url"
type="url"
placeholder="Shorten your link"
- value={url}
- onInput={(e) => {
- setUrl((e.target as HTMLInputElement).value);
- }}
+ autoComplete="off"
required
className="peer block w-full rounded-md border border-gray-200 bg-white p-2 pl-10 pr-12 text-sm shadow-lg focus:border-black focus:outline-none focus:ring-0"
/>
- <button
- type="submit"
- disabled={saving}
- className={`${
- saving
- ? "cursor-not-allowed"
- : "hover:border-gray-700 hover:text-gray-700 peer-focus:border-gray-700 peer-focus:text-gray-700"
- } absolute inset-y-0 right-0 my-1.5 mr-1.5 flex w-10 items-center justify-center rounded border border-gray-200 font-sans text-sm font-medium text-gray-400`}
- >
- {saving ? <LoadingDots color="#e5e7eb" /> : <p>↵</p>}
- </button>
+ <FormButton />
</div>
)}
</form>
@@ -149,6 +137,21 @@ const Demo = () => {
</motion.ul>
</div>
);
-};
+}
-export default Demo;
+const FormButton = () => {
+ const { pending } = useFormStatus();
+ return (
+ <button
+ type="submit"
+ disabled={pending}
+ className={`${
+ pending
+ ? "cursor-not-allowed bg-gray-100"
+ : "hover:border-gray-700 hover:text-gray-700 peer-focus:text-gray-700"
+ } absolute inset-y-0 right-0 my-1.5 mr-1.5 flex w-10 items-center justify-center rounded border border-gray-200 font-sans text-sm font-medium text-gray-400`}
+ >
+ {pending ? <LoadingSpinner className="h-4 w-4" /> : <p>↵</p>}
+ </button>
+ );
+};
diff --git a/pages/api/edge/links/index.ts b/pages/api/edge/links/index.ts
deleted file mode 100644
index a12d972ead..0000000000
--- a/pages/api/edge/links/index.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import type { NextRequest } from "next/server";
-import { setRandomKey } from "#/lib/upstash";
-import { isBlacklistedDomain } from "#/lib/utils";
-
-export const config = {
- runtime: "edge",
-};
-
-export default async function handler(req: NextRequest) {
- if (req.method === "POST") {
- const url = req.nextUrl.searchParams.get("url");
- if (!url) {
- return new Response(`Missing url`, { status: 400 });
- }
- const domainBlacklisted = await isBlacklistedDomain(url);
- if (domainBlacklisted) {
- return new Response(`Invalid url`, { status: 400 });
- }
- const { response, key } = await setRandomKey(url);
- if (response === "OK") {
- // if key was successfully added
- return new Response(
- JSON.stringify({
- key,
- url,
- }),
- { status: 200 },
- );
- } else {
- return new Response(
- JSON.stringify({
- error: "failed to save link",
- }),
- { status: 500 },
- );
- }
- } else {
- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });
- }
-}