Skip to content

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

refactor: direct fetch in static pages

Marc Seitze9cff52c4a91
diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.ts
index 553855b4..f07fc898 100644
--- a/lib/api/links/link-data.ts
+++ b/lib/api/links/link-data.ts
@@ -1,12 +1,102 @@
import {
+ Brand,
+ DataroomBrand,
ItemType,
+ LinkAudienceType,
+ LinkType,
PermissionGroupAccessControls,
+ Prisma,
ViewerGroupAccessControls,
} from "@prisma/client";
import prisma from "@/lib/prisma";
import { sortItemsByIndexAndName } from "@/lib/utils/sort-items-by-index-name";
+// ============================================================================
+// Types
+// ============================================================================
+
+type LinkFetchStatus = "ok" | "not_found" | "archived" | "deleted" | "free";
+
+export type LinkFetchResult =
+ | {
+ status: "ok";
+ linkType: LinkType;
+ link: any;
+ brand: Partial<Brand> | Partial<DataroomBrand> | null;
+ linkId?: string;
+ }
+ | {
+ status: Exclude<LinkFetchStatus, "ok">;
+ };
+
+// Common select object for link queries
+const linkSelect = {
+ id: true,
+ expiresAt: true,
+ emailProtected: true,
+ emailAuthenticated: true,
+ allowDownload: true,
+ enableFeedback: true,
+ enableScreenshotProtection: true,
+ password: true,
+ isArchived: true,
+ deletedAt: true,
+ enableIndexFile: true,
+ enableCustomMetatag: true,
+ metaTitle: true,
+ metaDescription: true,
+ metaImage: true,
+ metaFavicon: true,
+ welcomeMessage: true,
+ enableQuestion: true,
+ linkType: true,
+ feedback: {
+ select: {
+ id: true,
+ data: true,
+ },
+ },
+ enableAgreement: true,
+ agreement: true,
+ showBanner: true,
+ enableWatermark: true,
+ watermarkConfig: true,
+ groupId: true,
+ permissionGroupId: true,
+ audienceType: true,
+ dataroomId: true,
+ teamId: true,
+ team: {
+ select: {
+ plan: true,
+ globalBlockList: true,
+ },
+ },
+ customFields: {
+ select: {
+ id: true,
+ type: true,
+ identifier: true,
+ label: true,
+ placeholder: true,
+ required: true,
+ disabled: true,
+ orderIndex: true,
+ },
+ orderBy: {
+ orderIndex: "asc" as const,
+ },
+ },
+} satisfies Prisma.LinkSelect;
+
+// Type for the link record returned by the common select query
+type LinkRecord = Prisma.LinkGetPayload<{ select: typeof linkSelect }>;
+
+// ============================================================================
+// Internal Helpers
+// ============================================================================
+
// Helper function to get all parent folder IDs for given folder IDs
async function getAllParentFolderIds(
folderIds: string[],
@@ -31,7 +121,6 @@ async function getAllParentFolderIds(
// For each accessible folder, traverse up to find all parent folders
for (const folderId of folderIds) {
let currentId: string | null = folderId;
-
while (currentId) {
allRequiredFolderIds.add(currentId);
currentId = folderMap.get(currentId) || null;
@@ -41,6 +130,10 @@ async function getAllParentFolderIds(
return Array.from(allRequiredFolderIds);
}
+// ============================================================================
+// Data Fetchers (used by both API routes and getStaticProps)
+// ============================================================================
+
export async function fetchDataroomLinkData({
linkId,
dataroomId,
@@ -197,9 +290,7 @@ export async function fetchDataroomLinkData({
);
const dataroomBrand = await prisma.dataroomBrand.findFirst({
- where: {
- dataroomId: linkData.dataroom.id,
- },
+ where: { dataroomId: linkData.dataroom.id },
select: {
logo: true,
banner: true,
@@ -210,9 +301,7 @@ export async function fetchDataroomLinkData({
});
const teamBrand = await prisma.brand.findFirst({
- where: {
- teamId: linkData.dataroom.teamId,
- },
+ where: { teamId: linkData.dataroom.teamId },
select: {
logo: true,
banner: true,
@@ -341,9 +430,7 @@ export async function fetchDataroomDocumentLinkData({
}
const dataroomBrand = await prisma.dataroomBrand.findFirst({
- where: {
- dataroomId: linkData.dataroom.id,
- },
+ where: { dataroomId: linkData.dataroom.id },
select: {
logo: true,
banner: true,
@@ -354,9 +441,7 @@ export async function fetchDataroomDocumentLinkData({
});
const teamBrand = await prisma.brand.findFirst({
- where: {
- teamId: linkData.dataroom.teamId,
- },
+ where: { teamId: linkData.dataroom.teamId },
select: {
logo: true,
banner: true,
@@ -420,9 +505,7 @@ export async function fetchDocumentLinkData({
}
const brand = await prisma.brand.findFirst({
- where: {
- teamId: linkData.document.teamId,
- },
+ where: { teamId: linkData.document.teamId },
select: {
logo: true,
brandColor: true,
@@ -433,3 +516,253 @@ export async function fetchDocumentLinkData({
return { linkData, brand };
}
+
+// ============================================================================
+// Unified Link Data Fetcher for getStaticProps
+// Avoids internal HTTP fetch which can be blocked by Vercel edge (403 errors)
+// ============================================================================
+
+/**
+ * Core function to process link data after fetching the link record.
+ * Handles all link types: DOCUMENT_LINK, DATAROOM_LINK, WORKFLOW_LINK
+ */
+async function processLinkData(
+ link: LinkRecord,
+ options: {
+ dataroomDocumentId?: string;
+ isCustomDomain?: boolean;
+ } = {},
+): Promise<LinkFetchResult> {
+ const { dataroomDocumentId, isCustomDomain } = options;
+ const teamPlan = link.team?.plan || "free";
+ const linkType = link.linkType;
+
+ // For custom domains, free plan is not allowed
+ if (isCustomDomain && teamPlan.includes("free")) {
+ return { status: "free" };
+ }
+
+ // Handle WORKFLOW_LINK
+ if (linkType === "WORKFLOW_LINK") {
+ let brand: Partial<Brand> | null = null;
+ if (link.teamId) {
+ const teamBrand = await prisma.brand.findUnique({
+ where: { teamId: link.teamId },
+ select: {
+ logo: true,
+ brandColor: true,
+ accentColor: true,
+ },
+ });
+ brand = teamBrand;
+ }
+
+ // For workflow links, return the link with minimal processing
+ // Remove team object (contains plan, globalBlockList) but keep teamId for feature flags
+ const sanitizedLink = {
+ ...link,
+ team: undefined,
+ deletedAt: undefined,
+ };
+
+ // Serialize to convert Date objects to strings (required for Next.js getStaticProps)
+ const serializedLink = JSON.parse(JSON.stringify(sanitizedLink));
+ const serializedBrand = brand ? JSON.parse(JSON.stringify(brand)) : null;
+
+ return {
+ status: "ok",
+ linkType,
+ brand: serializedBrand,
+ linkId: link.id,
+ link: serializedLink,
+ };
+ }
+
+ let brand: Partial<Brand> | Partial<DataroomBrand> | null = null;
+ let linkData: any;
+
+ // Handle DOCUMENT_LINK
+ if (linkType === "DOCUMENT_LINK") {
+ const data = await fetchDocumentLinkData({
+ linkId: link.id,
+ teamId: link.teamId!,
+ });
+ linkData = data.linkData;
+ brand = data.brand;
+ }
+ // Handle DATAROOM_LINK
+ else if (linkType === "DATAROOM_LINK") {
+ if (dataroomDocumentId) {
+ // Fetching specific document within dataroom
+ try {
+ const data = await fetchDataroomDocumentLinkData({
+ linkId: link.id,
+ teamId: link.teamId!,
+ dataroomDocumentId: dataroomDocumentId,
+ permissionGroupId: link.permissionGroupId || undefined,
+ ...(link.audienceType === LinkAudienceType.GROUP &&
+ link.groupId && {
+ groupId: link.groupId,
+ }),
+ });
+ linkData = data.linkData;
+ brand = data.brand;
+ } catch {
+ return { status: "not_found" };
+ }
+ } else {
+ // Fetching full dataroom
+ const data = await fetchDataroomLinkData({
+ linkId: link.id,
+ dataroomId: link.dataroomId,
+ teamId: link.teamId!,
+ permissionGroupId: link.permissionGroupId || undefined,
+ ...(link.audienceType === LinkAudienceType.GROUP &&
+ link.groupId && {
+ groupId: link.groupId,
+ }),
+ });
+ linkData = data.linkData;
+ brand = data.brand;
+ linkData.accessControls = data.accessControls;
+ }
+ }
+
+ // Only include agreement if enabled (no need to expose it otherwise)
+ const sanitizedAgreement =
+ link.enableAgreement && link.agreement
+ ? {
+ id: link.agreement.id,
+ name: link.agreement.name,
+ content: link.agreement.content,
+ contentType: link.agreement.contentType,
+ requireName: link.agreement.requireName,
+ }
+ : null;
+
+ // Sanitize document - keep fields needed by getStaticProps
+ // Note: team/teamId are used server-side for feature flags and are stripped before client props
+ const sanitizedDocument = linkData?.document
+ ? {
+ id: linkData.document.id,
+ name: linkData.document.name,
+ teamId: linkData.document.teamId,
+ team: linkData.document.team, // Used server-side for plan check, stripped before client
+ downloadOnly: linkData.document.downloadOnly,
+ advancedExcelEnabled: linkData.document.advancedExcelEnabled,
+ versions: linkData.document.versions,
+ }
+ : undefined;
+
+ // Sanitize link for return - remove sensitive/internal data
+ const sanitizedLink = {
+ ...link,
+ // Remove team object (contains plan, globalBlockList) but keep teamId for feature flags
+ team: undefined,
+ // Remove internal fields
+ deletedAt: undefined,
+ document: undefined,
+ dataroom: undefined,
+ // Use sanitized agreement
+ agreement: sanitizedAgreement,
+ ...(teamPlan === "free" && {
+ customFields: [],
+ enableAgreement: false,
+ enableWatermark: false,
+ permissionGroupId: null,
+ }),
+ };
+
+ const returnLink = {
+ ...sanitizedLink,
+ ...linkData,
+ // Override with sanitized document
+ document: sanitizedDocument,
+ // Remove internal IDs
+ dataroomId: undefined,
+ dataroomDocument: linkData?.dataroom?.documents?.[0] || undefined,
+ };
+
+ // Serialize to convert Date objects to strings (required for Next.js getStaticProps)
+ const serializedLink = JSON.parse(JSON.stringify(returnLink));
+ const serializedBrand = brand ? JSON.parse(JSON.stringify(brand)) : null;
+
+ return {
+ status: "ok",
+ linkType,
+ link: serializedLink,
+ brand: serializedBrand,
+ };
+}
+
+/**
+ * Fetch link data by linkId (for /view/[linkId] routes)
+ */
+export async function fetchLinkDataById({
+ linkId,
+ dataroomDocumentId,
+}: {
+ linkId: string;
+ dataroomDocumentId?: string;
+}): Promise<LinkFetchResult> {
+ const link = await prisma.link.findUnique({
+ where: { id: linkId },
+ select: linkSelect,
+ });
+
+ if (!link) {
+ return { status: "not_found" };
+ }
+
+ if (link.deletedAt) {
+ return { status: "deleted" };
+ }
+
+ if (link.isArchived) {
+ return { status: "archived" };
+ }
+
+ return processLinkData(link, { dataroomDocumentId, isCustomDomain: false });
+}
+
+/**
+ * Fetch link data by domain and slug (for /view/domains/[domain]/[slug] routes)
+ * Includes free plan check since custom domains require paid plan
+ */
+export async function fetchLinkDataByDomainSlug({
+ domain,
+ slug,
+ dataroomDocumentId,
+}: {
+ domain: string;
+ slug: string;
+ dataroomDocumentId?: string;
+}): Promise<LinkFetchResult> {
+ const link = await prisma.link.findUnique({
+ where: {
+ domainSlug_slug: {
+ slug: slug,
+ domainSlug: domain,
+ },
+ },
+ select: linkSelect,
+ });
+
+ if (!link) {
+ return { status: "not_found" };
+ }
+
+ if (link.isArchived) {
+ return { status: "archived" };
+ }
+
+ if (link.deletedAt) {
+ return { status: "deleted" };
+ }
+
+ return processLinkData(link, { dataroomDocumentId, isCustomDomain: true });
+}
+
+// Legacy export aliases for backward compatibility
+export const fetchCustomDomainLinkData = fetchLinkDataByDomainSlug;
+export type CustomDomainLinkResult = LinkFetchResult;
diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].ts
index 60c61b03..ed646428 100644
--- a/pages/api/links/domains/[...domainSlug].ts
+++ b/pages/api/links/domains/[...domainSlug].ts
@@ -173,7 +173,7 @@ export default async function handle(
});
brand = teamBrand;
}
-
+
return res.status(200).json({ linkType, brand, linkId: link.id });
}
diff --git a/pages/view/[linkId]/d/[documentId].tsx b/pages/view/[linkId]/d/[documentId].tsx
index f26bee34..2a2b48f2 100644
--- a/pages/view/[linkId]/d/[documentId].tsx
+++ b/pages/view/[linkId]/d/[documentId].tsx
@@ -11,6 +11,7 @@ import { ExtendedRecordMap } from "notion-types";
import { parsePageId } from "notion-utils";
import z from "zod";
+import { fetchLinkDataById } from "@/lib/api/links/link-data";
import notion from "@/lib/notion";
import { addSignedUrls, fetchMissingPageReferences } from "@/lib/notion/utils";
import { CustomUser, LinkWithDataroomDocument, NotionTheme } from "@/lib/types";
@@ -193,18 +194,19 @@ export async function getStaticProps(context: GetStaticPropsContext) {
try {
const linkId = z.string().cuid().parse(linkIdParam);
const documentId = z.string().cuid().parse(documentIdParam);
- const res = await fetch(
- `${process.env.NEXTAUTH_URL}/api/links/${linkId}/documents/${documentId}`,
- );
- if (!res.ok) {
- if (res.status === 404) {
- return { notFound: true };
- }
- return { props: { error: true }, revalidate: 30 };
+ // Fetch link data directly from database to avoid internal HTTP fetch
+ // which can be blocked by Vercel's edge protection (403 errors)
+ const result = await fetchLinkDataById({
+ linkId,
+ dataroomDocumentId: documentId,
+ });
+
+ if (result.status !== "ok") {
+ return { notFound: true };
}
- const { linkType, link, brand } =
- (await res.json()) as DataroomDocumentLinkData;
+
+ const { linkType, link, brand } = result;
if (!link || !linkType) {
return { notFound: true };
diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsx
index 4a817167..014c82e2 100644
--- a/pages/view/[linkId]/index.tsx
+++ b/pages/view/[linkId]/index.tsx
@@ -12,6 +12,7 @@ import { ExtendedRecordMap } from "notion-types";
import { parsePageId } from "notion-utils";
import z from "zod";
+import { fetchLinkDataById } from "@/lib/api/links/link-data";
import { getFeatureFlags } from "@/lib/featureFlags";
import notion from "@/lib/notion";
import { addSignedUrls, fetchMissingPageReferences } from "@/lib/notion/utils";
@@ -74,12 +75,18 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {
try {
const linkId = z.string().cuid().parse(linkIdParam);
- const res = await fetch(`${process.env.NEXTAUTH_URL}/api/links/${linkId}`);
- if (!res.ok) {
- throw new Error(`Failed to fetch: ${res.status}`);
+
+ // Fetch link data directly from database to avoid internal HTTP fetch
+ // which can be blocked by Vercel's edge protection (403 errors)
+ const result = await fetchLinkDataById({ linkId });
+
+ if (result.status !== "ok") {
+ return {
+ notFound: true,
+ };
}
- const { linkType, link, brand } = (await res.json()) as any;
+ const { linkType, link, brand } = result;
if (!linkType) {
return {
diff --git a/pages/view/domains/[domain]/[slug]/d/[documentId].tsx b/pages/view/domains/[domain]/[slug]/d/[documentId].tsx
index 80ba77e6..2fc8f77b 100644
--- a/pages/view/domains/[domain]/[slug]/d/[documentId].tsx
+++ b/pages/view/domains/[domain]/[slug]/d/[documentId].tsx
@@ -11,6 +11,7 @@ import { ExtendedRecordMap } from "notion-types";
import { parsePageId } from "notion-utils";
import z from "zod";
+import { fetchLinkDataByDomainSlug } from "@/lib/api/links/link-data";
import notion from "@/lib/notion";
import { addSignedUrls, fetchMissingPageReferences } from "@/lib/notion/utils";
import { CustomUser, LinkWithDataroomDocument, NotionTheme } from "@/lib/types";
@@ -206,21 +207,16 @@ export async function getStaticProps(context: GetStaticPropsContext) {
.parse(slugParam);
const documentId = z.string().cuid().parse(documentIdParam);
- const res = await fetch(
- `${process.env.NEXTAUTH_URL}/api/links/domains/${encodeURIComponent(
- domain,
- )}/${encodeURIComponent(slug)}/documents/${documentId}`,
- );
- if (!res.ok) {
- if (res.status === 404) {
- return { notFound: true };
- }
-
- return { props: { error: true }, revalidate: 30 };
+ const result = await fetchLinkDataByDomainSlug({
+ domain,
+ slug,
+ dataroomDocumentId: documentId,
+ });
+ if (result.status !== "ok") {
+ return { notFound: true };
}
- const { linkType, link, brand } =
- (await res.json()) as DataroomDocumentLinkData;
+ const { linkType, link, brand } = result;
if (!link || !linkType) {
return { notFound: true };
diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsx
index 75647998..b70c0928 100644
--- a/pages/view/domains/[domain]/[slug]/index.tsx
+++ b/pages/view/domains/[domain]/[slug]/index.tsx
@@ -12,6 +12,7 @@ import { ExtendedRecordMap } from "notion-types";
import { parsePageId } from "notion-utils";
import z from "zod";
+import { fetchLinkDataByDomainSlug } from "@/lib/api/links/link-data";
import { getFeatureFlags } from "@/lib/featureFlags";
import notion from "@/lib/notion";
import { addSignedUrls, fetchMissingPageReferences } from "@/lib/notion/utils";
@@ -63,16 +64,14 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {
.regex(/^[a-zA-Z0-9_-]+$/, "Invalid path parameter")
.parse(slugParam);
- const res = await fetch(
- `${process.env.NEXTAUTH_URL}/api/links/domains/${encodeURIComponent(
- domain,
- )}/${encodeURIComponent(slug)}`,
- );
- if (!res.ok) {
- throw new Error(`Failed to fetch: ${res.status}`);
+ const result = await fetchLinkDataByDomainSlug({ domain, slug });
+ if (result.status !== "ok") {
+ return {
+ notFound: true,
+ };
}
- const responseData = (await res.json()) as any;
- const { linkType, link, brand, linkId } = responseData;
+
+ const { linkType, link, brand, linkId } = result;
if (!linkType) {
return {