diff --git a/Readme.md b/Readme.md index ae7d036..f82de56 100644 --- a/Readme.md +++ b/Readme.md @@ -19,7 +19,8 @@ supports both Fastify@1 and Fastify@2. const fastify = require('fastify')() fastify.register(require('fastify-cookie'), { - secret: "my-secret" // for cookies signature + secret: "my-secret", // for cookies signature + parseOptions: {} // options for parsing cookies }) fastify.get('/', (req, reply) => { @@ -47,6 +48,8 @@ as an object named `cookies`. Thus, if a request contains the header `Cookie: foo=foo` then, within your handler, `req.cookies.foo` would equal `'foo'`. +You can pass options to the [cookie parse](https://github.com/jshttp/cookie#cookieparsestr-options) by setting an object named `parseOptions` in the plugin config object. + ### Sending The method `setCookie(name, value, options)` is added to the `reply` object diff --git a/plugin.js b/plugin.js index 4cb372d..9ff0f8a 100644 --- a/plugin.js +++ b/plugin.js @@ -36,10 +36,14 @@ function fastifyCookieClearCookie (reply, name, options) { return fastifyCookieSetCookie(reply, name, '', opts) } -function fastifyCookieOnReqHandler (fastifyReq, fastifyRes, done) { - const cookieHeader = fastifyReq.req.headers.cookie - fastifyReq.cookies = (cookieHeader) ? cookie.parse(cookieHeader) : {} - done() +function onReqHandlerWrapper (options) { + return function fastifyCookieOnReqHandler (fastifyReq, fastifyRes, done) { + const cookieHeader = fastifyReq.req.headers.cookie + if (cookieHeader) { + fastifyReq.cookies = cookie.parse(cookieHeader, options) + } + done() + } } function plugin (fastify, options, next) { @@ -55,7 +59,7 @@ function plugin (fastify, options, next) { fastify.decorateReply('unsignCookie', function unsignCookieWrapper (value) { return cookieSignature.unsign(value, secret) }) - fastify.addHook('onRequest', fastifyCookieOnReqHandler) + fastify.addHook('onRequest', onReqHandlerWrapper(options.parseOptions)) next() } diff --git a/test/cookie.test.js b/test/cookie.test.js index c2d58c5..7d2ab2e 100644 --- a/test/cookie.test.js +++ b/test/cookie.test.js @@ -272,3 +272,43 @@ test('cookies signature', (t) => { }) }) }) + +test('pass options to `cookies.parse`', (t) => { + t.plan(6) + const fastify = Fastify() + fastify.register(plugin, { + parseOptions: { + decode: decoder + } + }) + + fastify.get('/test1', (req, reply) => { + t.ok(req.cookies) + t.ok(req.cookies.foo) + t.is(req.cookies.foo, 'bartest') + reply.send({ hello: 'world' }) + }) + + fastify.listen(0, (err) => { + if (err) tap.error(err) + fastify.server.unref() + + const reqOpts = { + method: 'GET', + baseUrl: 'http://localhost:' + fastify.server.address().port + } + const req = request.defaults(reqOpts) + const headers = { + cookie: 'foo=bar' + } + req({ uri: '/test1', headers }, (err, response, body) => { + t.error(err) + t.strictEqual(response.statusCode, 200) + t.deepEqual(JSON.parse(body), { hello: 'world' }) + }) + }) + + function decoder (str) { + return str + 'test' + } +})