From 1f9fb91c4dbd2cd80c282cf09c6aede7c8e5660c Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Tue, 13 Aug 2024 14:15:25 +0200 Subject: [PATCH] fix: add proper cache control headers (#2617) The whole point of `asset()` is to enable caching. Yet we were not adding cache control headers... :D --------- Co-authored-by: Marvin Hagemeister --- src/middlewares/static_files.ts | 4 ++++ src/middlewares/static_files_test.ts | 28 ++++++++++++++++++++++++++++ tests/test_utils.tsx | 2 +- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/middlewares/static_files.ts b/src/middlewares/static_files.ts index a21f7cb2bf2..2ae81ba05c1 100644 --- a/src/middlewares/static_files.ts +++ b/src/middlewares/static_files.ts @@ -79,6 +79,10 @@ export function staticFiles(): MiddlewareFn { } } + if (BUILD_ID === cacheKey) { + headers.append("Cache-Control", "public, max-age=31536000, immutable"); + } + headers.set("Content-Length", String(file.size)); if (req.method === "HEAD") { file.close(); diff --git a/src/middlewares/static_files_test.ts b/src/middlewares/static_files_test.ts index de40d6bc378..5dc04596b51 100644 --- a/src/middlewares/static_files_test.ts +++ b/src/middlewares/static_files_test.ts @@ -153,3 +153,31 @@ Deno.test("static files - disables caching in development", async () => { "no-cache, no-store, max-age=0, must-revalidate", ); }); + +Deno.test("static files - enables caching in production", async () => { + const buildCache = new MockBuildCache({ + "foo.css": { content: "body {}", hash: null }, + }); + const server = serveMiddleware( + staticFiles(), + { + buildCache, + config: { + basePath: "", + build: { + outDir: "", + }, + mode: "production", + root: ".", + staticDir: "", + }, + }, + ); + + const res = await server.get(`/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`); + await res.body?.cancel(); + expect(res.status).toEqual(200); + expect(res.headers.get("Cache-Control")).toEqual( + "public, max-age=31536000, immutable", + ); +}); diff --git a/tests/test_utils.tsx b/tests/test_utils.tsx index 123f5cf09a3..5df7881886c 100644 --- a/tests/test_utils.tsx +++ b/tests/test_utils.tsx @@ -155,7 +155,7 @@ export async function withChildProcessServer( for await (const line of lines.values({ preventCancel: true })) { output.push(line); const match = line.match( - /https?:\/\/localhost:\d+(\/\w+[-\w]*)*/g, + /https?:\/\/[^:]+:\d+(\/\w+[-\w]*)*/g, ); if (match) { address = match[0];