The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
migrate domain redis too
Steven Teyf1fcc6dfb310
diff --git a/apps/web/app/admin.dub.co/actions.ts b/apps/web/app/admin.dub.co/actions.tsindex 10a4283121..f79c92653d 100644--- a/apps/web/app/admin.dub.co/actions.ts+++ b/apps/web/app/admin.dub.co/actions.ts@@ -3,7 +3,6 @@import { deleteProject } from "@/lib/api/projects";import { getSession, hashToken } from "@/lib/auth";import prisma from "@/lib/prisma";-import { redis } from "@/lib/upstash";import {DUB_PROJECT_ID,LEGAL_USER_ID,@@ -359,10 +358,6 @@ export async function deleteAndBlacklistLink(data: FormData) {const blacklistedDomains = (await get("domains")) as string[];const response = await Promise.allSettled([- redis.set(`${SHORT_DOMAIN}:${key}`, {- url: encodeURIComponent(url),- banned: true,- }),prisma.link.update({where: {domain_key: {@@ -372,6 +367,7 @@ export async function deleteAndBlacklistLink(data: FormData) {},data: {userId: LEGAL_USER_ID,+ projectId: LEGAL_PROJECT_ID,},}),fetch(diff --git a/apps/web/app/api/callback/stripe/route.ts b/apps/web/app/api/callback/stripe/route.tsindex 99c885afb3..7c44516b99 100644--- a/apps/web/app/api/callback/stripe/route.ts+++ b/apps/web/app/api/callback/stripe/route.ts@@ -192,6 +192,7 @@ export const POST = async (req: Request) => {stripeId,},select: {+ id: true,slug: true,domains: true,users: {@@ -225,7 +226,11 @@ export const POST = async (req: Request) => {const pipeline = redis.pipeline();// remove root domain redirect for all domainsprojectDomains.forEach((domain) => {- pipeline.del(`root:${domain}`);+ pipeline.hset(domain, {+ _root: {+ projectId: project.id,+ },+ });});await Promise.allSettled([diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/route.tsindex 189c8f2fae..72bad75a7f 100644--- a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts@@ -4,7 +4,6 @@ import { redis } from "@/lib/upstash";import {addDomainToVercel,changeDomainForImages,- changeDomainForLinks,deleteDomainAndLinks,removeDomainFromVercel,setRootDomain,@@ -72,49 +71,7 @@ export const PUT = withAuth(async ({ req, project, domain }) => {}}- const response = await Promise.allSettled([- // if the domain is being changed, we need to:- // 1. Remove the old domain from Vercel- // 2. Add the new domain to Vercel- // 3. Update all links in the project to point to the new domain- // 4. Update all images in the project to point to the new domain- ...(newDomain !== domain- ? [- removeDomainFromVercel(domain),- changeDomainForLinks(domain, newDomain),- changeDomainForImages(domain, newDomain),- ]- : []),- /*- if the project is not a free plan:- - if the domain is being set:- - Set the root domain to the target in Redis- - if the domain is being changed, also change the root domain key in Redis- - if the domain is being unset:- - delete the root domain key in Redis- */- project.plan !== "free" &&- (target- ? setRootDomain({- domain,- target,- rewrite: type === "rewrite",- ...(newDomain !== domain && {- newDomain,- }),- })- : redis.del(`root:${domain}`)),- // if the domain is being set as the primary domain, set the current primary domain to false- primary &&- prisma.domain.updateMany({- where: {- projectId: project.id,- primary: true,- },- data: {- primary: false,- },- }),+ const response = await Promise.all([// Update the domain in the database along with its primary statusprisma.domain.update({where: {@@ -139,8 +96,38 @@ export const PUT = withAuth(async ({ req, project, domain }) => {archived,},}),+ ...(newDomain !== domain+ ? [+ removeDomainFromVercel(domain),+ changeDomainForImages(domain, newDomain),+ ]+ : []),+ // if the domain is being set as the primary domain, set the current primary domain to false+ primary &&+ prisma.domain.updateMany({+ where: {+ projectId: project.id,+ primary: true,+ },+ data: {+ primary: false,+ },+ }),]);+ await setRootDomain({+ id: response[0].id,+ domain,+ ...(project.plan !== "free" && {+ url: target,+ }),+ rewrite: type === "rewrite",+ ...(newDomain !== domain && {+ newDomain,+ }),+ projectId: project.id,+ });+return NextResponse.json(response);});diff --git a/apps/web/app/api/projects/[slug]/domains/route.ts b/apps/web/app/api/projects/[slug]/domains/route.tsindex 26f18b262c..1a61b0c865 100644--- a/apps/web/app/api/projects/[slug]/domains/route.ts+++ b/apps/web/app/api/projects/[slug]/domains/route.ts@@ -58,13 +58,17 @@ export const POST = withAuth(async ({ req, project }) => {3. If the domain is being set as the primary domain, set all other domains to not be the primary domain4. Add the domain to the database along with its primary status*/- const response = await Promise.allSettled([- target &&- setRootDomain({- domain,+ const response = await Promise.all([+ prisma.domain.create({+ data: {+ slug: domain,target,- rewrite: type === "rewrite",- }),+ type,+ projectId: project.id,+ primary: primary || project.domains.length === 0,+ archived,+ },+ }),primary &&prisma.domain.updateMany({where: {@@ -75,17 +79,17 @@ export const POST = withAuth(async ({ req, project }) => {primary: false,},}),- prisma.domain.create({- data: {- slug: domain,- target,- type,- projectId: project.id,- primary,- archived,- },- }),]);+ await setRootDomain({+ id: response[0].id,+ domain,+ projectId: project.id,+ ...(project.plan !== "free" && {+ url: target,+ }),+ rewrite: type === "rewrite",+ });+return NextResponse.json(response);});diff --git a/apps/web/app/api/projects/route.ts b/apps/web/app/api/projects/route.tsindex cc11256bc3..74e6f311ab 100644--- a/apps/web/app/api/projects/route.ts+++ b/apps/web/app/api/projects/route.ts@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";import {addDomainToVercel,domainExists,+ setRootDomain,validateDomain,} from "@/lib/api/domains";import { withSession } from "@/lib/auth";@@ -111,7 +112,7 @@ export const POST = withSession(async ({ req, session }) => {{ status: 422 },);}- const response = await Promise.allSettled([+ const response = await Promise.all([prisma.project.create({data: {name,@@ -132,9 +133,18 @@ export const POST = withSession(async ({ req, session }) => {}),billingCycleStart: new Date().getDate(),},+ include: {+ domains: true,+ },}),addDomainToVercel(domain),]);+ await setRootDomain({+ id: response[0].domains[0].id,+ domain,+ projectId: response[0].id,+ });+return NextResponse.json(response);});diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.tsindex 732f19e61e..96352cc194 100644--- a/apps/web/lib/api/domains.ts+++ b/apps/web/lib/api/domains.ts@@ -155,58 +155,40 @@ export const verifyDomain = async (domain: string) => {};export async function setRootDomain({+ id,domain,- target,+ projectId,+ url,rewrite,newDomain,}: {+ id: string;domain: string;- target: string;- rewrite: boolean;+ projectId: string;+ url?: string;+ rewrite?: boolean;newDomain?: string; // if the domain is changed, this will be the new domain}) {if (newDomain) {- const pipeline = redis.pipeline();- pipeline.del(`root:${domain}`);- pipeline.set(`root:${newDomain}`, {- target,- ...(rewrite && {- rewrite: true,- iframeable: await isIframeable({ url: target, requestDomain: domain }),- }),- });- return await pipeline.exec();- } else {- await redis.set(`root:${domain}`, {- target,- ...(rewrite && {- rewrite: true,- iframeable: await isIframeable({ url: target, requestDomain: domain }),- }),- });+ await redis.rename(domain, newDomain);}-}--/* Change the domain for every link and its respective stats when the project domain is changed */-export async function changeDomainForLinks(domain: string, newDomain: string) {- const links = await prisma.link.findMany({- where: {- domain,- },- select: {- key: true,+ return await redis.hset(newDomain || domain, {+ _root: {+ id,+ ...(url && {+ url,+ }),+ ...(url &&+ rewrite && {+ rewrite: true,+ iframeable: await isIframeable({+ url,+ requestDomain: domain,+ }),+ }),+ projectId,},});- if (links.length === 0) return null;- const pipeline = redis.pipeline();- links.forEach(({ key }) => {- pipeline.rename(`${domain}:${key}`, `${newDomain}:${key}`);- });- try {- return await pipeline.exec();- } catch (e) {- return null;- }}/* Change the domain for all images for a given project on Cloudinary */diff --git a/apps/web/lib/api/projects.ts b/apps/web/lib/api/projects.tsindex 3131745cf9..40490a2910 100644--- a/apps/web/lib/api/projects.ts+++ b/apps/web/lib/api/projects.ts@@ -33,9 +33,20 @@ export async function deleteProject(}),]);+ const linksByDomain: Record<string, string[]> = {};+ defaultDomainLinks.forEach(async (link) => {+ const { domain, key } = link;++ if (!linksByDomain[domain]) {+ linksByDomain[domain] = [];+ }+ linksByDomain[domain].push(key.toLowerCase());+ });+const pipeline = redis.pipeline();- defaultDomainLinks.forEach(({ domain, key }) => {- pipeline.del(`${domain}:${key}`);++ Object.entries(linksByDomain).forEach(([domain, links]) => {+ pipeline.hdel(domain, ...links);});// delete all domains, links, and uploaded images associated with the project@@ -46,7 +57,8 @@ export async function deleteProject(skipPrismaDelete: true,}),),- pipeline.exec(), // delete all default domain links from redis+ // delete all default domain links from redis+ pipeline.exec(),// remove all images from cloudinary...defaultDomainLinks.map(({ domain, key, proxy }) =>proxydiff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex dd47da0945..d4e7beb024 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -16,7 +16,7 @@ import {} from "next/server";import { isBlacklistedReferrer } from "../edge-config";import { getLinkViaEdge } from "../planetscale";-import { RedisDomainMetadataProps, RedisLinkProps } from "../types";+import { RedisLinkProps } from "../types";export default async function LinkMiddleware(req: NextRequest,@@ -62,20 +62,23 @@ export default async function LinkMiddleware(if (!linkData) {// short link not found, redirect to root+ // TODO: log 404s (https://github.com/dubinc/dub/issues/559)return NextResponse.redirect(new URL("/", req.url), DUB_HEADERS);}// format link to fit the RedisLinkProps interfacelink = await formatRedisLink(linkData as any);- await redis.hset(domain, {- [key]: link,- });+ ev.waitUntil(+ redis.hset(domain, {+ [key]: link,+ }),+ );}const {id,- url: target,+ url,password,proxy,rewrite,@@ -142,12 +145,12 @@ export default async function LinkMiddleware(} else if (rewrite) {if (iframeable) {return NextResponse.rewrite(- new URL(`/rewrite/${target}`, req.url),+ new URL(`/rewrite/${url}`, req.url),DUB_HEADERS,);} else {// if link is not iframeable, use Next.js rewrite instead- return NextResponse.rewrite(target, DUB_HEADERS);+ return NextResponse.rewrite(url, DUB_HEADERS);}// redirect to iOS link if it is specified and the user is on an iOS device@@ -167,6 +170,6 @@ export default async function LinkMiddleware(// regular redirect} else {- return NextResponse.redirect(getFinalUrl(target, { req }), DUB_HEADERS);+ return NextResponse.redirect(getFinalUrl(url, { req }), DUB_HEADERS);}}diff --git a/apps/web/lib/middleware/root.ts b/apps/web/lib/middleware/root.tsindex e0b42b0c9d..fbd1888f01 100644--- a/apps/web/lib/middleware/root.ts+++ b/apps/web/lib/middleware/root.ts@@ -1,8 +1,10 @@import { recordClick } from "@/lib/tinybird";-import { redis } from "@/lib/upstash";+import { formatRedisDomain, redis } from "@/lib/upstash";import { DUB_HEADERS } from "@dub/utils";import { NextFetchEvent, NextRequest, NextResponse } from "next/server";import { parse } from "./utils";+import { RedisDomainProps } from "../types";+import { getDomainViaEdge } from "../planetscale";export default async function RootMiddleware(req: NextRequest,@@ -14,34 +16,44 @@ export default async function RootMiddleware(return NextResponse.next();}- // record clicks on root page- ev.waitUntil(recordClick({ req, domain }));+ let link = await redis.hget<RedisDomainProps>(domain, "_root");++ if (!link) {+ const linkData = await getDomainViaEdge(domain);++ if (!linkData) {+ // short link not found, redirect to root+ return NextResponse.redirect(new URL("/", req.url), DUB_HEADERS);+ }- const response = await redis.get<{- target: string;- rewrite?: boolean;- iframeable?: boolean;- }>(`root:${domain}`);+ // format link to fit the RedisLinkProps interface+ link = await formatRedisDomain(linkData as any);- const { target, rewrite, iframeable } = response || {};+ ev.waitUntil(+ redis.hset(domain, {+ _root: link,+ }),+ );+ }++ const { id, url, rewrite, iframeable, projectId } = link;++ // record clicks on root page+ ev.waitUntil(recordClick({ req, id, domain, projectId }));- if (target) {+ if (url) {if (rewrite) {if (iframeable) {- // note: there's a discrepancy between the implementation here and for- // link rewriting in `lib/api/links` – here we do `encodeURIComponent` but for links we- // don't need to. This is because link targets are already encoded, while root targets- // are not. TODO: standardize this in the future.return NextResponse.rewrite(- new URL(`/rewrite/${encodeURIComponent(target)}`, req.url),+ new URL(`/rewrite/${url}`, req.url),DUB_HEADERS,);} else {// if link is not iframeable, use Next.js rewrite instead- return NextResponse.rewrite(target, DUB_HEADERS);+ return NextResponse.rewrite(url, DUB_HEADERS);}} else {- return NextResponse.redirect(target, DUB_HEADERS);+ return NextResponse.redirect(url, DUB_HEADERS);}} else {// rewrite to root page unless the user defines a site to redirect todiff --git a/apps/web/lib/middleware/utils.ts b/apps/web/lib/middleware/utils.tsindex baa3abe2ef..ce9c610164 100644--- a/apps/web/lib/middleware/utils.ts+++ b/apps/web/lib/middleware/utils.ts@@ -25,23 +25,23 @@ export const parse = (req: NextRequest) => {return { domain, path, fullPath, key, fullKey };};-export const getFinalUrl = (target: string, { req }: { req: NextRequest }) => {+export const getFinalUrl = (url: string, { req }: { req: NextRequest }) => {// query is the query string (e.g. dub.sh/github?utm_source=twitter -> ?utm_source=twitter)const searchParams = req.nextUrl.searchParams;// get the query params of the target url- const targetUrl = new URL(target);+ const urlObj = new URL(url);// @ts-ignore – until https://github.com/microsoft/TypeScript/issues/54466 is fixed- if (searchParams.size === 0) return targetUrl.toString(); // if there are no query params, then return the target url as is (no need to parse it)+ if (searchParams.size === 0) return urlObj.toString(); // if there are no query params, then return the target url as is (no need to parse it)// if searchParams (type: `URLSearchParams`) has the same key as target url, then overwrite itfor (const [key, value] of searchParams) {- targetUrl.searchParams.set(key, value);+ urlObj.searchParams.set(key, value);}// construct final url- const finalUrl = targetUrl.toString();+ const finalUrl = urlObj.toString();return finalUrl;};diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 338fec723f..86a2f64772 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -13,11 +13,6 @@ export interface QRLinkProps {url?: string;}-export interface RedisDomainMetadataProps {- projectId: string;- redirectRules?: Record<string, string>;-}-export interface RedisLinkProps {id: string;url: string;@@ -101,6 +96,7 @@ export type DomainVerificationStatusProps =| "Unknown Error";export interface DomainProps {+ id: string;slug: string;verified: boolean;primary: boolean;@@ -109,6 +105,14 @@ export interface DomainProps {type: string;placeholder?: string;clicks: number;+ projectId: string;+}+export interface RedisDomainProps {+ id: string;+ url?: string;+ rewrite?: boolean;+ iframeable?: boolean;+ projectId?: string;}export interface BitlyGroupProps {diff --git a/apps/web/lib/upstash.ts b/apps/web/lib/upstash.tsindex 938b04076f..6c62a28fb4 100644--- a/apps/web/lib/upstash.ts+++ b/apps/web/lib/upstash.ts@@ -1,7 +1,12 @@import { getDomainWithoutWWW, isDubDomain, isIframeable } from "@dub/utils";import { Ratelimit } from "@upstash/ratelimit";import { Redis } from "@upstash/redis";-import { LinkProps, RedisLinkProps } from "./types";+import {+ DomainProps,+ LinkProps,+ RedisDomainProps,+ RedisLinkProps,+} from "./types";// Initiate Redis instance by connecting to REST URLexport const redis = new Redis({@@ -90,3 +95,20 @@ export async function formatRedisLink(...(projectId && { projectId }),};}++export async function formatRedisDomain(+ domain: DomainProps,+): Promise<RedisDomainProps> {+ const { id, slug, target: url, type, projectId } = domain;++ return {+ id,+ ...(url && { url }),+ ...(type === "rewrite" &&+ url && {+ rewrite: true,+ iframeable: await isIframeable({ url, requestDomain: slug }),+ }),+ ...(projectId && { projectId }),+ };+}diff --git a/apps/web/scripts/migrate-links-to-projects.ts b/apps/web/scripts/migrate-links-to-projects.tsindex 2c59e7ffe6..d619f603ca 100644--- a/apps/web/scripts/migrate-links-to-projects.ts+++ b/apps/web/scripts/migrate-links-to-projects.ts@@ -55,13 +55,8 @@ async function main() {// const projectName =// capitalize(u.name ?? u.email?.split("@")[0]) + "'s Links";- // let projectSlug = "";- // if (u.name) {- // projectSlug = slugify(u.name);- // }- // if (projectSlug === "") {- // projectSlug = slugify(u.email?.split("@")[0] ?? "");- // }+ // const projectSlug = slugify(u.email ?? "");+// return {// userId: user.userId,// name: u.name,diff --git a/apps/web/scripts/migrate-redis.ts b/apps/web/scripts/migrate-redis.tsnew file mode 100644index 0000000000..4948e2dc25--- /dev/null+++ b/apps/web/scripts/migrate-redis.ts@@ -0,0 +1,7 @@+import "dotenv-flow/config";+import prisma from "@/lib/prisma";+import { redis } from "./utils";++async function main() {}++main();