Get unlimited public & private packages + package-based permissions with npm Pro.Get started »

fastify-cookie

3.6.0 • Public • Published

fastify-cookie

Greenkeeper badge Build Status

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.

Example

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'})
})

API

Parsing

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.

Sending

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 set
  • value: a string value for the cookie
  • options: an options object as described in the cookie serialize with a extra param "signed" for signed cookie documentation

Clearing

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 cleared
  • options: an options object as described in the cookie serialize documentation. Its optional to pass options object

License

MIT License

Install

npm i fastify-cookie

DownloadsWeekly Downloads

10,949

Version

3.6.0

License

MIT

Unpacked Size

17.5 kB

Total Files

9

Last publish

Collaborators

  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar