The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
make AI implementation a bit more explicit, update ratelimiting setup
Steven Tey730e74323506
diff --git a/apps/web/app/api/ai/completion/route.ts b/apps/web/app/api/ai/completion/route.tsnew file mode 100644index 0000000000..d15477621e--- /dev/null+++ b/apps/web/app/api/ai/completion/route.ts@@ -0,0 +1,57 @@+import { anthropic } from "@/lib/anthropic";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { ratelimit } from "@/lib/upstash";+import { ipAddress } from "@vercel/edge";+import { AnthropicStream, StreamingTextResponse } from "ai";+import { getToken } from "next-auth/jwt";+import { NextRequest } from "next/server";++export const runtime = "edge";++export async function POST(req: NextRequest) {+ try {+ const session = await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ });+ if (!session?.email) {+ throw new DubApiError({+ code: "unauthorized",+ message: "You must be logged in to access this resource",+ });+ }++ const ip = ipAddress(req);+ const { success } = await ratelimit(5, "1 m").limit(`ai-completion:${ip}`);+ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Don't DDoS me pls 🥺",+ });+ }++ // Extract the `prompt` from the body of the request+ const { prompt } = await req.json();++ // Ask Claude for a streaming chat completion given the prompt+ const response = await anthropic.messages.create({+ messages: [+ {+ role: "user",+ content: prompt,+ },+ ],+ model: "claude-3-sonnet-20240229",+ stream: true,+ max_tokens: 300,+ });++ // Convert the response into a friendly text-stream+ const stream = AnthropicStream(response);++ // Respond with the stream+ return new StreamingTextResponse(stream);+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.tsindex e46739d145..4861045a34 100644--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts@@ -4,7 +4,6 @@ import {exceededLimitError,handleAndReturnErrorResponse,} from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/middleware/utils";import { getDomainOrLink, getWorkspaceViaEdge } from "@/lib/planetscale";import { ratelimit } from "@/lib/upstash";import {@@ -12,6 +11,7 @@ import {getAnalyticsEdgeQuerySchema,} from "@/lib/zod/schemas";import { DUB_DEMO_LINKS, DUB_WORKSPACE_ID, getSearchParams } from "@dub/utils";+import { ipAddress } from "@vercel/edge";import { NextResponse, type NextRequest } from "next/server";export const runtime = "edge";@@ -36,11 +36,11 @@ export const GET = async (if (demoLink) {// Rate limit in productionif (process.env.NODE_ENV !== "development") {- const identity_hash = await getIdentityHash(req);+ const ip = ipAddress(req);const { success } = await ratelimit(15,endpoint === "clicks" ? "10 s" : "1 m",- ).limit(`demo-analytics:${demoLink.id}:${identity_hash}:${endpoint}`);+ ).limit(`demo-analytics:${demoLink.id}:${ip}:${endpoint}`);if (!success) {throw new DubApiError({diff --git a/apps/web/app/api/auth/account-exists/route.ts b/apps/web/app/api/auth/account-exists/route.tsindex 3a86387676..3bca742f5e 100644--- a/apps/web/app/api/auth/account-exists/route.ts+++ b/apps/web/app/api/auth/account-exists/route.ts@@ -1,16 +1,14 @@import { isWhitelistedEmail } from "@/lib/edge-config";-import { getIdentityHash } from "@/lib/middleware/utils";import { DATABASE_URL, conn } from "@/lib/planetscale";import { ratelimit } from "@/lib/upstash";+import { ipAddress } from "@vercel/edge";import { NextRequest, NextResponse } from "next/server";export const runtime = "edge";export async function POST(req: NextRequest) {- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit(5, "1 m").limit(- `account-exists:${identity_hash}`,- );+ const ip = ipAddress(req);+ const { success } = await ratelimit(5, "1 m").limit(`account-exists:${ip}`);if (!success) {return new Response("Don't DDoS me pls 🥺", { status: 429 });}diff --git a/apps/web/app/api/links/iframeable/route.ts b/apps/web/app/api/links/iframeable/route.tsindex 73b3085434..852bbe3492 100644--- a/apps/web/app/api/links/iframeable/route.ts+++ b/apps/web/app/api/links/iframeable/route.ts@@ -1,8 +1,8 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { getDomainQuerySchema, getUrlQuerySchema } from "@/lib/zod/schemas";import { isIframeable } from "@dub/utils";+import { ipAddress } from "@vercel/edge";import { getToken } from "next-auth/jwt";import { NextRequest, NextResponse } from "next/server";@@ -21,10 +21,8 @@ export async function GET(req: NextRequest) {secret: process.env.NEXTAUTH_SECRET,});if (!session?.email) {- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit().limit(- `iframeable:${identity_hash}`,- );+ const ip = ipAddress(req);+ const { success } = await ratelimit().limit(`iframeable:${ip}`);if (!success) {throw new DubApiError({code: "rate_limit_exceeded",diff --git a/apps/web/app/api/links/random/route.ts b/apps/web/app/api/links/random/route.tsindex e7400a8a28..1715409c55 100644--- a/apps/web/app/api/links/random/route.ts+++ b/apps/web/app/api/links/random/route.ts@@ -1,9 +1,9 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/middleware/utils";import { getRandomKey } from "@/lib/planetscale";import { ratelimit } from "@/lib/upstash";import { domainKeySchema } from "@/lib/zod/schemas";import { getSearchParams } from "@dub/utils";+import { ipAddress } from "@vercel/edge";import { getToken } from "next-auth/jwt";import { NextRequest, NextResponse } from "next/server";@@ -23,8 +23,8 @@ export const GET = async (req: NextRequest) => {secret: process.env.NEXTAUTH_SECRET,});if (!session?.email) {- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit().limit(`metatags:${identity_hash}`);+ const ip = ipAddress(req);+ const { success } = await ratelimit().limit(`links-random:${ip}`);if (!success) {throw new DubApiError({code: "rate_limit_exceeded",diff --git a/apps/web/app/api/metatags/route.ts b/apps/web/app/api/metatags/route.tsindex 1096583d7f..fb11a72505 100644--- a/apps/web/app/api/metatags/route.ts+++ b/apps/web/app/api/metatags/route.ts@@ -1,7 +1,7 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { getUrlQuerySchema } from "@/lib/zod/schemas";+import { ipAddress } from "@vercel/edge";import { getToken } from "next-auth/jwt";import { NextRequest, NextResponse } from "next/server";import { getMetaTags } from "./utils";@@ -20,8 +20,8 @@ export async function GET(req: NextRequest) {secret: process.env.NEXTAUTH_SECRET,});if (!session?.email) {- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit().limit(`metatags:${identity_hash}`);+ const ip = ipAddress(req);+ const { success } = await ratelimit().limit(`metatags:${ip}`);if (!success) {throw new DubApiError({code: "rate_limit_exceeded",diff --git a/apps/web/app/api/providers/route.ts b/apps/web/app/api/providers/route.tsindex 863c9edd87..1d4772fe35 100644--- a/apps/web/app/api/providers/route.ts+++ b/apps/web/app/api/providers/route.ts@@ -1,8 +1,8 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";import { getUrlQuerySchema } from "@/lib/zod/schemas";import { fetchWithTimeout } from "@dub/utils";+import { ipAddress } from "@vercel/edge";import { getToken } from "next-auth/jwt";import { NextRequest, NextResponse } from "next/server";@@ -20,8 +20,8 @@ export async function GET(req: NextRequest) {secret: process.env.NEXTAUTH_SECRET,});if (!session?.email) {- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit().limit(`providers:${identity_hash}`);+ const ip = ipAddress(req);+ const { success } = await ratelimit().limit(`providers:${ip}`);if (!success) {return new Response("Don't DDoS me pls 🥺", { status: 429 });}diff --git a/apps/web/app/api/qr/route.tsx b/apps/web/app/api/qr/route.tsxindex 139de74abf..908a4c891a 100644--- a/apps/web/app/api/qr/route.tsx+++ b/apps/web/app/api/qr/route.tsx@@ -1,9 +1,9 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getIdentityHash } from "@/lib/middleware/utils";import { QRCodeSVG } from "@/lib/qr/utils";import { ratelimit } from "@/lib/upstash";import { getQRCodeQuerySchema } from "@/lib/zod/schemas";import { getSearchParams } from "@dub/utils";+import { ipAddress } from "@vercel/edge";import { getToken } from "next-auth/jwt";import { ImageResponse } from "next/og";import { NextRequest } from "next/server";@@ -18,8 +18,8 @@ export async function GET(req: NextRequest) {secret: process.env.NEXTAUTH_SECRET,});if (!session?.email) {- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit().limit(`qr:${identity_hash}`);+ const ip = ipAddress(req);+ const { success } = await ratelimit().limit(`qr:${ip}`);if (!success) {throw new DubApiError({code: "rate_limit_exceeded",diff --git a/apps/web/app/api/support/route.ts b/apps/web/app/api/support/route.tsindex fdf447fe8b..236dbf3219 100644--- a/apps/web/app/api/support/route.ts+++ b/apps/web/app/api/support/route.ts@@ -1,6 +1,6 @@-import { anthropic } from "@/lib/anthropic";import { withSession } from "@/lib/auth";import { plain, upsertPlainCustomer } from "@/lib/plain";+import z from "@/lib/zod";import { NextResponse } from "next/server";export const GET = withSession(async ({ session }) => {@@ -10,29 +10,17 @@ export const GET = withSession(async ({ session }) => {});});+const supportRequestQuerySchema = z.object({+ title: z.string().min(1),+ message: z.string().min(1),+ attachmentIds: z.array(z.string()),+});+// POST /api/support – file a support requestexport const POST = withSession(async ({ req, session }) => {- const { message, attachmentIds } = await req.json();-- let title = "New Support Request";-- try {- const { content } = await anthropic.messages.create({- messages: [- {- role: "user",- content: `Create a short but concise title that summarizes the following support request. Only return the generated title, and nothing else.-- ${message}`,- },- ],- model: "claude-3-sonnet-20240229",- max_tokens: 300,- });- title = content[0].text;- } catch (e) {- console.error("Error generating title:", e);- }+ const { title, message, attachmentIds } = supportRequestQuerySchema.parse(+ await req.json(),+ );const res = await plain.createThread({customerIdentifier: {diff --git a/apps/web/app/api/unsplash/search/route.ts b/apps/web/app/api/unsplash/search/route.tsindex 21fe87cf5e..57496c8daf 100644--- a/apps/web/app/api/unsplash/search/route.ts+++ b/apps/web/app/api/unsplash/search/route.ts@@ -1,5 +1,5 @@-import { getIdentityHash } from "@/lib/middleware/utils";import { ratelimit } from "@/lib/upstash";+import { ipAddress } from "@vercel/edge";import { NextResponse } from "next/server";import { unsplash } from "../utils";@@ -17,10 +17,8 @@ export async function GET(req: Request) {return new Response("Unsplash API key not found", { status: 400 });}- const identity_hash = await getIdentityHash(req);- const { success } = await ratelimit(10, "10 s").limit(- `unsplash:${identity_hash}`,- );+ const ip = ipAddress(req);+ const { success } = await ratelimit(10, "10 s").limit(`unsplash:${ip}`);if (!success) {return new Response("Don't DDoS me pls 🥺", { status: 429 });}diff --git a/apps/web/ui/layout/help/contact-form.tsx b/apps/web/ui/layout/help/contact-form.tsxindex cebaaaf072..e1461bdaa4 100644--- a/apps/web/ui/layout/help/contact-form.tsx+++ b/apps/web/ui/layout/help/contact-form.tsx@@ -1,9 +1,10 @@import { CheckCircleFill } from "@/ui/shared/icons";import { Button, LoadingSpinner, useEnterSubmit } from "@dub/ui";import { cn } from "@dub/utils";+import { useCompletion } from "ai/react";import { AnimatePresence, motion } from "framer-motion";import { ChevronLeft, Image, Trash2, UploadCloud } from "lucide-react";-import { Dispatch, SetStateAction, useRef, useState } from "react";+import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";import TextareaAutosize from "react-textarea-autosize";import { toast } from "sonner";@@ -13,9 +14,11 @@ export function ContactForm({setScreen: Dispatch<SetStateAction<"main" | "contact">>;}) {const [data, setData] = useState<{+ title: string | null;message: string;attachmentIds: string[];}>({+ title: null,message: "",attachmentIds: [],});@@ -80,6 +83,23 @@ export function ContactForm({const { handleKeyDown } = useEnterSubmit(formRef);+ const {+ completion,+ isLoading: generatingAIKey,+ complete,+ } = useCompletion({+ api: `/api/ai/completion`,+ onError: (error) => {+ toast.error(error.message);+ },+ });++ useEffect(() => {+ if (completion) {+ setData((prev) => ({ ...prev, title: completion }));+ }+ }, [completion]);+return (<div className="relative w-full px-3 pb-16 pt-5 sm:px-6"><button@@ -107,7 +127,7 @@ export function ContactForm({) : (<motion.formref={formRef}- className="mt-5"+ className="mt-5 grid gap-2"onSubmit={async (e) => {e.preventDefault();setFormStatus("loading");@@ -119,15 +139,34 @@ export function ContactForm({toast.error(res.error);setFormStatus("idle");} else {- setData({ message: "", attachmentIds: [] });+ setData({ title: null, message: "", attachmentIds: [] });setFormStatus("success");}}}initial={{ opacity: 1, y: 0 }}exit={{ opacity: 0, y: -10 }}>- <label className="block w-full">- <span className="block text-sm font-medium text-gray-700">+ {typeof data.title === "string" && (+ <label>+ <span className="text-sm font-medium text-gray-700">+ Issue title+ </span>+ <input+ name="title"+ required+ placeholder="E.g. Custom domain not working"+ autoComplete="off"+ value={data.title}+ onChange={(e) =>+ setData((prev) => ({ ...prev, title: e.target.value }))+ }+ className="mt-1 block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ />+ </label>+ )}++ <label>+ <span className="text-sm font-medium text-gray-700">Describe the issue</span><TextareaAutosize@@ -135,8 +174,16 @@ export function ContactForm({requiredplaceholder="E.g. My custom domain is not working."minRows={8}+ autoFocusautoComplete="off"value={data.message}+ onBlur={() => {+ if (!data.title && data.message) {+ complete(`Create a short but concise title that summarizes the following support request. Only return the generated title, and nothing else. Don't use quotation marks++ ${data.message}`);+ }+ }}onChange={(e) =>setData((prev) => ({ ...prev, message: e.target.value }))}@@ -149,7 +196,7 @@ export function ContactForm({/></label>- <div className="mt-2 grid w-full gap-2">+ <div className="grid w-full gap-2">{images.map((image) => (<divkey={image.attachmentId}@@ -187,7 +234,7 @@ export function ContactForm({<labelhtmlFor="image"- className="group relative mt-1 flex aspect-[5/1] w-full cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-gray-300 bg-white transition-all"+ className="group relative flex aspect-[5/1] w-full cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-gray-300 bg-white transition-all"><divclassName="absolute z-[5] h-full w-full rounded-md"