inert icon indicating copy to clipboard operation
inert copied to clipboard

Disabling `must-revalidate` when serving static files via Inert

Open pgayvallet opened this issue 3 years ago • 1 comments

Support plan

  • is this issue currently blocking your project? (yes/no): no
  • is this issue affecting a production system? (yes/no): no

Context

  • node version: 16.14.2
  • module version: 6.0.5
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): hapi application
  • any other relevant information: N/A

How can we help?

I'd like to implement a cache-busting mechanism based on filepath, meaning that I'd like to have the cache-control header be (exclusively) max-age={MAX_AGE}, immutable

However, I can't find a way to not have Inert (or HAPI?) adds the must-revalidate directive to this header (or to add immutable to it fwiw).

The way we're configuring our route:

server.route({
      path,
      method: 'GET',
      handler: {
        directory: {
          path: dirPath,
          listing: false,
          lookupCompressed: true,
          etagMethod : false,
        },
      },
      options: {
        auth: false,
        cache: {
          privacy: 'default',
          otherwise: 'immutable',
          expiresIn: 365 * 24 * 60 * 60 * 1000,
        },
      },
    });

When calling the endpoint, the must-revalidate is added

Expected: "max-age=31536000, immutable"
Received: "max-age=31536000, must-revalidate"

Is there any way to prevent inert from adding the must-revalidate directive when serving the files, and to add custom directives (e.g immutable)?

pgayvallet avatar Apr 11 '22 08:04 pgayvallet

Unfortunately the must-revalidate parameter is currently hardcoded in hapi, and inert cannot change this. It would be nice if hapi had an option to customise this and add other parameters like immutable.

If you don't want to change hapi, the best option is to set the cache-control header yourself, which causes the default logic to be disabled. This can be done in a route-specific ext handler, eg.:

options: {
    …,
    ext: {
        onPostHandler(request, h) {

            const response = request.response;
            const ttl = Math.floor(response.settings.ttl, 1000);
            response.header('cache-control', `max-age=${ttl}, immutable`);

            return h.continue;
        }
    }
}

I guess inert could do this and expose an option, but I really think that this should be fixed in hapi itself.

FYI, otherwise is used when caching is disable for the response, eg. for responses to a POST request, or when the response ttl is 0.

kanongil avatar Apr 11 '22 08:04 kanongil