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 <marvin@deno.com>
This commit is contained in:
co-authored by
Marvin Hagemeister
parent
bd16a65587
commit
1f9fb91c4d
@@ -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();
|
||||
|
||||
@@ -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",
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user