Skip to content

Commit

Permalink
feat: support maxAge for public assets (#860)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Jan 20, 2023
1 parent 3d61ebf commit 71576c0
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 11 deletions.
13 changes: 12 additions & 1 deletion src/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
import { resolve } from "pathe";
import { createHooks, createDebugger } from "hookable";
import { createUnimport } from "unimport";
import defu from "defu";
import consola from "consola";
import type { NitroConfig, Nitro } from "./types";
import { loadOptions } from "./options";
Expand Down Expand Up @@ -61,7 +62,17 @@ export async function createNitro(config: NitroConfig = {}): Promise<Nitro> {
asset.baseURL = asset.baseURL || "/";
const isTopLevel = asset.baseURL === "/";
asset.fallthrough = asset.fallthrough ?? isTopLevel;
asset.maxAge = asset.maxAge ?? (isTopLevel ? 0 : 60);
asset.maxAge = asset.maxAge ?? 0;
if (asset.maxAge && !asset.fallthrough) {
options.routeRules[asset.baseURL + "/**"] = defu(
options.routeRules[asset.baseURL + "/**"],
{
headers: {
"cache-control": `public, max-age=${asset.maxAge}, immutable`,
},
}
);
}
}

// Server assets
Expand Down
5 changes: 2 additions & 3 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,9 @@ export async function loadOptions(
app: {
baseURL: options.baseURL,
},
nitro: {
routeRules: options.routeRules,
},
nitro: {},
});
options.runtimeConfig.nitro.routeRules = options.routeRules;

for (const publicAsset of options.publicAssets) {
publicAsset.dir = resolve(options.srcDir, publicAsset.dir);
Expand Down
6 changes: 0 additions & 6 deletions src/runtime/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,5 @@ export default eventHandler((event) => {
event.node.res.setHeader("Content-Length", asset.size);
}

// TODO: Asset dir cache control
// if (isBuildAsset) {
// const TWO_DAYS = 2 * 60 * 60 * 24
// event.node.res.setHeader('Cache-Control', `max-age=${TWO_DAYS}, immutable`)
// }

return readAsset(id);
});
3 changes: 2 additions & 1 deletion test/fixture/nitro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ export default defineNitroConfig({
{
baseName: "files",
dir: "files",
}
},
],
publicAssets: [
{
baseURL: "build",
dir: "public/build",
maxAge: 3600,
},
],
nodeModulesDirs: ["./_/node_modules"],
Expand Down

0 comments on commit 71576c0

Please sign in to comment.