Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add custom domain

Richie McIlroyb8367cc86a3e
diff --git a/.env.example b/.env.example
index ba9f7d0ee..db19c70e0 100644
--- a/.env.example
+++ b/.env.example
@@ -72,7 +72,10 @@ NEXTAUTH_SECRET=
# Only needed by cap.so cloud
# NEXT_LOOPS_KEY=
-
+# Only needed by cap.so cloud
+# VERCEL_AUTH_TOKEN=
+# VERCEL_PROJECT_ID=
+# VERCEL_TEAM_ID=
### @cap/tasks
TASKS_PORT=3002
diff --git a/apps/web/app/api/settings/workspace/domain/route.ts b/apps/web/app/api/settings/workspace/domain/route.ts
new file mode 100644
index 000000000..823212c93
--- /dev/null
+++ b/apps/web/app/api/settings/workspace/domain/route.ts
@@ -0,0 +1,303 @@
+export const dynamic = "force-dynamic";
+export const revalidate = 0;
+export const fetchCache = 'force-no-store'
+
+import { type NextRequest } from "next/server";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { spaces } from "@cap/database/schema";
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+
+const getConfigResponse = async (domain: string) => {
+ console.log(`[Domain Config] Fetching config for domain: ${domain}`);
+ const response = await fetch(
+ `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${process.env.VERCEL_TEAM_ID}&strict=true`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ cache: "no-store"
+ },
+ ).then((res) => res.json());
+ console.log(`[Domain Config] Response:`, response);
+ return response;
+};
+
+const getDomainResponse = async (domain: string) => {
+ console.log(`[Domain Status] Checking status for domain: ${domain}`);
+ const response = await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain.toLowerCase()}?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ cache: "no-store"
+ },
+ ).then((res) => res.json());
+ console.log(`[Domain Status] Response:`, response);
+ return response;
+};
+
+const verifyDomain = async (domain: string) => {
+ console.log(`[Domain Verify] Verifying domain: ${domain}`);
+ const response = await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain.toLowerCase()}/verify?teamId=${process.env.VERCEL_TEAM_ID}&strict=true`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ },
+ ).then((res) => res.json());
+ console.log(`[Domain Verify] Response:`, response);
+ return response;
+};
+
+const addDomain = async (domain: string) => {
+ console.log(`[Domain Add] Adding new domain: ${domain}`);
+ const response = await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ name: domain }),
+ cache: "no-store"
+ },
+ ).then((res) => res.json());
+ console.log(`[Domain Add] Response:`, response);
+ return response;
+};
+
+const getRequiredConfig = async (domain: string) => {
+ console.log(`[Required Config] Fetching required config for domain: ${domain}`);
+ const response = await fetch(
+ `https://vercel.com/api/v6/domains/${domain.toLowerCase()}/config?strict=true&teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ cache: "no-store"
+ },
+ ).then((res) => res.json());
+ console.log(`[Required Config] Response:`, response);
+ return response;
+};
+
+async function checkDomainStatus(domain: string) {
+ console.log(`[Domain Check] Checking domain status for: ${domain}`);
+ try {
+ const [domainJson, configJson, requiredConfigJson] = await Promise.all([
+ getDomainResponse(domain),
+ getConfigResponse(domain),
+ getRequiredConfig(domain),
+ ]);
+
+ let verified = false;
+
+ if (configJson.misconfigured || domainJson?.error?.code === "not_found") {
+ verified = false;
+ } else if (domainJson.verified) {
+ verified = true;
+ } else {
+ const verificationJson = await verifyDomain(domain);
+ verified = verificationJson && verificationJson.verified;
+ }
+
+ // Get the current and required A records
+ const currentAValues = configJson.aValues || [];
+ const requiredAValue = requiredConfigJson.aValues?.[0];
+
+ return {
+ verified,
+ config: {
+ ...configJson,
+ verification: domainJson?.verification || [],
+ currentAValues,
+ requiredAValue
+ },
+ status: domainJson
+ };
+ } catch (error) {
+ console.error('[Domain Check] Error checking domain status:', error);
+ return {
+ verified: false,
+ error: "Failed to check domain status"
+ };
+ }
+}
+
+export async function POST(request: NextRequest) {
+ console.log('[POST] Processing domain addition request');
+ const user = await getCurrentUser();
+ const { domain, spaceId } = await request.json();
+ console.log(`[POST] Request details - Domain: ${domain}, SpaceId: ${spaceId}`);
+
+ if (!user) {
+ console.log('[POST] Unauthorized - No user found');
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+
+ if (!space || space.ownerId !== user.id) {
+ console.log('[POST] Unauthorized - Invalid space or ownership');
+ return Response.json({ error: "Unauthorized" }, { status: 403 });
+ }
+
+ try {
+ console.log(`[POST] Adding domain to Vercel: ${domain}`);
+ const addDomainResponse = await addDomain(domain);
+
+ if (addDomainResponse.error) {
+ console.error('[POST] Error adding domain:', addDomainResponse.error);
+ return Response.json({ error: addDomainResponse.error.message }, { status: 400 });
+ }
+
+ console.log(`[POST] Updating space with custom domain: ${domain}`);
+ await db
+ .update(spaces)
+ .set({
+ customDomain: domain,
+ domainVerified: null,
+ })
+ .where(eq(spaces.id, spaceId));
+
+ console.log('[POST] Checking domain verification status');
+ const status = await checkDomainStatus(domain);
+
+ if (status.verified) {
+ console.log(`[POST] Domain verified, updating verification timestamp: ${domain}`);
+ await db
+ .update(spaces)
+ .set({
+ domainVerified: new Date(),
+ })
+ .where(eq(spaces.id, spaceId));
+ }
+
+ return Response.json(status);
+ } catch (error) {
+ console.error('[POST] Error in domain verification:', error);
+ return Response.json(
+ { error: "Failed to verify domain" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function DELETE(request: NextRequest) {
+ console.log('[DELETE] Processing domain removal request');
+ const user = await getCurrentUser();
+ const { spaceId } = await request.json();
+ console.log(`[DELETE] Request details - SpaceId: ${spaceId}`);
+
+ if (!user) {
+ console.log('[DELETE] Unauthorized - No user found');
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+
+ if (!space || space.ownerId !== user.id) {
+ console.log('[DELETE] Unauthorized - Invalid space or ownership');
+ return Response.json({ error: "Unauthorized" }, { status: 403 });
+ }
+
+ try {
+ if (space.customDomain) {
+ console.log(`[DELETE] Removing domain from Vercel: ${space.customDomain}`);
+ await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${space.customDomain.toLowerCase()}?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: 'DELETE',
+ headers: {
+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
+ },
+ }
+ );
+ }
+
+ console.log('[DELETE] Updating space to remove custom domain');
+ await db
+ .update(spaces)
+ .set({
+ customDomain: null,
+ domainVerified: null,
+ })
+ .where(eq(spaces.id, spaceId));
+
+ return Response.json({ success: true });
+ } catch (error) {
+ console.error('[DELETE] Error removing domain:', error);
+ return Response.json(
+ { error: "Failed to remove domain" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function GET(request: NextRequest) {
+ console.log('[GET] Processing domain status check request');
+ const searchParams = request.nextUrl.searchParams;
+ const spaceId = searchParams.get('spaceId');
+ console.log(`[GET] Request details - SpaceId: ${spaceId}`);
+ const user = await getCurrentUser();
+
+ if (!user || !spaceId) {
+ console.log('[GET] Unauthorized - No user or spaceId found');
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+
+ if (!space || space.ownerId !== user.id) {
+ console.log('[GET] Unauthorized - Invalid space or ownership');
+ return Response.json({ error: "Unauthorized" }, { status: 403 });
+ }
+
+ if (!space.customDomain) {
+ console.log('[GET] No custom domain set for space');
+ return Response.json({ error: "No custom domain set" }, { status: 400 });
+ }
+
+ try {
+ console.log(`[GET] Checking status for domain: ${space.customDomain}`);
+ const status = await checkDomainStatus(space.customDomain);
+
+ if (status.verified && !space.domainVerified) {
+ console.log(`[GET] Updating domain verification timestamp: ${space.customDomain}`);
+ await db
+ .update(spaces)
+ .set({
+ domainVerified: new Date(),
+ })
+ .where(eq(spaces.id, spaceId));
+ } else if (!status.verified && space.domainVerified) {
+ console.log(`[GET] Removing domain verification timestamp: ${space.customDomain}`);
+ await db
+ .update(spaces)
+ .set({
+ domainVerified: null,
+ })
+ .where(eq(spaces.id, spaceId));
+ }
+
+ return Response.json(status);
+ } catch (error) {
+ console.error('[GET] Error checking domain status:', error);
+ return Response.json(
+ { error: "Failed to check domain status" },
+ { status: 500 }
+ );
+ }
+}
\ No newline at end of file
diff --git a/apps/web/app/dashboard/caps/components/CapCard.tsx b/apps/web/app/dashboard/caps/components/CapCard.tsx
index 9644c8783..427688f60 100644
--- a/apps/web/app/dashboard/caps/components/CapCard.tsx
+++ b/apps/web/app/dashboard/caps/components/CapCard.tsx
@@ -9,7 +9,7 @@ import { ShareIcon, ChevronDown } from "lucide-react";
import { SharingDialog } from "@/app/dashboard/caps/components/SharingDialog";
import { useRouter } from "next/navigation"; // Add this import
import { serverEnv, clientEnv, NODE_ENV } from "@cap/env";
-
+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
interface CapCardProps {
cap: {
id: string;
@@ -38,7 +38,8 @@ export const CapCard: React.FC<CapCardProps> = ({
const [title, setTitle] = useState(cap.name);
const [isSharingDialogOpen, setIsSharingDialogOpen] = useState(false);
const [sharedSpaces, setSharedSpaces] = useState(cap.sharedSpaces);
- const router = useRouter(); // Add this line
+ const router = useRouter();
+ const { activeSpace } = useSharedContext();
const handleTitleBlur = async () => {
if (!title) {
@@ -121,7 +122,9 @@ export const CapCard: React.FC<CapCardProps> = ({
<a
className="group block"
href={
- clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
+ activeSpace?.space.customDomain
+ ? `https://${activeSpace.space.customDomain}/${cap.id}`
+ : clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
? `https://cap.link/${cap.id}`
: `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${cap.id}`
}
diff --git a/apps/web/app/dashboard/settings/workspace/Workspace.tsx b/apps/web/app/dashboard/settings/workspace/Workspace.tsx
index e3bd0c90a..74a0ac762 100644
--- a/apps/web/app/dashboard/settings/workspace/Workspace.tsx
+++ b/apps/web/app/dashboard/settings/workspace/Workspace.tsx
@@ -29,6 +29,7 @@ import toast from "react-hot-toast";
import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
import { format } from "date-fns";
import { Tooltip } from "react-tooltip";
+import { CustomDomain } from "./components/CustomDomain";
export const Workspace = () => {
const { spaceData, activeSpace, user } = useSharedContext();
@@ -231,6 +232,20 @@ export const Workspace = () => {
Save
</Button>
</CardFooter>
+ {user.email === "[email protected]" && (
+ <>
+ <CardContent className="pt-6">
+ <CardTitle>Custom Domain</CardTitle>
+ <CardDescription>
+ Configure a custom domain for your workspace's shared caps.
+ </CardDescription>
+ <div className="mt-4">
+ <CustomDomain />
+ </div>
+ </CardContent>
+ <CardFooter className="border-b px-6 pt-0 pb-2"></CardFooter>
+ </>
+ )}
<CardHeader>
<div className="flex items-center justify-between">
<div>
diff --git a/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx b/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx
new file mode 100644
index 000000000..6285692c8
--- /dev/null
+++ b/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx
@@ -0,0 +1,481 @@
+export const dynamic = "force-dynamic";
+export const revalidate = 0;
+export const fetchCache = "force-no-store";
+
+import { useState, useEffect, useRef } from "react";
+import { Button, Input, Label } from "@cap/ui";
+import { toast } from "react-hot-toast";
+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
+import { RefreshCw, CheckCircle, XCircle, Copy, Check } from "lucide-react";
+import { useRouter } from "next/navigation";
+
+type DomainVerification = {
+ type: string;
+ domain: string;
+ value: string;
+ reason: string;
+};
+
+type DomainConfig = {
+ name: string;
+ apexName: string;
+ verification: DomainVerification[];
+ verified: boolean;
+ misconfigured?: boolean;
+ aValues?: string[];
+ currentAValues?: string[];
+ requiredAValue?: string;
+};
+
+type VerificationResponse = {
+ verified: boolean;
+ config: DomainConfig;
+ status: any;
+ aRecordConfig?: {
+ current: string;
+ required: string;
+ };
+};
+
+export function CustomDomain() {
+ const router = useRouter();
+ const { activeSpace } = useSharedContext();
+ const [domain, setDomain] = useState(activeSpace?.space.customDomain || "");
+ const [loading, setLoading] = useState(false);
+ const [verifying, setVerifying] = useState(false);
+ const [isVerified, setIsVerified] = useState(
+ !!activeSpace?.space.domainVerified
+ );
+ const [domainConfig, setDomainConfig] = useState<DomainConfig | null>(null);
+ const [copiedField, setCopiedField] = useState<"name" | "value" | null>(null);
+ const initialCheckDone = useRef(false);
+ const pollInterval = useRef<NodeJS.Timeout>();
+ const POLL_INTERVAL = 5000; // 5 seconds
+
+ const cleanDomain = (input: string) => {
+ if (!input) return "";
+
+ if (input === "cap.so" || input === "cap.link") {
+ return "";
+ }
+
+ const withoutProtocol = input.replace(/^(https?:\/\/)?(www\.)?/i, "");
+ const parts = withoutProtocol.split("/");
+ const domain = parts[0] || "";
+ const withoutQuery = domain.split("?")[0] || "";
+ const withoutHash = withoutQuery.split("#")[0] || "";
+ const cleanedDomain = withoutHash.trim();
+
+ // Check for valid domain with optional subdomains
+ const hasTLD =
+ /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(
+ cleanedDomain
+ );
+
+ return hasTLD ? cleanedDomain : "";
+ };
+
+ const handleCopy = async (text: string, field: "name" | "value") => {
+ try {
+ await navigator.clipboard.writeText(text);
+ setCopiedField(field);
+ setTimeout(() => setCopiedField(null), 2000);
+ toast.success("Copied to clipboard");
+ } catch (err) {
+ toast.error("Failed to copy to clipboard");
+ }
+ };
+
+ const checkVerification = async (showToasts = true) => {
+ if (!activeSpace?.space.id || !activeSpace?.space.customDomain) return;
+ setVerifying(true);
+ try {
+ const response = await fetch(
+ `/api/settings/workspace/domain?spaceId=${activeSpace.space.id}`,
+ {
+ cache: "no-store",
+ next: {
+ revalidate: 0,
+ },
+ }
+ );
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to check domain verification");
+ }
+
+ setIsVerified(data.verified);
+ setDomainConfig(data.config);
+
+ if (showToasts) {
+ if (data.verified) {
+ toast.success("Domain is verified!");
+ // Stop polling once verified
+ if (pollInterval.current) {
+ clearInterval(pollInterval.current);
+ pollInterval.current = undefined;
+ }
+ } else {
+ toast.error(
+ "Domain is not verified. Please check your DNS settings."
+ );
+ }
+ }
+ } catch (error) {
+ if (showToasts) {
+ toast.error("Failed to check domain verification");
+ }
+ } finally {
+ setVerifying(false);
+ }
+ };
+
+ useEffect(() => {
+ // Start polling if we have a custom domain and it's not verified
+ if (activeSpace?.space.customDomain && !isVerified) {
+ // Clear any existing interval
+ if (pollInterval.current) {
+ clearInterval(pollInterval.current);
+ }
+
+ // Check immediately
+ checkVerification(false);
+
+ // Start polling
+ pollInterval.current = setInterval(() => {
+ checkVerification(false);
+ }, POLL_INTERVAL);
+ }
+
+ // Cleanup interval if domain becomes verified or component unmounts
+ return () => {
+ if (pollInterval.current) {
+ clearInterval(pollInterval.current);
+ pollInterval.current = undefined;
+ }
+ };
+ }, [activeSpace?.space.customDomain, isVerified]);
+
+ // Initial check when component mounts
+ useEffect(() => {
+ if (!initialCheckDone.current && activeSpace?.space.customDomain) {
+ initialCheckDone.current = true;
+ checkVerification(false);
+ }
+ }, [activeSpace?.space.customDomain]);
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ const cleanedDomain = cleanDomain(domain);
+ if (!cleanedDomain) {
+ toast.error("Please enter a valid domain");
+ return;
+ }
+
+ setLoading(true);
+ setDomain(cleanedDomain); // Update the input to show the cleaned domain
+
+ try {
+ const response = await fetch("/api/settings/workspace/domain", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ domain: cleanedDomain,
+ spaceId: activeSpace?.space.id,
+ }),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to update domain");
+ }
+
+ toast.success("Domain settings updated");
+ router.refresh();
+
+ // Set initial domain config from the response
+ setDomainConfig(data.status);
+ setIsVerified(data.verified);
+
+ // Trigger a refresh after 1 second to get DNS config
+ setTimeout(() => {
+ checkVerification(false);
+ }, 1000);
+
+ // Start polling
+ pollInterval.current = setInterval(() => {
+ checkVerification(false);
+ }, POLL_INTERVAL);
+ } catch (error) {
+ toast.error("Failed to update domain settings");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleRemoveDomain = async () => {
+ if (!confirm("Are you sure you want to remove this custom domain?")) return;
+
+ setLoading(true);
+ try {
+ const response = await fetch("/api/settings/workspace/domain", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ spaceId: activeSpace?.space.id,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to remove domain");
+ }
+
+ // Clear polling when domain is removed
+ if (pollInterval.current) {
+ clearInterval(pollInterval.current);
+ pollInterval.current = undefined;
+ }
+
+ setDomain("");
+ setIsVerified(false);
+ toast.success("Custom domain removed");
+ router.refresh();
+ } catch (error) {
+ toast.error("Failed to remove domain");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <Label htmlFor="customDomain" className="text-sm font-medium">
+ Add your custom domain here
+ </Label>
+ <div className="mt-2 flex gap-2">
+ <Input
+ type="text"
+ id="customDomain"
+ placeholder="your-domain.com"
+ value={domain}
+ onChange={(e) => setDomain(e.target.value)}
+ disabled={loading}
+ className="flex-1"
+ />
+ <Button type="button" onClick={handleSubmit} disabled={loading}>
+ {loading ? "Saving..." : "Save"}
+ </Button>
+ {activeSpace?.space.customDomain && (
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => checkVerification(true)}
+ disabled={verifying}
+ className="w-[105px]"
+ >
+ {verifying ? (
+ <RefreshCw className="mr-2 h-6 w-6 animate-spin" />
+ ) : (
+ <RefreshCw className="mr-2 h-6 w-6" />
+ )}
+ Refresh
+ </Button>
+ )}
+ {activeSpace?.space.customDomain && (
+ <Button
+ type="button"
+ variant="destructive"
+ onClick={handleRemoveDomain}
+ disabled={loading}
+ >
+ Remove
+ </Button>
+ )}
+ </div>
+ {activeSpace?.space.customDomain && (
+ <div className="mt-4 space-y-4">
+ <div className="flex items-center gap-2">
+ {isVerified ? (
+ <>
+ <div className="flex items-center gap-1.5 text-green-500 bg-green-100 px-2.5 py-1.5 rounded-md text-sm">
+ <CheckCircle className="h-4 w-4" />
+ <span className="font-medium text-green-500 text-sm">
+ Domain verified
+ </span>
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="flex items-center gap-1.5 text-red-600 bg-red-50 px-2.5 py-1.5 rounded-md text-sm">
+ <XCircle className="h-4 w-4" />
+ <span className="font-medium text-red-500 text-sm">
+ Domain not verified
+ </span>
+ </div>
+ </>
+ )}
+ </div>
+ {!isVerified && domainConfig?.verification?.[0] && (
+ <div className="rounded-lg border border-gray-200 overflow-hidden">
+ <div className="px-4 py-3 bg-gray-50 border-b border-gray-200">
+ <h4 className="font-medium text-gray-900">
+ DNS Configuration Required
+ </h4>
+ <p className="mt-1 text-sm text-gray-600">
+ To verify your domain ownership, add the following TXT
+ record to your DNS configuration:
+ </p>
+ </div>
+ <div className="px-4 py-3">
+ <dl className="grid gap-4">
+ <div className="grid grid-cols-[100px,1fr] items-center">
+ <dt className="text-sm font-medium text-gray-500">
+ Type
+ </dt>
+ <dd className="text-sm text-gray-900">
+ {domainConfig?.verification?.[0]?.type}
+ </dd>
+ </div>
+ <div className="grid grid-cols-[100px,1fr] items-center">
+ <dt className="text-sm font-medium text-gray-500">
+ Name
+ </dt>
+ <dd className="flex items-center gap-2 text-sm text-gray-900">
+ <div className="flex items-center gap-1.5 bg-gray-50 px-2 py-1 rounded flex-1 min-w-0">
+ <code className="truncate">
+ {domainConfig?.verification?.[0]?.domain}
+ </code>
+ {domainConfig?.verification?.[0]?.domain && (
+ <button
+ type="button"
+ onClick={() => {
+ const domain =
+ domainConfig?.verification?.[0]?.domain;
+ if (domain) handleCopy(domain, "name");
+ }}
+ className="p-1 hover:bg-gray-100 rounded-md transition-colors shrink-0"
+ title="Copy to clipboard"
+ >
+ {copiedField === "name" ? (
+ <Check className="h-4 w-4 text-green-500" />
+ ) : (
+ <Copy className="h-4 w-4 text-gray-500" />
+ )}
+ </button>
+ )}
+ </div>
+ </dd>
+ </div>
+ <div className="grid grid-cols-[100px,1fr] items-center">
+ <dt className="text-sm font-medium text-gray-500">
+ Value
+ </dt>
+ <dd className="flex items-center gap-2 text-sm text-gray-900">
+ <div className="flex items-center gap-1.5 bg-gray-50 p-2 rounded flex-1 min-w-0">
+ <code className="font-mono text-xs break-all">
+ {domainConfig?.verification?.[0]?.value}
+ </code>
+ {domainConfig?.verification?.[0]?.value && (
+ <button
+ type="button"
+ onClick={() => {
+ const value =
+ domainConfig?.verification?.[0]?.value;
+ if (value) handleCopy(value, "value");
+ }}
+ className="p-1 hover:bg-gray-100 rounded-md transition-colors shrink-0"
+ title="Copy to clipboard"
+ >
+ {copiedField === "value" ? (
+ <Check className="h-4 w-4 text-green-500" />
+ ) : (
+ <Copy className="h-4 w-4 text-gray-500" />
+ )}
+ </button>
+ )}
+ </div>
+ </dd>
+ </div>
+ </dl>
+ </div>
+ </div>
+ )}
+
+ {!isVerified &&
+ !domainConfig?.verification?.[0] &&
+ domainConfig?.requiredAValue && (
+ <div className="rounded-lg border border-gray-200 overflow-hidden mt-4">
+ <div className="px-4 py-3 bg-gray-50 border-b border-gray-200">
+ <h4 className="font-medium text-gray-900">
+ DNS Configuration Required
+ </h4>
+ <p className="mt-1 text-sm text-gray-600">
+ Please configure your DNS settings with the following A
+ record:
+ </p>
+ </div>
+ <div className="px-4 py-3">
+ <dl className="grid gap-4">
+ {domainConfig.currentAValues &&
+ domainConfig.currentAValues.length > 0 && (
+ <div className="grid grid-cols-[100px,1fr] items-center">
+ <dt className="text-sm font-medium text-gray-500">
+ Current
+ </dt>
+ <dd className="text-sm text-gray-600">
+ {domainConfig.currentAValues.map(
+ (value, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-2"
+ >
+ <code className="bg-gray-50 px-2 py-1 rounded">
+ {value}
+ </code>
+ </div>
+ )
+ )}
+ </dd>
+ </div>
+ )}
+ <div className="grid grid-cols-[100px,1fr] items-center">
+ <dt className="text-sm font-medium text-gray-500">
+ Required
+ </dt>
+ <dd className="flex items-center gap-2">
+ <div className="flex items-center gap-1.5 bg-gray-50 px-2 py-1 rounded flex-1 min-w-0">
+ <code className="text-sm text-green-600">
+ {domainConfig.requiredAValue}
+ </code>
+ <button
+ type="button"
+ onClick={() =>
+ domainConfig.requiredAValue &&
+ handleCopy(domainConfig.requiredAValue, "value")
+ }
+ className="p-1 hover:bg-gray-100 rounded-md transition-colors shrink-0"
+ title="Copy to clipboard"
+ >
+ {copiedField === "value" ? (
+ <Check className="h-4 w-4 text-green-500" />
+ ) : (
+ <Copy className="h-4 w-4 text-gray-500" />
+ )}
+ </button>
+ </div>
+ </dd>
+ </div>
+ </dl>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx b/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx
index 53ed6ae21..0620d28ac 100644
--- a/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx
+++ b/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx
@@ -4,7 +4,7 @@ import { CapCardAnalytics } from "@/app/dashboard/caps/components/CapCardAnalyti
import moment from "moment";
import { Tooltip } from "react-tooltip";
import { serverEnv, clientEnv, NODE_ENV } from "@cap/env";
-
+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
interface SharedCapCardProps {
cap: {
id: string;
@@ -26,6 +26,7 @@ export const SharedCapCard: React.FC<SharedCapCardProps> = ({
}) => {
const [isEditing, setIsEditing] = useState(false);
const [title, setTitle] = useState(cap.name);
+ const { activeSpace } = useSharedContext();
const displayCount =
analytics === 0
@@ -40,7 +41,9 @@ export const SharedCapCard: React.FC<SharedCapCardProps> = ({
<a
className="group block"
href={
- clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
+ activeSpace?.space.customDomain
+ ? `https://${activeSpace.space.customDomain}/${cap.id}`
+ : clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
? `https://cap.link/${cap.id}`
: `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${cap.id}`
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 105ab1588..5bff02c02 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -133,6 +133,8 @@ export const spaces = mysqlTable(
ownerId: nanoId("ownerId").notNull(),
metadata: json("metadata"),
allowedEmailDomain: varchar("allowedEmailDomain", { length: 255 }),
+ customDomain: varchar("customDomain", { length: 255 }),
+ domainVerified: timestamp("domainVerified"),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
workosOrganizationId: varchar("workosOrganizationId", { length: 255 }),
@@ -140,6 +142,7 @@ export const spaces = mysqlTable(
},
(table) => ({
ownerIdIndex: index("owner_id_idx").on(table.ownerId),
+ customDomainIndex: index("custom_domain_idx").on(table.customDomain),
})
);