Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

feat(fonts): add server-side Computer Modern font mirrors (#3634)

denggl12394f384aa589d
diff --git a/.env.example b/.env.example
index ebf97d91f..ce6c1ee5a 100644
--- a/.env.example
+++ b/.env.example
@@ -18,6 +18,14 @@ APP_URL="http://localhost:3000"
# Vercel: APP_URL can be omitted; production uses VERCEL_PROJECT_PRODUCTION_URL.
+# --- Font mirror (server PDF rendering only) ---
+# Optional absolute HTTP(S) base URL, without a query string or fragment.
+# Mirrors only the five Computer Modern families; Google fonts and browser font
+# requests remain external. Preserve the upstream font/<family>/<file>.woff layout.
+# Set before server startup; restart/redeploy after changes. No web rebuild needed.
+# See docs/self-hosting/fonts.mdx for setup and current limitations.
+# WEB_FONT_BASE_URL="https://fonts.example.com/cm"
+
# --- Database (PostgreSQL) ---
# PostgreSQL connection URL. In Docker Compose, the hostname is usually `postgres`;
# when running directly on your machine, `localhost` is typical.
diff --git a/docs/docs.json b/docs/docs.json
index 493aa8b1e..6531fd8ad 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -236,6 +236,7 @@
"group": "Server Configuration",
"pages": [
"self-hosting/environment-variables",
+ "self-hosting/fonts",
"self-hosting/examples",
"self-hosting/job-search-and-ai",
"self-hosting/sso"
diff --git a/docs/guides/customizing-typography.mdx b/docs/guides/customizing-typography.mdx
index 50330eaf9..5a900411b 100644
--- a/docs/guides/customizing-typography.mdx
+++ b/docs/guides/customizing-typography.mdx
@@ -58,6 +58,11 @@ Drag the **Text size** slider. It goes from 9 pt to 12.5 pt in half-point steps,
If you set an exact body line height or **Spacing (Vertical)** in Advanced that doesn't match one of these, no density is selected.
+<Note>
+ Self-hosting operators can [mirror Computer Modern fonts for server PDFs](/self-hosting/fonts). This setting does not
+ change browser font previews or Google-hosted fonts.
+</Note>
+
## Use any font
<Steps>
diff --git a/docs/self-hosting/docker.mdx b/docs/self-hosting/docker.mdx
index 3df91c169..29f7d66c2 100644
--- a/docs/self-hosting/docker.mdx
+++ b/docs/self-hosting/docker.mdx
@@ -173,6 +173,8 @@ Your instance is running. Next, you might want to:
- **Keep it private.** After your own account exists, add `FLAG_DISABLE_SIGNUPS="true"` to `.env` and run
`docker compose up -d`. Nobody else can sign up; existing accounts keep working.
+- **Mirror Computer Modern fonts for server PDFs.** See [Font mirroring](/self-hosting/fonts) for configuration and
+ current browser and Google-font limitations.
- **Send real emails.** Add the `SMTP_*` settings from the [reference](/self-hosting/environment-variables#email).
- **Turn on job search and AI.** Connect shared Firecrawl and AI services, or enable personal keys with
`ENCRYPTION_SECRET`. See [Job search and AI](/self-hosting/job-search-and-ai).
diff --git a/docs/self-hosting/environment-variables.mdx b/docs/self-hosting/environment-variables.mdx
index 7f07379b4..d3bc07a8c 100644
--- a/docs/self-hosting/environment-variables.mdx
+++ b/docs/self-hosting/environment-variables.mdx
@@ -47,6 +47,23 @@ turn on an optional feature.
| `SERVER_PORT` | `3001` | Port the server listens on when `NODE_ENV` is not `production`, which is the local development setup. Ignored by the image. |
| `ROOT_RESUME_ID` | unset | Shows one public resume at `/` instead of the home page. See [Show one resume at your root address](/self-hosting/examples#show-one-resume-at-your-root-address). |
+## Font mirror
+
+| Variable | Default | Description |
+| ------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `WEB_FONT_BASE_URL` | unset | Absolute HTTP(S) base URL for the five Computer Modern families during server-side PDF rendering, for example `https://fonts.example.com/cm`. No query string or fragment. Unset or empty keeps the original URLs. |
+
+Preserve the upstream `font/<family>/<file>.woff` paths below this base URL. Set the variable before the server starts;
+restart or redeploy after changes. No web rebuild is needed for this server-side setting.
+
+<Warning>
+ This server-only variable is not exposed to the Vite browser app. Browser PDF rendering and font-picker previews still
+ use their original URLs. Google-hosted families and fallback fonts are not rewritten, including during server
+ rendering. This setting does not provide offline or Google-free font loading.
+</Warning>
+
+See [Mirror Computer Modern fonts](/self-hosting/fonts) for the asset layout, deployment settings and verification.
+
## Database
| Variable | Default | Description |
diff --git a/docs/self-hosting/fonts.mdx b/docs/self-hosting/fonts.mdx
new file mode 100644
index 000000000..b36aba5fb
--- /dev/null
+++ b/docs/self-hosting/fonts.mdx
@@ -0,0 +1,95 @@
+---
+title: "Mirror Computer Modern fonts"
+description: "Serve Computer Modern font files from your own host for server-generated PDFs, and understand which font requests remain external."
+---
+
+Set `WEB_FONT_BASE_URL` when you want the Node.js server to fetch Computer Modern font files from a
+mirror you control. You need a running Reactive Resume instance and an HTTP(S) server that can serve static files.
+
+<Warning>
+ This setting does not make font loading offline or Google-free. It covers only five Computer Modern families in
+ server-generated PDFs. The other catalog families, including Noto fallback fonts, keep their Google URLs. Browser PDF
+ rendering and font-picker previews keep all their original URLs, even for Computer Modern fonts.
+</Warning>
+
+## 1. Prepare the mirror
+
+Copy the `font/` directory from the `bitmaks/cm-web-fonts` source used by your release's
+`packages/fonts/src/webfontlist.json` to your static file server. Keep the directory names, filenames and case:
+
+```text
+cm/
+└── font/
+ ├── Bright/
+ ├── Concrete/
+ ├── Sans/
+ ├── Serif/
+ └── Typewriter/
+```
+
+These directories supply Computer Modern Bright, Concrete, Sans, Serif and Typewriter. Mirror every referenced
+weight and italic file, not only the preview font. The app does not bundle these files or populate your mirror.
+Keep the upstream license notices with your mirror.
+
+For example, with a base URL of `https://fonts.example.com/cm`, this original URL:
+
+```text
+https://cdn.jsdelivr.net/gh/bitmaks/cm-web-fonts@latest/font/Bright/cmunbmr.woff
+```
+
+becomes:
+
+```text
+https://fonts.example.com/cm/font/Bright/cmunbmr.woff
+```
+
+Use an absolute HTTP(S) URL without a query string or fragment. Surrounding whitespace and trailing slashes are removed. Do not include
+the `font/` segment in the base URL: the resolver appends it. Use an address reachable from the app server; inside
+Docker, `localhost` refers to the app container itself. The mirror must serve font bytes without a login page.
+
+## 2. Configure the deployment
+
+```dotenv
+WEB_FONT_BASE_URL="https://fonts.example.com/cm"
+```
+
+| Deployment | Where to set it | Apply the change |
+| --------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
+| Docker Compose | The app's `.env` file, loaded through `env_file`. | Run `docker compose up -d` to recreate the app container. No image rebuild is needed. |
+| Kubernetes | The app's environment Secret or ConfigMap. | Restart the app deployment so the new pods read it. |
+| Source checkout | Root `.env` for the production server, or `.env.local` for `pnpm dev`. | Restart the server or development command. |
+| Vercel | The project's environment variables for the intended deployment environment. | Redeploy the backend. |
+
+The server validates the URL at startup. An unset or empty value preserves the original URLs. Remove the variable
+and restart or redeploy to return to the default CDN.
+
+Set this value before starting the server. The server PDF entry supplies it to the font loader; the shared font
+catalog does not read environment variables. This setting is not exposed to the Vite browser app; rebuilding the
+web app does not enable browser mirroring.
+The Cloudflare Workers deployment is not covered by this Node.js server setup.
+
+## 3. Check delivery
+
+From the app server's network, request a mirrored file:
+
+```bash
+curl --fail --output /dev/null https://fonts.example.com/cm/font/Bright/cmunbmr.woff
+```
+
+Then generate a PDF through the server for a resume using Computer Modern Bright. Check the mirror's access logs
+for requests to `font/Bright/`. Repeat with any other Computer Modern families you use. A missing weight or italic
+file can fail PDF rendering; the mirror is not retried against the original CDN.
+
+Server-to-server font fetches do not require CORS headers. If another browser application also uses your mirror,
+configure that host to allow its origin and serve the appropriate font content type. CORS headers alone do not
+enable this setting in Reactive Resume's browser app.
+
+External Google requests can still occur for punctuation, symbols, emoji or language fallback fonts, even when
+the chosen heading and body fonts are Computer Modern. Browser network requests to the original font hosts are
+also expected with the current implementation.
+
+## Related pages
+
+- [Environment variables](/self-hosting/environment-variables#font-mirror): the setting's default and URL constraints.
+- [Self-hosting with Docker](/self-hosting/docker): configure the application container.
+- [Customizing typography](/guides/customizing-typography): choose heading and body fonts.
diff --git a/packages/env/src/server.test.ts b/packages/env/src/server.test.ts
index d4f1bbb00..b76d2f622 100644
--- a/packages/env/src/server.test.ts
+++ b/packages/env/src/server.test.ts
@@ -13,6 +13,7 @@ beforeEach(() => {
"AI_API_KEY",
"AI_BASE_URL",
"REDIS_URL",
+ "WEB_FONT_BASE_URL",
"STORAGE_HEALTHCHECK_TIMEOUT_MS",
])
vi.stubEnv(name, undefined);
@@ -22,6 +23,28 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe("web font mirror configuration", () => {
+ it.each([undefined, "", "https://fonts.example.com", "https://fonts.example.com/cm/", "http://localhost:8080"])(
+ "accepts %s",
+ async (value) => {
+ vi.stubEnv("WEB_FONT_BASE_URL", value);
+ expect((await import("./server")).env.WEB_FONT_BASE_URL).toBe(value || undefined);
+ },
+ );
+
+ it.each([
+ "not a url",
+ "/fonts",
+ "ftp://fonts.example.com",
+ "https://fonts.example.com?key=value",
+ "https://fonts.example.com#fonts",
+ ])("rejects %s", async (value) => {
+ vi.stubEnv("WEB_FONT_BASE_URL", value);
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ await expect(import("./server")).rejects.toThrow("Invalid environment variables");
+ });
+});
+
describe("server web access configuration", () => {
it.each([
{ WEB_ACCESS_API_KEY: "test-key" },
diff --git a/packages/env/src/server.ts b/packages/env/src/server.ts
index a8a144d0b..143569169 100644
--- a/packages/env/src/server.ts
+++ b/packages/env/src/server.ts
@@ -56,6 +56,10 @@ export const env = createEnv({
// Application
CLOUDFLARE: z.stringbool().default(false),
APP_URL: z.url({ protocol: /https?/ }),
+ WEB_FONT_BASE_URL: z
+ .url({ protocol: /^https?$/ })
+ .refine((value) => !/[?#]/.test(value), "Font base URL must not contain a query string or fragment")
+ .optional(),
ROOT_RESUME_ID: z
.string()
.trim()
diff --git a/packages/fonts/src/index.test.ts b/packages/fonts/src/index.test.ts
index 3b06e7b6f..f645e2913 100644
--- a/packages/fonts/src/index.test.ts
+++ b/packages/fonts/src/index.test.ts
@@ -1,6 +1,21 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { getFont, getPdfFallbackFontFamilies, resolveBoldFontWeight, resolveLegacyFontAlias } from "./index";
+it("keeps catalog sources independent of the server mirror environment", async () => {
+ vi.stubEnv("WEB_FONT_BASE_URL", "https://fonts.example.com/cm");
+ try {
+ vi.resetModules();
+ const { getWebFontSource, getWebFont } = await import("./index");
+ const original = "https://cdn.jsdelivr.net/gh/bitmaks/cm-web-fonts@latest/font/Bright/cmunbmr.woff";
+ expect(getWebFontSource("Computer Modern Bright")).toBe(original);
+ expect(getWebFontSource("Computer Modern Bright", "100")).toBe(original);
+ expect(getWebFont("Computer Modern Bright")?.preview).toBe(original);
+ expect(getWebFontSource("Roboto")).toMatch(/^https:\/\/fonts\.gstatic\.com\//);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+});
+
describe("getPdfFallbackFontFamilies", () => {
it("uses separate fonts for arrows and other text symbols", () => {
expect(getPdfFallbackFontFamilies("Times-Roman", { scripts: ["arrows"] })).toEqual([
diff --git a/packages/fonts/src/index.ts b/packages/fonts/src/index.ts
index fb1075c94..07eefd9f3 100644
--- a/packages/fonts/src/index.ts
+++ b/packages/fonts/src/index.ts
@@ -180,6 +180,7 @@ export function getWebFont(family: string) {
return webFontMap.get(family);
}
+/** Resolves a catalog font file with weight/style fallbacks. */
export function getWebFontSource(family: string, weight: FontWeight = "400", italic = false) {
const webFont = getWebFont(family);
if (!webFont) return null;
diff --git a/packages/pdf/src/forme/fonts.test.ts b/packages/pdf/src/forme/fonts.test.ts
index 7391e61d9..cba22e7f9 100644
--- a/packages/pdf/src/forme/fonts.test.ts
+++ b/packages/pdf/src/forme/fonts.test.ts
@@ -4,6 +4,7 @@ import { loadFonts } from "./fonts";
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
});
const font = (path: string) => ({
@@ -13,6 +14,41 @@ const font = (path: string) => ({
src: `https://fonts.gstatic.com${path}`,
});
+const computerModernBase = "https://cdn.jsdelivr.net/gh/bitmaks/cm-web-fonts@latest";
+const mirrorBase = "https://fonts.example.com/cm";
+
+it.each([
+ [undefined, computerModernBase],
+ ["", computerModernBase],
+ [mirrorBase, mirrorBase],
+ [`${mirrorBase}/`, mirrorBase],
+ [`${mirrorBase}///`, mirrorBase],
+ [` ${mirrorBase}/ `, mirrorBase],
+])("uses explicit mirror %s without reading the server environment", async (baseUrl, expectedBase) => {
+ vi.stubEnv("WEB_FONT_BASE_URL", "https://unused-env.example/cm");
+ vi.resetModules();
+ const { loadFonts: loadMirroredFonts } = await import("./fonts");
+ const requested: string[] = [];
+ vi.stubGlobal("fetch", (source: URL | string) => {
+ requested.push(String(source));
+ return Promise.resolve(new Response(new Uint8Array([1, 2, 3])));
+ });
+ const requests = [
+ { ...font(""), src: `${computerModernBase}/font/Bright/cmunbmr.woff` },
+ { ...font(""), weight: 700, italic: true, src: `${computerModernBase}/font/Bright/cmunbxo.woff` },
+ font("/s/mirror-test/font.ttf"),
+ ];
+ expect((await loadMirroredFonts(requests, baseUrl)).missing).toEqual([]);
+ expect(requested).toEqual([
+ `${expectedBase}/font/Bright/cmunbmr.woff`,
+ `${expectedBase}/font/Bright/cmunbxo.woff`,
+ "https://fonts.gstatic.com/s/mirror-test/font.ttf",
+ ]);
+ await loadMirroredFonts(requests, baseUrl);
+ expect(requested).toHaveLength(3);
+ expect(requests[0]?.src).toBe(`${computerModernBase}/font/Bright/cmunbmr.woff`);
+});
+
it("falls back to fonts.gstatic.cn when fonts.gstatic.com doesn't answer, then starts there", async () => {
vi.useFakeTimers();
const requested: string[] = [];
diff --git a/packages/pdf/src/forme/fonts.ts b/packages/pdf/src/forme/fonts.ts
index efe396737..f9e233ae4 100644
--- a/packages/pdf/src/forme/fonts.ts
+++ b/packages/pdf/src/forme/fonts.ts
@@ -102,16 +102,24 @@ const load = (src: string) => {
/**
* The font faces a document needs, as bytes Forme can embed. A face that fails to load is left out and listed in
* `missing`; Forme falls back to its built-in fonts for that text.
+ * An explicit mirror base rewrites only Computer Modern downloads, leaving catalog sources unchanged.
*/
export async function loadFonts(
requests: readonly PdfFontRequest[],
+ webFontBaseUrl?: string,
): Promise<{ fonts: FormeFont[]; warnings: string[]; missing: string[] }> {
+ const mirrorBase = webFontBaseUrl?.trim().replace(/\/+$/, "");
+ const computerModernBase = "https://cdn.jsdelivr.net/gh/bitmaks/cm-web-fonts@latest";
const warnings: string[] = [];
const missing: string[] = [];
const loaded = await Promise.all(
requests.map(async (request): Promise<FormeFont | null> => {
try {
- return { family: request.family, weight: request.weight, italic: request.italic, src: await load(request.src) };
+ const source =
+ mirrorBase && request.src.startsWith(computerModernBase)
+ ? mirrorBase + request.src.slice(computerModernBase.length)
+ : request.src;
+ return { family: request.family, weight: request.weight, italic: request.italic, src: await load(source) };
} catch (error) {
warnings.push(error instanceof Error ? error.message : `Font ${request.src} could not be loaded.`);
missing.push(request.family);
diff --git a/packages/pdf/src/forme/render.ts b/packages/pdf/src/forme/render.ts
index 908582067..bd1e015cf 100644
--- a/packages/pdf/src/forme/render.ts
+++ b/packages/pdf/src/forme/render.ts
@@ -37,6 +37,8 @@ export type RenderResumeInput = {
renderOptions?: ResumeRenderOptions | undefined;
resolveSectionTitle?: SectionTitleResolver | undefined;
readImage?: ((source: string) => Promise<Uint8Array>) | undefined;
+ /** Computer Modern mirror supplied by the server entry; browser callers leave it unset. */
+ webFontBaseUrl?: string | undefined;
};
export type RenderedResume = {
@@ -212,6 +214,7 @@ export function renderResume(engine: FormeEngine, input: RenderResumeInput): Pro
resolveSectionTitle: input.resolveSectionTitle,
}),
input.readImage,
+ input.webFontBaseUrl,
);
}
@@ -223,10 +226,11 @@ export async function renderResumeElement(
engine: FormeEngine,
element: ReactElement,
readImage?: (source: string) => Promise<Uint8Array>,
+ webFontBaseUrl?: string,
): Promise<RenderedResume> {
const data = (element.props as { data?: ResumeData }).data;
// Font downloads start first: they're the largest wait, and the tree needs only the icons.
- const fontsLoaded = loadFonts(data ? resumeFontRequests(data) : []);
+ const fontsLoaded = loadFonts(data ? resumeFontRequests(data) : [], webFontBaseUrl);
await loadIcons();
const tree = renderHostTree(element);
const [{ fonts, warnings: fontWarnings, missing }, { images, warnings: imageWarnings }] = await Promise.all([
diff --git a/packages/pdf/src/server-fonts.test.ts b/packages/pdf/src/server-fonts.test.ts
new file mode 100644
index 000000000..cb4acd776
--- /dev/null
+++ b/packages/pdf/src/server-fonts.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { act } from "react";
+import { defaultResumeData } from "@reactive-resume/schema/resume/default";
+import { createResumePdfFile } from "./server";
+
+// Stub only the PDF engine; exercise the real server entry, renderer and font fetch path.
+vi.mock("@formepdf/core", () => ({
+ prepareFont: undefined,
+ renderSerializedDocWithLayout: () =>
+ Promise.resolve({ pdf: new Uint8Array([1]), layout: { pages: [] }, warnings: [] }),
+}));
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+});
+
+it.each([
+ [undefined, "https://cdn.jsdelivr.net/gh/bitmaks/cm-web-fonts@latest"],
+ [" https://fonts.example.com/cm/// ", "https://fonts.example.com/cm"],
+])("applies server font configuration %s through the rendering pipeline", async (baseUrl, expectedBase) => {
+ vi.stubEnv("WEB_FONT_BASE_URL", baseUrl);
+ const requested: string[] = [];
+ vi.stubGlobal("fetch", (source: URL | string) => {
+ requested.push(String(source));
+ return Promise.resolve(new Response(new Uint8Array([1, 2, 3])));
+ });
+ const data = structuredClone(defaultResumeData);
+ data.basics.name = "Font mirror";
+ data.metadata.typography.body.fontFamily = "Computer Modern Bright";
+ data.metadata.typography.heading.fontFamily = "Computer Modern Bright";
+ const file = await act(() => createResumePdfFile({ data, filename: "mirror.pdf" }));
+ expect(file.type).toBe("application/pdf");
+ expect(requested).toContain(`${expectedBase}/font/Bright/cmunbmr.woff`);
+ expect(
+ requested.filter((url) => url.includes("/font/Bright/")).every((url) => url.startsWith(`${expectedBase}/`)),
+ ).toBe(true);
+});
diff --git a/packages/pdf/src/server.tsx b/packages/pdf/src/server.tsx
index 4c20eb926..29b7b9f6f 100644
--- a/packages/pdf/src/server.tsx
+++ b/packages/pdf/src/server.tsx
@@ -19,6 +19,7 @@ export type CreateResumePdfFileOptions = {
uploadOrigin?: string | undefined;
};
+/** Creates a server PDF using deployment font mirroring and the server image reader. */
export const createResumePdfFile = async ({
filename,
uploadOrigin,
@@ -28,6 +29,7 @@ export const createResumePdfFile = async ({
...input,
data: parseResumeData(input.data),
readImage: (source) => readServerImage(source, uploadOrigin),
+ webFontBaseUrl: process.env.WEB_FONT_BASE_URL,
});
// Characters no font can draw print as "?" rather than failing the file; the editor names them.
assertPdfFonts(result);
diff --git a/turbo.json b/turbo.json
index b8b5e427e..38e7e88a4 100644
--- a/turbo.json
+++ b/turbo.json
@@ -64,6 +64,7 @@
"SERVER_PORT",
"APP_URL",
"ROOT_RESUME_ID",
+ "WEB_FONT_BASE_URL",
"DATABASE_*",
"AUTH_SECRET",
"TRUSTED_PROXIES",
@@ -107,6 +108,7 @@
"SERVER_PORT",
"APP_URL",
"ROOT_RESUME_ID",
+ "WEB_FONT_BASE_URL",
"DATABASE_*",
"AUTH_SECRET",
"TRUSTED_PROXIES",
@@ -151,6 +153,7 @@
"SERVER_PORT",
"APP_URL",
"ROOT_RESUME_ID",
+ "WEB_FONT_BASE_URL",
"DATABASE_*",
"AUTH_SECRET",
"TRUSTED_PROXIES",
@@ -195,6 +198,7 @@
"SERVER_PORT",
"APP_URL",
"ROOT_RESUME_ID",
+ "WEB_FONT_BASE_URL",
"DATABASE_*",
"AUTH_SECRET",
"TRUSTED_PROXIES",
@@ -260,6 +264,7 @@
"SERVER_PORT",
"APP_URL",
"ROOT_RESUME_ID",
+ "WEB_FONT_BASE_URL",
"DATABASE_URL",
"AUTH_SECRET",
"TRUSTED_PROXIES",