Skip to content

Commit

Permalink
fix: add proper cache control headers (#2617)
Browse files Browse the repository at this point in the history
The whole point of `asset()` is to enable caching. Yet we were not
adding cache control headers... :D

---------

Co-authored-by: Marvin Hagemeister <[email protected]>
  • Loading branch information
lucacasonato and marvinhagemeister authored Aug 13, 2024
1 parent bd16a65 commit 1f9fb91
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/middlewares/static_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ export function staticFiles<T>(): MiddlewareFn<T> {
}
}

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();
Expand Down
28 changes: 28 additions & 0 deletions src/middlewares/static_files_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
);
});
2 changes: 1 addition & 1 deletion tests/test_utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down

0 comments on commit 1f9fb91

Please sign in to comment.