hapijs / inert

Static file and directory handlers for hapi.js
Other
238 stars 49 forks source link

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

Open pgayvallet opened 2 years ago

pgayvallet commented 2 years ago

Support plan

Context

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)?

kanongil commented 2 years ago

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.