From b35946dfcf1a64899cdbcb1c00c9f0aff2145fcb Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Wed, 2 Aug 2023 15:39:37 +0200 Subject: [PATCH] Fix support for response that does not set a cookie Signed-off-by: Matteo Collina --- plugin.js | 5 +++++ test/cookie.test.js | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+) 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' }) + }) +})