Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add root domain redirect support (schema, redis, middleware, API)

Cursor Agent3a610bac062a
diff --git a/lib/api/domains/redis.ts b/lib/api/domains/redis.ts
new file mode 100644
index 00000000..a770cc2e
--- /dev/null
+++ b/lib/api/domains/redis.ts
@@ -0,0 +1,29 @@
+import { redis } from "@/lib/redis";
+
+const DOMAIN_REDIRECT_PREFIX = "domain:redirect";
+
+function getRedisKey(domain: string): string {
+ return `${DOMAIN_REDIRECT_PREFIX}:${domain.toLowerCase()}`;
+}
+
+export async function getDomainRedirectUrl(
+ domain: string,
+): Promise<string | null> {
+ return redis.get<string>(getRedisKey(domain));
+}
+
+export async function setDomainRedirectUrl(
+ domain: string,
+ redirectUrl: string | null,
+): Promise<void> {
+ const key = getRedisKey(domain);
+ if (redirectUrl) {
+ await redis.set(key, redirectUrl);
+ } else {
+ await redis.del(key);
+ }
+}
+
+export async function deleteDomainRedirectUrl(domain: string): Promise<void> {
+ await redis.del(getRedisKey(domain));
+}
diff --git a/lib/middleware/domain.ts b/lib/middleware/domain.ts
index bbff568e..c420813d 100644
--- a/lib/middleware/domain.ts
+++ b/lib/middleware/domain.ts
@@ -1,41 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { BLOCKED_PATHNAMES } from "@/lib/constants";
+import { getDomainRedirectUrl } from "@/lib/api/domains/redis";
export default async function DomainMiddleware(req: NextRequest) {
const path = req.nextUrl.pathname;
const host = req.headers.get("host");
- // If it's the root path, redirect to papermark.com
+ // If it's the root path, check for a configured redirect URL in Redis
if (path === "/") {
- if (host === "guide.permithealth.com") {
- return NextResponse.redirect(
- new URL("https://guide.permithealth.com/faq", req.url),
- );
- }
-
- if (host === "fund.tradeair.in") {
- return NextResponse.redirect(
- new URL("https://tradeair.in/sv-fm-inbound", req.url),
- );
- }
-
- if (host === "docs.pashupaticapital.com") {
- return NextResponse.redirect(
- new URL("https://www.pashupaticapital.com/", req.url),
- );
- }
-
- if (host === "partners.braxtech.net") {
- return NextResponse.redirect(
- new URL("https://partners.braxtech.net/investors", req.url),
- );
- }
-
- if (host === "research.elazaradvisors.com") {
- return NextResponse.redirect(
- new URL("https://research.elazaradvisors.com/root", req.url),
- );
+ if (host) {
+ const redirectUrl = await getDomainRedirectUrl(host);
+ if (redirectUrl) {
+ return NextResponse.redirect(new URL(redirectUrl, req.url), {
+ status: 301,
+ });
+ }
}
return NextResponse.redirect(new URL("https://www.papermark.com", req.url));
diff --git a/pages/api/teams/[teamId]/domains/[domain]/index.ts b/pages/api/teams/[teamId]/domains/[domain]/index.ts
index f79303b4..77b820ef 100644
--- a/pages/api/teams/[teamId]/domains/[domain]/index.ts
+++ b/pages/api/teams/[teamId]/domains/[domain]/index.ts
@@ -3,6 +3,10 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api//auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
+import {
+ deleteDomainRedirectUrl,
+ setDomainRedirectUrl,
+} from "@/lib/api/domains/redis";
import { getApexDomain, removeDomainFromVercel } from "@/lib/domains";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
@@ -61,9 +65,10 @@ export default async function handle(
id: domainToBeDeleted?.id,
},
}),
+ deleteDomainRedirectUrl(domain),
]);
- return res.status(204).end(); // 204 No Content response for successful deletes
+ return res.status(204).end();
} catch (error) {
log({
message: `Failed to delete domain: _${domain}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,
@@ -132,9 +137,66 @@ export default async function handle(
});
errorhandler(error, res);
}
+ } else if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/domains/:domain - update domain settings (e.g. redirectUrl)
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, domain } = req.query as { teamId: string; domain: string };
+ const userId = (session.user as CustomUser).id;
+
+ if (!domain) {
+ return res.status(400).json("Domain is required");
+ }
+
+ try {
+ const { domain: domainToBeUpdated } = await getTeamWithDomain({
+ teamId,
+ userId,
+ domain,
+ });
+
+ if (!domainToBeUpdated) {
+ return res.status(404).json("Domain not found");
+ }
+
+ const { redirectUrl } = req.body as { redirectUrl: string | null };
+
+ if (redirectUrl !== null && redirectUrl !== undefined && redirectUrl !== "") {
+ try {
+ new URL(redirectUrl);
+ } catch {
+ return res.status(422).json({ message: "Invalid redirect URL" });
+ }
+ }
+
+ const normalizedUrl = redirectUrl || null;
+
+ const updatedDomain = await prisma.domain.update({
+ where: {
+ id: domainToBeUpdated.id,
+ teamId,
+ },
+ data: {
+ redirectUrl: normalizedUrl,
+ },
+ });
+
+ await setDomainRedirectUrl(domain, normalizedUrl);
+
+ return res.status(200).json(updatedDomain);
+ } catch (error) {
+ log({
+ message: `Failed to update domain: _${domain}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,
+ type: "error",
+ mention: true,
+ });
+ errorhandler(error, res);
+ }
} else {
- // We only allow POST requests
- res.setHeader("Allow", ["DELETE", "PATCH"]);
+ res.setHeader("Allow", ["DELETE", "PATCH", "PUT"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
diff --git a/pages/api/teams/[teamId]/domains/index.ts b/pages/api/teams/[teamId]/domains/index.ts
index 051b1418..dcc0ae3a 100644
--- a/pages/api/teams/[teamId]/domains/index.ts
+++ b/pages/api/teams/[teamId]/domains/index.ts
@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
+import { setDomainRedirectUrl } from "@/lib/api/domains/redis";
import { addDomainToVercel, validDomainRegex } from "@/lib/domains";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
@@ -35,6 +36,7 @@ export default async function handle(
slug: true,
verified: true,
isDefault: true,
+ redirectUrl: true,
},
orderBy: {
createdAt: "asc",
@@ -68,8 +70,7 @@ export default async function handle(
userId,
});
- // Assuming data is an object with `domain` properties
- const { domain } = req.body;
+ const { domain, redirectUrl } = req.body;
// Sanitize domain by removing whitespace, protocol, and paths
const sanitizedDomain = domain
@@ -109,10 +110,15 @@ export default async function handle(
slug: sanitizedDomain,
userId,
teamId,
+ ...(redirectUrl && { redirectUrl }),
},
});
await addDomainToVercel(sanitizedDomain);
+ if (redirectUrl) {
+ await setDomainRedirectUrl(sanitizedDomain, redirectUrl);
+ }
+
return res.status(201).json(response);
} catch (error) {
log({
diff --git a/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sql b/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sql
new file mode 100644
index 00000000..9144e8b0
--- /dev/null
+++ b/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Domain" ADD COLUMN "redirectUrl" TEXT;
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 02b6d14f..f8fa941e 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -103,6 +103,7 @@ model Domain {
Team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
verified Boolean @default(false) // Whether the domain has been verified
isDefault Boolean @default(false) // Whether the domain is the primary domain
+ redirectUrl String? // URL to redirect to when visiting the root of this domain
lastChecked DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt