perf(static): serve the hashed assets from Brotli copies written at build time

Every file under assets/ was compressed again on each download, at the low
level a request path can afford. They carry their content hash in the name
and never change, so the client build now writes a Brotli copy beside each
compressible one (postbuild, scripts/precompress.mjs) and production points
a browser that accepts Brotli at that copy before express.static serves it.

Measured on a production build of 5.1.2, fetching the 652 precached files
the way a service worker install does: 16.3 MB -> 13.9 MB on the wire and
about 1.0 s -> 0.2 s of server CPU per install. A client without Brotli, a
range request and a build without copies are served exactly as before.
This commit is contained in:
John Jahn
2026-11-10 15:03:28 -05:00
committed by Maurice
parent a9d11ccb2e
commit 04b1fb72bb
9 changed files with 314 additions and 2 deletions
+5 -1
View File
@@ -11,6 +11,7 @@ import { verifyJwtAndLoadUser } from '../auth-core/jwt-verify';
import { withRequestContext } from '../database/request-context';
import { StorageService } from '../storage/storage.service';
import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types';
import { precompressedStatic } from './precompressed-static';
import type { EntityManager } from '@mikro-orm/core';
import express, { Request, Response, NextFunction } from 'express';
@@ -290,7 +291,9 @@ export function applyPlatformSpa(app: express.Application): void {
app.get(/.*/, (req: Request, res: Response) => answerUnmatchedGet(req, res));
}
const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+$/;
// The optional .br is the Brotli copy the client build writes beside a hashed file
// (precompressed-static.ts); it is as immutable as the file it was made from.
const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+(?:\.br)?$/;
/**
* Production static serving of the built client (JS/CSS/assets). Split out from
@@ -302,6 +305,7 @@ const HASHED_ASSET = /[\\/]assets[\\/][^\\/]+-[\w-]{8,}\.\w+$/;
export function applyPlatformStatic(app: express.Application): void {
// Case-sensitive on purpose (legacy parity).
if (readEnv().app.nodeEnv !== 'production') return;
app.use(precompressedStatic(path.join(PUBLIC_DIR, 'assets')));
app.use(
express.static(PUBLIC_DIR, {
setHeaders: (res, filePath) => {
@@ -0,0 +1,58 @@
import express, { type NextFunction, type Request, type Response } from 'express';
import { readdirSync } from 'node:fs';
import path from 'node:path';
const BROTLI_SUFFIX = '.br';
/** Every URL under `urlPrefix` whose file has a Brotli copy beside it. A missing directory holds none. */
function collectPrecompressed(dir: string, urlPrefix: string, into: Set<string>): Set<string> {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return into;
}
for (const entry of entries) {
if (entry.isDirectory()) collectPrecompressed(path.join(dir, entry.name), `${urlPrefix}${entry.name}/`, into);
else if (entry.name.endsWith(BROTLI_SUFFIX)) into.add(`${urlPrefix}${entry.name.slice(0, -BROTLI_SUFFIX.length)}`);
}
return into;
}
/** The Content-Type the static handler gives the original file, charset included, from the same table. */
function contentTypeOf(file: string): string {
const { mime } = express.static;
const type = mime.lookup(file);
const charset = mime.charsets.lookup(type, '');
return charset ? `${type}; charset=${charset}` : type;
}
/**
* Hands a browser that accepts Brotli the copy the client build wrote beside a hashed
* asset (`<file>.br`, client/scripts/precompress.mjs) instead of compressing the file
* again on every download.
*
* It only points the request at the copy and sets the two headers the static handler
* behind it cannot know (the type of the original file, the encoding); that handler
* still sends the file, with its own caching headers, ETag and conditional requests.
* The compression middleware leaves a response that already names its encoding alone.
*
* The copies are listed from disk once, at startup, so only a file the build produced
* is ever rewritten, whatever the request path looks like, and a build without copies
* (a source checkout that skipped the postbuild step) is served as before. A range
* request gets the uncompressed file: its offsets mean the original bytes.
*/
export function precompressedStatic(assetsDir: string, urlPrefix = '/assets/') {
const precompressed = collectPrecompressed(assetsDir, urlPrefix, new Set<string>());
return (req: Request, res: Response, next: NextFunction): void => {
if ((req.method !== 'GET' && req.method !== 'HEAD') || !precompressed.has(req.path)) return next();
// Said for every answer under this URL, so a cache never hands the Brotli bytes
// to a client that did not ask for them.
res.vary('Accept-Encoding');
if (req.headers.range || !req.acceptsEncodings('br')) return next();
res.setHeader('Content-Type', contentTypeOf(req.path));
res.setHeader('Content-Encoding', 'br');
req.url = `${req.path}${BROTLI_SUFFIX}${req.url.slice(req.path.length)}`;
next();
};
}