apicache icon indicating copy to clipboard operation
apicache copied to clipboard

Headers cannot be overwritten when cached response is served

Open apascal opened this issue 6 years ago • 3 comments

Headers cannot be overwritten with the global options, since ^1.4.0 and https://github.com/kwhitley/apicache/commit/beaaa70076bdaaa94008638f500f87c940197713

When a cached response is delivered, regardless of globalOptions.headers, headers are overwritten with the decrementing max-age value. The global headers still work when the response is cached the first time.

This is not the expected behaviour as these headers are in my opinion meant to be used whatever the cached response is.

We had to revert to apicache@^1.3.1 in order to be able to force the headers (see #165 why).

apascal avatar Apr 05 '19 21:04 apascal

When this issue will be sorted in new release ?

globalOptions.headers should not be overwritten with the decrementing max-age value.

manojktechie avatar Sep 13 '19 07:09 manojktechie

I bumped into the same problem and as a workaround I made a wrapper for cache middleware that passes it augmented writeHead function that overrides headers just before sending them to the client:

const apicache = require('apicache');

const baseCache = apicache.options({
  headers: {
    'cache-control': 'no-cache',
  },
}).middleware;

const cache = function() {
  const baseCacheArgs = arguments;
  return (req, res, next) => {
    const writeHead = res.writeHead;
    res.writeHead = function (statusCode, statusMessage, headers) {
      // For why this is needed see docs at https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers
      headers = typeof statusMessage == 'object' && typeof headers == 'undefined' ? statusMessage : headers;
      if (headers) {
        headers['cache-control'] = 'no-cache';
      }
      return writeHead.call(this, statusCode, headers);
    };
    baseCache(baseCacheArgs)(req, res, next);
  }
}

I needed to cache the responses on the backend, but have the client always make requests as I clear the cache backend-side on some conditions.

0x48Maciek avatar Feb 26 '20 08:02 0x48Maciek