Why public is always returned as default Cache-Control value?
#1440
Replies: 1 comment
|
It is hardcoded. In src/utils/cache.ts the first line of handleCacheHeaders builds the header as: const cacheControls = ["public", ...(opts.cacheControls || [])];so "public" is always prepended no matter what you pass in cacheControls, and passing ["private"] gives you a contradictory "public, private, ..." header. There is no option to suppress it right now, so I would call this a bug (or at least a missing escape hatch) rather than intentional design. Workaround until that changes: overwrite the header right after the call, since handleCacheHeaders sets it with headers.set and a later set wins: const matched = handleCacheHeaders(event, { etag, maxAge: 3600 });
event.res.headers.set("cache-control", "private, max-age=3600");
if (matched) return;For Nitro's defineCachedEventHandler there is no exposed knob for this either, so the same post-hoc header override in the handler (or a response middleware/plugin that rewrites cache-control for the affected routes) is the practical fix. Worth filing an issue proposing that h3 only defaults to "public" when the caller did not pass any cacheControls at all. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Where it is Implemented
https://github.com/h3js/h3/blob/main/src/utils/cache.ts
Also at line 12 it is stated that:
// * Note: `public` cache control will be added by defaultAs stated at the comment we see in the implementation:
Was this default
publicbehavior intentional? This way it is impossible to return aprivatecache withhandleCacheHeaders(event, opts)therefore nitro'sdefineCachedHandleras well.Though in nitro using
defineCachedFunctionomits this "add these default headers" completely but that outputs a json which is not exactly what we always want.So does h3 (or Nitro on top of it) give you any other way to manually overwrite the cache-control header afterward, outside this function?
As far as I looked around there is no proven or mentioned way.
at least one person has reported this doesn't work #1945, and I couldn't find any documented override method
All reactions