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!

perf(server): serve brotli, send Early Hints links and purge Cloudflare by tag

Amruth Pillai0e28991fec82
diff --git a/.agents/docs/research/web-performance.md b/.agents/docs/research/web-performance.md
index 39823a1f7..e6a04596f 100644
--- a/.agents/docs/research/web-performance.md
+++ b/.agents/docs/research/web-performance.md
@@ -76,6 +76,13 @@ and the request structure more than the absolute milliseconds.
## Ranked backlog
+**Done since the audit (October 27, 2026):** the Cloudflare Cache Rule for `/assets/*` (owner; the WASM and `.mjs`
+worker now return `HIT`), and four code changes: brotli copies written by the Docker build and served with
+`precompressed: true`; preload `Link` headers for each page's stylesheet and fonts, for Early Hints; `Cache-Tag`
+headers (`html` on pages, `public` on fixed-name files) so the release purge leaves hashed assets cached; and the
+Cloudflare Web Analytics beacon allowed in `script-src`. The zone settings that make the last three take effect
+(Early Hints, Web Analytics, a brotli Compression Rule) are owner actions.
+
### Owner actions in Cloudflare (no code)
1. Cache Rule: cache everything under `/assets/*` (honour origin TTL). Edge-caches the WASM and `.mjs` worker.
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index b8794fe71..26c4b8184 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -456,11 +456,13 @@ jobs:
run: |
set -euo pipefail
+ # Only pages and fixed-name public files, which the server tags (apps/server/src/static/web.ts). Hashed
+ # /assets files never change, so they stay cached across releases.
response=$(curl -fsS --max-time 10 --retry 3 --retry-delay 5 --retry-connrefused -X POST \
"https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/purge_cache" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json" \
- --data '{"purge_everything":true}')
+ --data '{"tags":["html","public"]}')
if [ "$(jq -r '.success' <<< "$response")" != "true" ]; then
echo "$response" | jq .
diff --git a/AGENTS.md b/AGENTS.md
index b9673b17d..2d4346a0d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -227,11 +227,11 @@ docker compose up -d --build
```
- Build outputs: `apps/web/dist` (SPA/assets), `apps/web/dist-prerender` (localized marketing HTML), and `apps/server/dist` (`index.mjs` plus server/deployment chunks). `pnpm start` runs the built server; set `NODE_ENV=production` so it uses `PORT` instead of `SERVER_PORT`. Export runtime variables or provide root `.env`; `.env.local` is not loaded by `start`.
-- Production Compose loads `.env.example` then `.env`, not `.env.local`. Configure `.env` with container hostnames (`postgres`, `redis`, `seaweedfs`) and production secrets before running it. The Docker image runs as `node`, listens on `3000`, and persists local storage through `/app/data`. Health endpoint: `/api/health`.
+- Production Compose loads `.env.example` then `.env`, not `.env.local`. Configure `.env` with container hostnames (`postgres`, `redis`, `seaweedfs`) and production secrets before running it. The Docker image runs as `node`, listens on `3000`, and persists local storage through `/app/data`. Health endpoint: `/api/health`. Its build also writes brotli copies (`*.br`) of the web app's text files and WASM (`tooling/docker/precompress.mjs`), which the server sends to browsers that accept brotli.
- `vercel.json` defines Vercel Services (project framework must be `Services`): `frontend` (`apps/web`, static `dist`) and `backend` (`apps/server`, entrypoint `apps/server/vercel.mjs` re-exporting the tsdown build). The backend build runs `pnpm build` for both apps, then `node apps/server/dist/prepare-deployment.mjs`. Top-level rewrites send paths whose last segment has a file extension to `frontend` and everything else, including HTML shells, to `backend`, except the server-owned paths listed first. The Function uses Node 24 and a 300-second budget. `outputDirectory: "."` on `backend` stops the builder from treating `dist/index.mjs` (the Docker entrypoint) as the handler.
- Vercel environment normalization accepts `POSTGRES_URL`, direct/unpooled DB aliases, and `KV_URL`. `APP_URL` can be derived from Vercel host variables. Blob is the default when no S3 credentials are set. Preview deployments require isolated resources before enabling `ALLOW_PREVIEW_MIGRATIONS=true`; see `docs/self-hosting/vercel.mdx`.
- `.github/workflows/ci.yml` is the CI workflow: unit/browser tests and Vercel and Cloudflare compatibility run as separate jobs on PRs and pushes to `main`. `autofix.yml` runs write-capable autofix (`pnpm knip --fix` and `pnpm check`) separately because autofix.ci requires its own workflow name. Manual runs default to CI; `live_smoke=true` runs only the dedicated deployment smoke test. `issue-maintenance.yml` combines issue-form labeling with scheduled needs-info cleanup. GitHub runners are the default; `USE_BLACKSMITH=true` switches runners and paired actions.
-- `docker-publish.yml` publishes native AMD64/ARM64 images. `main` publishes nightly aliases; release tags/explicit release dispatch publish stable aliases and can trigger configured production integrations. See `.agents/docs/container-publishing.md` before release work.
+- `docker-publish.yml` publishes native AMD64/ARM64 images. `main` publishes nightly aliases; release tags/explicit release dispatch publish stable aliases and can trigger configured production integrations. The production Cloudflare purge removes only the `html` and `public` cache tags that `apps/server/src/static/web.ts` sets; hashed `/assets/*` stay cached across releases. See `.agents/docs/container-publishing.md` before release work.
- Deployment smoke tests create/delete accounts and files; run only against a dedicated test installation. Details: `docs/contributing/deployment-checks.mdx`.
## Security and pull requests
diff --git a/Dockerfile b/Dockerfile
index 5014498a1..b1715b3b5 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -38,6 +38,9 @@ COPY --from=pruner /app/package.json /app/.gitignore /app/vite.config.ts /app/vi
ARG TURBO_TEAM
RUN --mount=type=secret,id=TURBO_TOKEN,env=TURBO_TOKEN \
TURBO_TEAM=${TURBO_TEAM} pnpm turbo run build --filter=web --filter=server
+# Brotli copies of the web app's text files and WASM, which the server sends to browsers that accept brotli.
+COPY --from=pruner /app/tooling/docker/precompress.mjs ./tooling/docker/precompress.mjs
+RUN node tooling/docker/precompress.mjs apps/web/dist
FROM base AS runtime-pruner
COPY . .
diff --git a/apps/server/src/static/web.test.ts b/apps/server/src/static/web.test.ts
index fe3fb6ff9..1fabbe32d 100644
--- a/apps/server/src/static/web.test.ts
+++ b/apps/server/src/static/web.test.ts
@@ -27,6 +27,9 @@ vi.mock("@reactive-resume/env/server", () => ({
const { handleWebApp } = await import("./web");
+const searchLink =
+ '<https://context7.com/api/v2/ask?siteKey=ask_b3fd9335a63f1b21b1a814ac>; rel="search"; type="text/plain"; title="Search rxresu.me"';
+
describe("web app fallback classification", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -47,11 +50,9 @@ describe("web app fallback classification", () => {
);
expect(html).toContain('</blockquote><div id="app"></div>');
expect(html).not.toContain("Add .md");
- const link =
- '<https://context7.com/api/v2/ask?siteKey=ask_b3fd9335a63f1b21b1a814ac>; rel="search"; type="text/plain"; title="Search rxresu.me"';
- expect(response.headers.get("Link")).toBe(link);
+ expect(response.headers.get("Link")).toBe(searchLink);
const head = await handleWebApp(new Request(`https://rxresu.me${path}`, { method: "HEAD" }));
- expect(head.headers.get("Link")).toBe(link);
+ expect(head.headers.get("Link")).toBe(searchLink);
expect(await head.text()).toBe("");
},
);
@@ -158,7 +159,20 @@ describe("web app fallback classification", () => {
const scripts = response.headers.get("Content-Security-Policy")?.match(/script-src ([^;]*)/)?.[1];
expect(scripts).toBe(
- `'self' 'wasm-unsafe-eval' 'sha256-${createHash("sha256").update("boot()").digest("base64")}'`,
+ `'self' 'wasm-unsafe-eval' https://static.cloudflareinsights.com 'sha256-${createHash("sha256").update("boot()").digest("base64")}'`,
+ );
+ });
+
+ it("tags pages for the release purge and preloads their stylesheet and fonts for Early Hints", async () => {
+ const response = await handleWebApp(
+ new Request("https://example.com/"),
+ async () =>
+ '<html><head><link rel="icon" href="/favicon.ico"><link rel="stylesheet" crossorigin href="/assets/index-a.css"><link rel="preload" as="font" type="font/woff2" href="/assets/figtree-b.woff2" crossorigin></head><body><div id="app"></div></body></html>',
+ );
+
+ expect(response.headers.get("Cache-Tag")).toBe("html");
+ expect(response.headers.get("Link")).toBe(
+ `${searchLink}, </assets/index-a.css>; rel=preload; as=style; crossorigin, </assets/figtree-b.woff2>; rel=preload; as=font; crossorigin`,
);
});
diff --git a/apps/server/src/static/web.ts b/apps/server/src/static/web.ts
index 2c00ce834..c6d97e323 100644
--- a/apps/server/src/static/web.ts
+++ b/apps/server/src/static/web.ts
@@ -68,7 +68,8 @@ export function isProfilePath(pathname: string): boolean {
* Scripts run only from the app's own files and the inline scripts of the page served, allowed by hash; `wasm-unsafe-eval`
* lets the PDF engine (Forme, WebAssembly) start. Pictures, avatars and fonts can live on any https host (a resume's
* picture URL, a sign-in provider's avatar) and the PDF engine fetches them, so images, fonts and connections stay open
- * to https. Recordings, previews and workers use blob: URLs.
+ * to https. Recordings, previews and workers use blob: URLs. Cloudflare Web Analytics, when turned on for the zone, injects
+ * its real-user metrics beacon from static.cloudflareinsights.com.
*/
export function contentSecurityPolicy(html = "") {
const inlineScripts = html.matchAll(
@@ -82,7 +83,7 @@ export function contentSecurityPolicy(html = "") {
);
return [
"default-src 'self'",
- ["script-src 'self' 'wasm-unsafe-eval'", ...hashes].join(" "),
+ ["script-src 'self' 'wasm-unsafe-eval' https://static.cloudflareinsights.com", ...hashes].join(" "),
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https:",
"font-src 'self' data: https:",
@@ -105,6 +106,24 @@ export const BASE_SECURITY_HEADERS = {
"Content-Security-Policy": contentSecurityPolicy(),
};
+/**
+ * Preload links for the stylesheet and fonts a page's <head> loads. Cloudflare sends them ahead of the page as 103 Early
+ * Hints, so they download while the origin is still answering.
+ */
+function preloadLinks(html: string) {
+ const end = html.indexOf("</head>");
+ const head = end === -1 ? html : html.slice(0, end);
+ return [...head.matchAll(/<link\b[^>]*>/g)].flatMap(([tag]) => {
+ const href = tag.match(/\bhref="(\/assets\/[^"]+)"/)?.[1];
+ // The preload must share the tag's CORS mode, or the browser downloads the file twice.
+ const cors = /\scrossorigin\b/.test(tag) ? "; crossorigin" : "";
+ if (href && /\brel="stylesheet"/.test(tag)) return [`<${href}>; rel=preload; as=style${cors}`];
+ if (href && /\brel="preload"/.test(tag) && /\bas="font"/.test(tag))
+ return [`<${href}>; rel=preload; as=font${cors}`];
+ return [];
+ });
+}
+
/**
* An HTML page whose policy allows exactly the inline scripts of its template. Hashes come from the template before
* any resume-derived markup goes in, so text that slipped past escaping could never allow itself.
@@ -115,7 +134,16 @@ function htmlResponse(html: string, headers: Record<string, string>, template =
const body = html
.replace("</head>", () => `<meta name="context7-site-verification" content="${verification}"></head>`)
.replace(/<body\b[^>]*>/i, (tag) => `${tag}${note}`);
- return new Response(body, { headers: { ...headers, "Content-Security-Policy": contentSecurityPolicy(template) } });
+ return new Response(body, {
+ headers: {
+ ...headers,
+ Link: [headers.Link, ...preloadLinks(template)].filter(Boolean).join(", "),
+ // Pages name the current build's assets, so a release purges this tag from Cloudflare's cache
+ // (.github/workflows/docker-publish.yml).
+ "Cache-Tag": "html",
+ "Content-Security-Policy": contentSecurityPolicy(template),
+ },
+ });
}
const githubUrl = "https://github.com/reactive-resume/reactive-resume";
@@ -256,11 +284,14 @@ export const serveWebDistStatic = env.CLOUDFLARE
? undefined
: serveStatic({
root: staticRoot,
+ // The Docker build writes brotli copies beside the text files and WASM (tooling/docker/precompress.mjs).
+ precompressed: true,
onFound: (_path, context) => {
- // Vite fingerprints everything under /assets, so a file there never changes.
- if (context.req.path.startsWith("/assets/") || /^\/videos\/.*-v\d+\.(?:mp4|webp)$/.test(context.req.path)) {
+ // Vite fingerprints everything under /assets, so a file there never changes. Other files keep their names
+ // when their content changes, so a release purges them from Cloudflare's cache by this tag.
+ if (context.req.path.startsWith("/assets/"))
context.header("Cache-Control", "public, max-age=31536000, immutable");
- }
+ else context.header("Cache-Tag", "public");
// `/index.html` is the app shell too; it must not be frameable either.
if (context.req.path.endsWith(".html"))
for (const [name, value] of Object.entries(BASE_SECURITY_HEADERS)) context.header(name, value);
diff --git a/tooling/docker/precompress.mjs b/tooling/docker/precompress.mjs
new file mode 100644
index 000000000..7f99f00aa
--- /dev/null
+++ b/tooling/docker/precompress.mjs
@@ -0,0 +1,44 @@
+// Writes a brotli copy (`<file>.br`) beside each text file and WASM module in the built web app. The server's static
+// handler sends it to browsers that accept brotli (apps/server/src/static/web.ts); the rest get gzip on the fly.
+// Usage: node tooling/docker/precompress.mjs apps/web/dist
+import { readdir, readFile, writeFile } from "node:fs/promises";
+import { extname, join } from "node:path";
+import { promisify } from "node:util";
+import { brotliCompress, constants } from "node:zlib";
+
+const [root] = process.argv.slice(2);
+if (!root) throw new Error("Usage: node tooling/docker/precompress.mjs <directory>");
+
+const compress = promisify(brotliCompress);
+// HTML pages aren't here: the server rewrites them per request and compresses them then.
+const text = new Set([".css", ".js", ".json", ".mjs", ".svg", ".txt", ".webmanifest", ".xml"]);
+
+const entries = await readdir(root, { recursive: true, withFileTypes: true });
+const files = entries
+ .filter((entry) => entry.isFile() && (text.has(extname(entry.name)) || extname(entry.name) === ".wasm"))
+ .map((entry) => join(entry.parentPath, entry.name));
+
+let before = 0;
+let after = 0;
+await Promise.all(
+ files.map(async (file) => {
+ const data = await readFile(file);
+ // The server doesn't compress responses under 1 KiB either.
+ if (data.byteLength < 1024) return;
+ const brotli = await compress(data, {
+ params: {
+ [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,
+ [constants.BROTLI_PARAM_MODE]: text.has(extname(file))
+ ? constants.BROTLI_MODE_TEXT
+ : constants.BROTLI_MODE_GENERIC,
+ [constants.BROTLI_PARAM_SIZE_HINT]: data.byteLength,
+ },
+ });
+ if (brotli.byteLength >= data.byteLength) return;
+ await writeFile(`${file}.br`, brotli);
+ before += data.byteLength;
+ after += brotli.byteLength;
+ }),
+);
+
+console.log(`Precompressed ${(before / 1e6).toFixed(1)} MB to ${(after / 1e6).toFixed(1)} MB of brotli.`);