The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
offload more stuff to waitUntil
Steven Teya6dc9d5f9cf4
diff --git a/apps/web/app/api/admin/ban/route.ts b/apps/web/app/api/admin/ban/route.tsindex dd70bb0cf6..bcbbdf5664 100644--- a/apps/web/app/api/admin/ban/route.ts+++ b/apps/web/app/api/admin/ban/route.ts@@ -4,7 +4,7 @@ import { updateConfig } from "@/lib/edge-config";import { unsubscribe } from "@/lib/flodesk";import prisma from "@/lib/prisma";import { storage } from "@/lib/storage";-import { get } from "@vercel/edge-config";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// POST /api/admin/ban@@ -41,34 +41,32 @@ export const POST = withAdmin(async ({ req }) => {return new Response("No user found", { status: 404 });}- const blacklistedEmails = (await get("emails")) as string[];+ waitUntil(+ Promise.allSettled([+ ...user.projects.map(({ project }) =>+ deleteWorkspaceAdmin({+ id: project.id,+ slug: project.slug,+ stripeId: project.stripeId || null,+ logo: project.logo || null,+ }),+ ),- await Promise.allSettled(- user.projects.map(({ project }) =>- deleteWorkspaceAdmin({- id: project.id,- slug: project.slug,- stripeId: project.stripeId || null,- logo: project.logo || null,+ prisma.user.delete({+ where: {+ id: user.id,+ },+ }),+ // if the user has a custom avatar, delete it+ user.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&+ storage.delete(`avatars/${user.id}`),+ unsubscribe(email),+ updateConfig({+ key: "emails",+ value: email,}),- ),+ ]),);- await Promise.allSettled([- prisma.user.delete({- where: {- id: user.id,- },- }),- // if the user has a custom avatar, delete it- user.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&- storage.delete(`avatars/${user.id}`),- unsubscribe(email),- updateConfig({- key: "emails",- value: email,- }),- ]);-return NextResponse.json({ success: true });});diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.tsindex 9e03fa5872..00789598ca 100644--- a/apps/web/app/api/domains/[domain]/route.ts+++ b/apps/web/app/api/domains/[domain]/route.ts@@ -10,6 +10,7 @@ import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import prisma from "@/lib/prisma";import { DomainSchema, updateDomainBodySchema } from "@/lib/zod/schemas";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// GET /api/domains/[domain] – get a workspace's domain@@ -76,40 +77,42 @@ export const PATCH = withWorkspace(}}- const response = await Promise.all([- prisma.domain.update({- where: {- slug: domain,- },- data: {- slug: newDomain,- type,- archived,- ...(placeholder && { placeholder }),+ const response = await prisma.domain.update({+ where: {+ slug: domain,+ },+ data: {+ slug: newDomain,+ type,+ archived,+ ...(placeholder && { placeholder }),+ ...(workspace.plan !== "free" && {+ target,+ expiredUrl,+ }),+ },+ });++ waitUntil(+ Promise.all([+ setRootDomain({+ id: response.id,+ domain,...(workspace.plan !== "free" && {- target,- expiredUrl,+ url: target || undefined,}),- },- }),- // remove old domain from Vercel- newDomain !== domain && removeDomainFromVercel(domain),- ]);-- await setRootDomain({- id: response[0].id,- domain,- ...(workspace.plan !== "free" && {- url: target || undefined,- }),- rewrite: type === "rewrite",- ...(newDomain !== domain && {- newDomain,- }),- projectId: workspace.id,- });+ rewrite: type === "rewrite",+ ...(newDomain !== domain && {+ newDomain,+ }),+ projectId: workspace.id,+ }),+ // remove old domain from Vercel+ newDomain !== domain && removeDomainFromVercel(domain),+ ]),+ );- return NextResponse.json(DomainSchema.parse(response[0]));+ return NextResponse.json(DomainSchema.parse(response));},{domainChecks: true,diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.tsindex ac4f16e26e..4747688a85 100644--- a/apps/web/app/api/domains/route.ts+++ b/apps/web/app/api/domains/route.ts@@ -9,6 +9,7 @@ import { withWorkspace } from "@/lib/auth";import prisma from "@/lib/prisma";import z from "@/lib/zod";import { DomainSchema, addDomainBodySchema } from "@/lib/zod/schemas";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// GET /api/domains – get all domains for a workspace@@ -77,15 +78,17 @@ export const POST = withWorkspace(async ({ req, workspace }) => {},});- await setRootDomain({- id: response.id,- domain,- projectId: workspace.id,- ...(workspace.plan !== "free" && {- url: target || undefined,+ waitUntil(+ setRootDomain({+ id: response.id,+ domain,+ projectId: workspace.id,+ ...(workspace.plan !== "free" && {+ url: target || undefined,+ }),+ rewrite: type === "rewrite",}),- rewrite: type === "rewrite",- });+ );return NextResponse.json(DomainSchema.parse(response), { status: 201 });});diff --git a/apps/web/app/api/workspaces/route.ts b/apps/web/app/api/workspaces/route.tsindex 10a0a9551d..7f4576a147 100644--- a/apps/web/app/api/workspaces/route.ts+++ b/apps/web/app/api/workspaces/route.ts@@ -9,6 +9,7 @@ import { checkIfUserExists } from "@/lib/planetscale";import prisma from "@/lib/prisma";import { WorkspaceSchema, createWorkspaceSchema } from "@/lib/zod/schemas";import { FREE_WORKSPACES_LIMIT, nanoid } from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// GET /api/workspaces - get all projects for the current user@@ -104,57 +105,59 @@ export const POST = withSession(async ({ req, session }) => {});}- const [projectResponse, domainRepsonse] = await Promise.all([- prisma.project.create({- data: {- name,- slug,- users: {- create: {- userId: session.user.id,- role: "owner",- },- },- ...(domain && {- domains: {- create: {- slug: domain,- primary: true,- },- },- }),- billingCycleStart: new Date().getDate(),- inviteCode: nanoid(24),- defaultDomains: {- create: {}, // by default, we give users all the default domains when they create a project+ const projectResponse = await prisma.project.create({+ data: {+ name,+ slug,+ users: {+ create: {+ userId: session.user.id,+ role: "owner",},},- include: {+ ...(domain && {domains: {- select: {- id: true,- slug: true,+ create: {+ slug: domain,primary: true,},},- users: {- select: {- role: true,- },+ }),+ billingCycleStart: new Date().getDate(),+ inviteCode: nanoid(24),+ defaultDomains: {+ create: {}, // by default, we give users all the default domains when they create a project+ },+ },+ include: {+ domains: {+ select: {+ id: true,+ slug: true,+ primary: true,},},- }),- domain && addDomainToVercel(domain),- ]);+ users: {+ select: {+ role: true,+ },+ },+ },+ });- // if domain is specified and it was successfully added to Vercel- // update it in Redis cache- if (domain && domainRepsonse && !domainRepsonse.error) {- await setRootDomain({- id: projectResponse.domains[0].id,- domain,- projectId: projectResponse.id,- });+ if (domain) {+ waitUntil(+ (async () => {+ const domainRepsonse = await addDomainToVercel(domain);+ if (!domainRepsonse.error) {+ await setRootDomain({+ id: projectResponse.domains[0].id,+ domain,+ projectId: projectResponse.id,+ });+ }+ })(),+ );}const response = {diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.tsindex 282f33a0cb..1a59c7198c 100644--- a/apps/web/lib/api/domains.ts+++ b/apps/web/lib/api/domains.ts@@ -6,6 +6,7 @@ import {isIframeable,validDomainRegex,} from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { storage } from "../storage";import { recordLink } from "../tinybird";@@ -208,13 +209,7 @@ export async function setRootDomain({}/* Delete a domain and all links & images associated with it */-export async function deleteDomainAndLinks(- domain: string,- {- // Note: in certain cases, we don't need to remove the domain from the Prisma- skipPrismaDelete = false,- } = {},-) {+export async function deleteDomainAndLinks(domain: string) {const [domainData, allLinks] = await Promise.all([prisma.domain.findUnique({where: {@@ -243,34 +238,39 @@ export async function deleteDomainAndLinks(if (!domainData) {return null;}- return await Promise.allSettled([- // delete all links from redis- redis.del(domain.toLowerCase()),- // record deletes in tinybird for domain & links- recordLink({- link: {- id: domainData.id,- domain,- key: "_root",- url: domainData.target || "",- projectId: domainData.projectId,- },- deleted: true,- }),- ...allLinks.flatMap((link) => [++ const response = await prisma.domain.delete({+ where: {+ slug: domain,+ },+ });++ waitUntil(+ Promise.allSettled([+ // delete all links from redis+ redis.del(domain.toLowerCase()),+ // record deletes in tinybird for domain & linksrecordLink({- link,+ link: {+ id: domainData.id,+ domain,+ key: "_root",+ url: domainData.target || "",+ projectId: domainData.projectId,+ },deleted: true,}),- storage.delete(`images/${link.id}`),+ ...allLinks.flatMap((link) => [+ recordLink({+ link,+ deleted: true,+ }),+ storage.delete(`images/${link.id}`),+ ]),+ // remove the domain from Vercel+ removeDomainFromVercel(domain),]),- // remove the domain from Vercel- removeDomainFromVercel(domain),- !skipPrismaDelete &&- prisma.domain.delete({- where: {- slug: domain,- },- }),- ]);+ );++ return response;}diff --git a/apps/web/lib/api/workspaces.ts b/apps/web/lib/api/workspaces.tsindex ea249b107f..0d7d7aca54 100644--- a/apps/web/lib/api/workspaces.ts+++ b/apps/web/lib/api/workspaces.ts@@ -7,6 +7,7 @@ import {LEGAL_USER_ID,LEGAL_WORKSPACE_ID,} from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { WorkspaceProps } from "../types";import { redis } from "../upstash";@@ -39,58 +40,50 @@ export async function deleteWorkspace(}),]);- const linksByDomain: Record<string, string[]> = {};- defaultDomainLinks.forEach(async (link) => {- const { domain, key } = link;-- if (!linksByDomain[domain]) {- linksByDomain[domain] = [];- }- linksByDomain[domain].push(key.toLowerCase());+ const response = await prisma.project.delete({+ where: {+ slug: workspace.slug,+ },});- const pipeline = redis.pipeline();+ waitUntil(+ (async () => {+ const linksByDomain: Record<string, string[]> = {};+ defaultDomainLinks.forEach(async (link) => {+ const { domain, key } = link;- Object.entries(linksByDomain).forEach(([domain, links]) => {- pipeline.hdel(domain.toLowerCase(), ...links);- });+ if (!linksByDomain[domain]) {+ linksByDomain[domain] = [];+ }+ linksByDomain[domain].push(key.toLowerCase());+ });- // delete all domains, links, and uploaded images associated with the workspace- const deleteDomainsLinksResponse = await Promise.allSettled([- ...customDomains.map(({ slug }) =>- deleteDomainAndLinks(slug, {- // here, we don't need to delete in prisma because we're deleting the workspace later and have onDelete: CASCADE set- skipPrismaDelete: true,- }),- ),- // delete all default domain links from redis- pipeline.exec(),- // remove all images from R2- ...defaultDomainLinks.map(({ id, proxy, image }) =>- proxy && image?.startsWith(process.env.STORAGE_BASE_URL as string)- ? storage.delete(`images/${id}`)- : Promise.resolve(),- ),- ]);+ const pipeline = redis.pipeline();- const deleteWorkspaceResponse = await Promise.all([- // delete workspace logo if it's a custom logo stored in R2- workspace.logo?.startsWith(process.env.STORAGE_BASE_URL as string) &&- storage.delete(`logos/${workspace.id}`),- // if they have a Stripe subscription, cancel it- workspace.stripeId && cancelSubscription(workspace.stripeId),- // delete the workspace- prisma.project.delete({- where: {- slug: workspace.slug,- },- }),- ]);+ Object.entries(linksByDomain).forEach(([domain, links]) => {+ pipeline.hdel(domain.toLowerCase(), ...links);+ });- return {- deleteDomainsLinksResponse,- deleteWorkspaceResponse,- };+ await Promise.allSettled([+ ...customDomains.map(({ slug }) => deleteDomainAndLinks(slug)),+ // delete all default domain links from redis+ pipeline.exec(),+ // remove all images from R2+ ...defaultDomainLinks.map(({ id, proxy, image }) =>+ proxy && image?.startsWith(process.env.STORAGE_BASE_URL as string)+ ? storage.delete(`images/${id}`)+ : Promise.resolve(),+ ),+ // delete workspace logo if it's a custom logo stored in R2+ workspace.logo?.startsWith(process.env.STORAGE_BASE_URL as string) &&+ storage.delete(`logos/${workspace.id}`),+ // if they have a Stripe subscription, cancel it+ workspace.stripeId && cancelSubscription(workspace.stripeId),+ ]);+ })(),+ );++ return response;}export async function deleteWorkspaceAdmin(@@ -121,12 +114,7 @@ export async function deleteWorkspaceAdmin(// delete all domains, links, and uploaded images associated with the workspaceconst deleteDomainsLinksResponse = await Promise.allSettled([- ...customDomains.map(({ slug }) =>- deleteDomainAndLinks(slug, {- // here, we don't need to delete in prisma because we're deleting the workspace later and have onDelete: CASCADE set- skipPrismaDelete: true,- }),- ),+ ...customDomains.map(({ slug }) => deleteDomainAndLinks(slug)),]);const deleteWorkspaceResponse = await Promise.all([diff --git a/apps/web/ui/modals/add-edit-domain-modal/index.tsx b/apps/web/ui/modals/add-edit-domain-modal/index.tsxindex 0db4192722..5dc0813a88 100644--- a/apps/web/ui/modals/add-edit-domain-modal/index.tsx+++ b/apps/web/ui/modals/add-edit-domain-modal/index.tsx@@ -169,7 +169,7 @@ function AddEditDomainModal({type="button"onClick={() => {window.confirm(- "Warning: Changing your workspace's domain will break all existing short links and reset their analytics. Are you sure you want to continue?",+ "Warning: Changing your workspace's domain will break all existing short links. Are you sure you want to continue?",) && setLockDomain(false);}}>