The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add PublishableKeyForm
Steven Tey59c7c62df4ca
diff --git a/apps/web/app/(ee)/api/track/sale/client/route.ts b/apps/web/app/(ee)/api/track/sale/client/route.tsnew file mode 100644index 0000000000..f0943eeece--- /dev/null+++ b/apps/web/app/(ee)/api/track/sale/client/route.ts@@ -0,0 +1,56 @@+import { trackSale } from "@/lib/api/conversions/track-sale";+import { DubApiError } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { withPublishableKey } from "@/lib/auth/publishable-key";+import { trackSaleRequestSchema } from "@/lib/zod/schemas/sales";+import { NextResponse } from "next/server";++// POST /api/track/sale/client – Track a sale conversion event on the client side+export const POST = withPublishableKey(+ async ({ req, workspace }) => {+ const body = await parseRequestBody(req);++ let {+ customerExternalId,+ paymentProcessor,+ invoiceId,+ amount,+ currency,+ metadata,+ eventName,+ leadEventName,+ } = trackSaleRequestSchema.parse(body);++ if (!customerExternalId) {+ throw new DubApiError({+ code: "bad_request",+ message: "customerExternalId is required",+ });+ }++ const response = await trackSale({+ customerExternalId,+ amount,+ currency,+ eventName,+ paymentProcessor,+ invoiceId,+ leadEventName,+ metadata,+ workspace,+ rawBody: body,+ });++ return NextResponse.json(response);+ },+ {+ requiredPlan: [+ "business",+ "business plus",+ "business extra",+ "business max",+ "advanced",+ "enterprise",+ ],+ },+);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.tsindex f6d4e731a8..0f0580a56c 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts@@ -58,8 +58,14 @@ export const GET = withWorkspace(// PATCH /api/workspaces/[idOrSlug] – update a specific workspace by id or slugexport const PATCH = withWorkspace(async ({ req, workspace }) => {- const { name, slug, logo, conversionEnabled, allowedHostnames } =- await updateWorkspaceSchema.parseAsync(await parseRequestBody(req));+ const {+ name,+ slug,+ logo,+ conversionEnabled,+ allowedHostnames,+ publishableKey,+ } = await updateWorkspaceSchema.parseAsync(await parseRequestBody(req));if (["free", "pro"].includes(workspace.plan) && conversionEnabled) {throw new DubApiError({@@ -92,6 +98,7 @@ export const PATCH = withWorkspace(...(validHostnames !== undefined && {allowedHostnames: validHostnames,}),+ ...(publishableKey !== undefined && { publishableKey }),},include: {domains: {diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/allowed-hostnames.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/allowed-hostnames-form.tsxsimilarity index 98%rename from apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/allowed-hostnames.tsxrename to apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/allowed-hostnames-form.tsxindex cd368aeab7..c48bcb29f4 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/allowed-hostnames.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/allowed-hostnames-form.tsx@@ -8,7 +8,7 @@ import Link from "next/link";import { useState } from "react";import { toast } from "sonner";-export const AllowedHostnames = () => {+export const AllowedHostnamesForm = () => {const { allowedHostnames, loading } = useWorkspace();return (@@ -123,7 +123,7 @@ const AddHostnameForm = () => {onClick={addHostname}disabled={!isValidHostname(hostname) || hostname.length === 0}loading={processing}- className="w-40"+ className="w-fit"disabledTooltip={permissionsError || undefined}/></form>diff --git a/apps/web/ui/workspaces/conversion-tracking-toggle.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/conversion-tracking-toggle.tsxsimilarity index 100%rename from apps/web/ui/workspaces/conversion-tracking-toggle.tsxrename to apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/conversion-tracking-toggle.tsxdiff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/page.tsxindex 9fdae2381b..94b5956146 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/page.tsx@@ -1,10 +1,12 @@-import { ConversionTrackingToggle } from "@/ui/workspaces/conversion-tracking-toggle";-import { AllowedHostnames } from "./allowed-hostnames";+import { PublishableKeyForm } from "app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/publishable-key-form";+import { AllowedHostnamesForm } from "./allowed-hostnames-form";+import { ConversionTrackingToggle } from "./conversion-tracking-toggle";export default function WorkspaceAnalytics() {return (<div className="flex h-full flex-col gap-10">- <AllowedHostnames />+ <AllowedHostnamesForm />+ <PublishableKeyForm /><ConversionTrackingToggle /></div>);diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/publishable-key-form.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/publishable-key-form.tsxnew file mode 100644index 0000000000..71cd4070b1--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/analytics/publishable-key-form.tsx@@ -0,0 +1,163 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import { useConfirmModal } from "@/ui/modals/confirm-modal";+import { Button, CopyButton } from "@dub/ui";+import { nanoid } from "@dub/utils";+import Link from "next/link";+import { useState } from "react";+import { toast } from "sonner";++export const PublishableKeyForm = () => {+ const { id, publishableKey, mutate, role } = useWorkspace();+ const [processing, setProcessing] = useState(false);++ const { error: permissionsError } = clientAccessCheck({+ action: "workspaces.write",+ role,+ customPermissionDescription: "manage publishable keys",+ });++ const handleGenerateKey = async () => {+ setProcessing(true);++ const newPublishableKey = `dub_pk_${nanoid(24)}`;++ const response = await fetch(`/api/workspaces/${id}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ publishableKey: newPublishableKey,+ }),+ });++ if (response.ok) {+ toast.success("Publishable key generated successfully.");+ } else {+ const { error } = await response.json();+ toast.error(error.message);+ }++ mutate();+ setProcessing(false);+ };++ const handleRevokeKey = async () => {+ setProcessing(true);++ const response = await fetch(`/api/workspaces/${id}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ publishableKey: null,+ }),+ });++ if (response.ok) {+ toast.success("Publishable key revoked successfully.");+ } else {+ const { error } = await response.json();+ toast.error(error.message);+ }++ mutate();+ setProcessing(false);+ };++ const {+ setShowConfirmModal: setShowGenerateModal,+ confirmModal: generateModal,+ } = useConfirmModal({+ title: "Generate New Publishable Key",+ description:+ "Are you sure you want to generate a new publishable key? This will invalidate the existing key.",+ confirmText: "Generate Key",+ onConfirm: handleGenerateKey,+ });++ const { setShowConfirmModal: setShowRevokeModal, confirmModal: revokeModal } =+ useConfirmModal({+ title: "Revoke Publishable Key",+ description:+ "Are you sure you want to revoke the publishable key? This action cannot be undone.",+ confirmText: "Revoke Key",+ onConfirm: handleRevokeKey,+ });++ return (+ <div className="rounded-lg border border-neutral-200 p-5">+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">+ <div className="flex flex-col gap-1">+ <h2 className="text-xl font-semibold tracking-tight text-black">+ Publishable Key+ </h2>+ <p className="text-sm text-neutral-500">+ Use this key for client-side tracking and analytics integration.{" "}+ <Link+ href="https://dub.co/docs/api-reference/authentication#publishable-key"+ target="_blank"+ className="underline transition-colors hover:text-neutral-800"+ >+ Learn more.+ </Link>+ </p>+ </div>+ {!publishableKey && (+ <Button+ text="Generate Key"+ className="h-8 w-fit px-3 sm:shrink-0"+ onClick={() => setShowGenerateModal(true)}+ loading={processing}+ disabledTooltip={permissionsError || undefined}+ />+ )}+ </div>++ {publishableKey ? (+ <div className="mt-5 space-y-3">+ <div className="flex flex-col gap-3 rounded-md border border-neutral-200 p-3 sm:flex-row sm:items-center sm:justify-between sm:gap-2">+ <div className="flex min-w-0 items-center gap-2">+ <code className="min-w-0 flex-1 truncate font-mono text-sm text-neutral-800">+ {publishableKey}+ </code>+ <CopyButton value={publishableKey} className="shrink-0" />+ </div>+ <div className="flex items-center gap-2 sm:shrink-0">+ <Button+ text="Regenerate"+ variant="secondary"+ onClick={() => setShowGenerateModal(true)}+ loading={processing}+ disabledTooltip={permissionsError || undefined}+ className="h-7 flex-1 px-2 text-xs sm:flex-none"+ />+ <Button+ text="Revoke"+ variant="danger"+ onClick={() => setShowRevokeModal(true)}+ loading={processing}+ disabledTooltip={permissionsError || undefined}+ className="h-7 flex-1 px-2 text-xs sm:flex-none"+ />+ </div>+ </div>+ </div>+ ) : (+ <div className="mt-5">+ <div className="flex items-center justify-center rounded-md border border-dashed border-neutral-300 p-8">+ <p className="text-sm text-neutral-500">+ No publishable key configured+ </p>+ </div>+ </div>+ )}+ {generateModal}+ {revokeModal}+ </div>+ );+};diff --git a/apps/web/lib/auth/publishable-key.ts b/apps/web/lib/auth/publishable-key.tsindex 4ae0f88426..4899db21f2 100644--- a/apps/web/lib/auth/publishable-key.ts+++ b/apps/web/lib/auth/publishable-key.ts@@ -47,11 +47,16 @@ export const withPublishableKey = (if (!authorizationHeader.includes("Bearer ")) {throw new DubApiError({code: "bad_request",- message:- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",+ message: "Invalid or missing publishable key.",});}const publishableKey = authorizationHeader.replace("Bearer ", "");+ if (!publishableKey.startsWith("dub_pk_")) {+ throw new DubApiError({+ code: "bad_request",+ message: "Invalid or missing publishable key.",+ });+ }const { success, limit, reset, remaining } = await ratelimit(600,@@ -72,7 +77,7 @@ export const withPublishableKey = (});}- const workspace = await prisma.project.findFirst({+ const workspace = await prisma.project.findUnique({where: {publishableKey,},@@ -81,7 +86,8 @@ export const withPublishableKey = (if (!workspace) {throw new DubApiError({code: "unauthorized",- message: "Unauthorized: Invalid Dub publishable key.",+ message:+ "Unauthorized: Workspace does not have a publishable key configured.",});}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex d3c45167c9..d03079902b 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -185,6 +185,7 @@ export interface ExtendedWorkspaceProps extends WorkspaceProps {users: (WorkspaceProps["users"][number] & {workspacePreferences?: z.infer<typeof workspacePreferencesSchema>;})[];+ publishableKey: string | null;}export type WorkspaceWithUsers = Omit<WorkspaceProps, "domains">;diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.tsindex 9887849fee..8bc5e0f439 100644--- a/apps/web/lib/zod/schemas/workspaces.ts+++ b/apps/web/lib/zod/schemas/workspaces.ts@@ -147,6 +147,7 @@ export const createWorkspaceSchema = z.object({export const updateWorkspaceSchema = createWorkspaceSchema.partial().extend({allowedHostnames: z.array(z.string()).optional(),+ publishableKey: z.string().nullish(),});export const notificationTypes = z.enum([@@ -168,6 +169,7 @@ export const WorkspaceSchemaExtended = WorkspaceSchema.extend({workspacePreferences: z.record(z.any()).nullish(),}),),+ publishableKey: z.string().nullable(),});export const OnboardingUsageSchema = z.object({