I would like to be able to control the API cache headers (per global / collection). Currently it seems like the default behavior of the API is to return a "Cache-Control: private", but I would rather have it respond with something like "Cache-Control: max-age=604800, stale-while-revalidate=86400". I could control this at the reverse proxy, but it makes more sense to have the application control this (and also more common), preferably with global defaults and global / collection overrides. Is there anything currenlty in Payload that enables me to do this? I could add express middleware, but based on the Github it seems like express could be deprecated in favour of Next.
For anyone finding this; I did end up using Express middleware, we'll see where it ends up when and if express is dropped in favour of next.
I ended up with a solution that still allowed me to configure caching on a collection / global level, which is captured and set by middleware. Here is the gist
https://gist.github.com/Swahjak/501e9c58551cd5433707d4bd2b737f4eWould you mind sharing the code used to solve this? I am also needing to do this soon.
Thank you for sharing!
That hook is awesome
@372724903499005954
I'll mark this thread as solved then
Hey I tried to use the hook as follows
app.use((req, res, next) => useCache(req, res, next));
but I'm still not getting any cache control showing in my browser, I've also set the custom field as follows
cacheControl: "public, max-age=300, stale-while-revalidate=300, stale-if-error=86400",
in my media collection..
- i'm trying to use your useCache hook above. I put it here:
express: {
// preMiddleware: [
// (req, res, next) => {
// useCache(req, res, next);
// },
// ],
postMiddleware: [
(req, res, next) => {
useCache(req, res, next);
},
],
},
in the payload.config.ts
But I never (ever?) have req.collection be anything other than undefined, so
//console.log(req.collection.config.custom?.cacheControl);
if (req.collection && req.collection.config.custom?.cacheControl) {
const cacheControl = req.collection.config.custom.cacheControl;
req.payload.logger.info(`Cache-Control: ${cacheControl}`);
res.set('Cache-Control', cacheControl);
next();
return;
}
never runs
Thoughts?
Star
Discord
online
Get dedicated engineering support directly from the Payload team.