diff --git a/index.js b/index.js index 236ddf3..dfc2184 100644 --- a/index.js +++ b/index.js @@ -75,7 +75,9 @@ function fastifyCaching (instance, options, next) { } instance.addHook('onRequest', (req, res, next) => { - res.header('Cache-control', value) + if (res.hasHeader('Cache-control') === false) { + res.header('Cache-control', value) + } next() }) } diff --git a/test/headers.test.js b/test/headers.test.js index d941239..9afd1ea 100644 --- a/test/headers.test.js +++ b/test/headers.test.js @@ -139,6 +139,35 @@ test('sets public with max-age and s-maxage header', async (t) => { t.equal(response.headers['cache-control'], 'public, max-age=300, s-maxage=12345') }) +test('do not set headers if another upstream plugin already sets it', async (t) => { + t.plan(2) + + const opts = { + privacy: plugin.privacy.PUBLIC, + expiresIn: 300, + serverExpiresIn: 12345 + } + + const fastify = Fastify() + fastify.addHook('onRequest', async (req, reply) => { + reply.header('cache-control', 'do not override') + }) + await fastify.register(plugin, opts) + + fastify.get('/', (req, reply) => { + reply.send({ hello: 'world' }) + }) + + await fastify.ready() + + const response = await fastify.inject({ + method: 'GET', + path: '/' + }) + t.ok(response.headers['cache-control']) + t.equal(response.headers['cache-control'], 'do not override') +}) + test('only sets max-age and ignores s-maxage with private header', async (t) => { t.plan(2)