diff --git a/plugin.js b/plugin.js index 66a418a..dd9d17e 100644 --- a/plugin.js +++ b/plugin.js @@ -102,6 +102,11 @@ function setCookies (reply) { } function fastifyCookieOnSendHandler (fastifyReq, fastifyRes, payload, done) { + if (!fastifyRes[kReplySetCookies]) { + done() + return + } + if (fastifyRes[kReplySetCookies].size) { setCookies(fastifyRes) } diff --git a/test/cookie.test.js b/test/cookie.test.js index 48b2f94..6b08813 100644 --- a/test/cookie.test.js +++ b/test/cookie.test.js @@ -1252,3 +1252,25 @@ test('cookies get set correctly if set inside onRequest', (t) => { t.equal(cookies[0].path, '/') }) }) + +test('do not crash if the onRequest hook is not run', (t) => { + t.plan(3) + const fastify = Fastify() + fastify.addHook('onRequest', async (req, reply) => { + return reply.send({ hello: 'world' }) + }) + + fastify.register(plugin) + + fastify.inject({ + method: 'GET', + url: '/test1', + headers: { + cookie: 'foo=foo' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + t.same(JSON.parse(res.body), { hello: 'world' }) + }) +})