A plugin for Fastify that adds support for reading and setting cookies.
This plugin's cookie parsing works via Fastify's onRequest hook. Therefore,
you should register it prior to any other onRequest hooks that will depend
upon this plugin's actions.
fastify-cookie v2.x
supports both Fastify@1 and Fastify@2.
fastify-cookie v3 only supports Fastify@2.
const fastify = require('fastify')()
fastify.register(require('fastify-cookie'), {
secret: "my-secret", // for cookies signature
parseOptions: {} // options for parsing cookies
})
fastify.get('/', (req, reply) => {
const aCookieValue = req.cookies.cookieName
const bCookieValue = reply.unsignCookie(req.cookies.cookieSigned);
reply
.setCookie('foo', 'foo', {
domain: 'example.com',
path: '/'
})
setCookie('bar', 'bar', {
path: '/',
signed: true
})
.send({hello: 'world'})
})Cookies are parsed in the onRequest Fastify hook and attached to the request
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 by setting an object named parseOptions in the plugin config object.
The method setCookie(name, value, options) is added to the reply object
via the Fastify decorateReply API. Thus, in a request handler,
reply.setCookie('foo', 'foo', {path: '/'}) will set a cookie named foo
with a value of 'foo' on the cookie path /.
name: a string name for the cookie to be setvalue: a string value for the cookieoptions: an options object as described in the cookie serialize with a extra param "signed" for signed cookie documentation
The method clearCookie(name, options) is added to the reply object
via the Fastify decorateReply API. Thus, in a request handler,
reply.clearCookie('foo', {path: '/'}) will clear a cookie named foo
on the cookie path /.
name: a string name for the cookie to be clearedoptions: an options object as described in the cookie serialize documentation. Its optional to passoptionsobject