Skip to content

🎥 Make videos programmatically with React

Docs: Serve uncacheable 404s for missing assets (#10105)

Jonny Burger8e2d2b778326
diff --git a/packages/docs/build-docs.ts b/packages/docs/build-docs.ts
index 85b181268b..cc931188c4 100644
--- a/packages/docs/build-docs.ts
+++ b/packages/docs/build-docs.ts
@@ -133,4 +133,5 @@ await run(
docusaurusEnv,
);
await run('copy convert assets', 'bun', ['copy-convert.ts']);
+await run('generate asset manifest', 'bun', ['generate-asset-manifest.ts']);
await run('count generated pages', 'bun', ['count-pages.ts']);
diff --git a/packages/docs/generate-asset-manifest.ts b/packages/docs/generate-asset-manifest.ts
new file mode 100644
index 0000000000..b72a141dd6
--- /dev/null
+++ b/packages/docs/generate-asset-manifest.ts
@@ -0,0 +1,50 @@
+import fs from 'fs';
+import path from 'path';
+
+// The Vercel header rule for /assets/(.*) applies `max-age=31536000, immutable`
+// to 404s as well, so browsers and CDNs can cache a "not found" for a year.
+// This manifest lets middleware.ts distinguish real assets from misses and
+// serve the misses with `Cache-Control: no-store` instead.
+const buildDir = path.join(__dirname, 'build');
+const assetsDir = path.join(buildDir, 'assets');
+
+if (!fs.existsSync(assetsDir)) {
+ throw new Error(
+ `Expected ${assetsDir} to exist - run the Docusaurus build first`,
+ );
+}
+
+const files: string[] = [];
+
+const walk = (dir: string) => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full);
+ } else if (entry.isFile()) {
+ files.push(
+ '/assets/' + path.relative(assetsDir, full).split(path.sep).join('/'),
+ );
+ }
+ }
+};
+
+walk(assetsDir);
+files.sort();
+
+// A wrongly empty manifest would make the middleware 404 every asset.
+// A real Docusaurus build emits thousands of files under /assets.
+if (files.length < 100) {
+ throw new Error(
+ `Only found ${files.length} files under build/assets - refusing to write asset-manifest.json`,
+ );
+}
+
+fs.writeFileSync(
+ path.join(buildDir, 'asset-manifest.json'),
+ JSON.stringify(files),
+);
+
+console.log(
+ `[docs build] Wrote asset-manifest.json with ${files.length} entries`,
+);
diff --git a/packages/docs/middleware.ts b/packages/docs/middleware.ts
index 32362fa1c4..3492c1abc7 100644
--- a/packages/docs/middleware.ts
+++ b/packages/docs/middleware.ts
@@ -1,9 +1,42 @@
import {rewrite} from '@vercel/functions';
export const config = {
- matcher: ['/pricing', '/docs/:path*', '/elements', '/elements.md', '/elements/:path*'],
+ matcher: [
+ '/pricing',
+ '/docs/:path*',
+ '/elements',
+ '/elements.md',
+ '/elements/:path*',
+ '/assets/:path*',
+ ],
};
+let assetManifestPromise: Promise<Set<string> | null> | null = null;
+
+// Lists every file under /assets of the current deployment, generated by
+// generate-asset-manifest.ts during the build. Fetched once per edge instance;
+// middleware and static files deploy atomically, so it is always in sync.
+function getAssetManifest(origin: string): Promise<Set<string> | null> {
+ if (!assetManifestPromise) {
+ assetManifestPromise = fetch(new URL('/asset-manifest.json', origin))
+ .then(async (res) => {
+ if (!res.ok) {
+ throw new Error(`Manifest returned status ${res.status}`);
+ }
+
+ return new Set((await res.json()) as string[]);
+ })
+ .catch(() => {
+ // Fail open: without a manifest, requests fall through to static
+ // serving (the pre-existing behavior). Retry on the next request.
+ assetManifestPromise = null;
+ return null;
+ });
+ }
+
+ return assetManifestPromise;
+}
+
function parseAcceptHeader(acceptHeader: string): string[] {
return acceptHeader
.split(',')
@@ -55,16 +88,50 @@ function prefersMarkdown(
return false;
}
-export default function middleware(request: Request) {
+export default async function middleware(request: Request) {
const url = new URL(request.url);
const pathname = url.pathname;
+ if (pathname.startsWith('/assets/')) {
+ // Assets are content-hashed and vercel.ts marks /assets/(.*) as
+ // `max-age=31536000, immutable`. Vercel applies that header to 404s too,
+ // so a missing asset (e.g. requested by stale HTML after a deploy) would
+ // be cached as "not found" for a year by browsers and CDNs. Serve misses
+ // as uncacheable 404s instead; real files fall through to static serving.
+ let decodedPathname = pathname;
+ try {
+ decodedPathname = decodeURIComponent(pathname);
+ } catch {
+ // Not decodable - cannot match a real file, will 404 below.
+ }
+
+ const manifest = await getAssetManifest(url.origin);
+ if (manifest && !manifest.has(decodedPathname)) {
+ return new Response('Not Found', {
+ status: 404,
+ headers: {
+ 'Cache-Control': 'no-store',
+ 'Content-Type': 'text/plain; charset=utf-8',
+ 'X-Asset-404': 'not-in-manifest',
+ },
+ });
+ }
+
+ return;
+ }
+
if (pathname === '/pricing') {
- return Response.redirect(new URL('/docs/license/pricing', request.url), 308);
+ return Response.redirect(
+ new URL('/docs/license/pricing', request.url),
+ 308,
+ );
}
if (pathname === '/docs/pricing') {
- return Response.redirect(new URL('/docs/license/pricing', request.url), 308);
+ return Response.redirect(
+ new URL('/docs/license/pricing', request.url),
+ 308,
+ );
}
if (pathname === '/docs/license-pricing-compliance/faq') {
diff --git a/packages/docs/src/test/middleware.test.ts b/packages/docs/src/test/middleware.test.ts
index bce5e861e6..403800d312 100644
--- a/packages/docs/src/test/middleware.test.ts
+++ b/packages/docs/src/test/middleware.test.ts
@@ -1,8 +1,10 @@
import {expect, test} from 'bun:test';
import middleware from '../../middleware';
-test('rewrites /elements.md to the Elements overview raw markdown', () => {
- const response = middleware(new Request('https://remotion.dev/elements.md'));
+test('rewrites /elements.md to the Elements overview raw markdown', async () => {
+ const response = await middleware(
+ new Request('https://remotion.dev/elements.md'),
+ );
expect(response).toBeInstanceOf(Response);
expect(response.headers.get('x-middleware-rewrite')).toBe(