pillarjs / cookies

Signed and unsigned cookies based on Keygrip
MIT License
1.29k stars 152 forks source link
cookies javascript nodejs

Cookies

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Cookies is a node.js module for getting and setting HTTP(S) cookies. Cookies can be signed to prevent tampering, using Keygrip. It can be used with the built-in node.js HTTP library, or as Connect/Express middleware.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install cookies

Features

API

new Cookies(request, response [, options])

Create a new cookie jar for a given request and response pair. The request argument is a Node.js HTTP incoming request object and the response argument is a Node.js HTTP server response object.

A Keygrip object or an array of keys can optionally be passed as options.keys to enable cryptographic signing based on SHA1 HMAC, using rotated credentials.

A Boolean can optionally be passed as options.secure to explicitally specify if the connection is secure, rather than this module examining request.

Note that since this only saves parameters without any other processing, it is very lightweight. Cookies are only parsed on demand when they are accessed.

Cookies.express(keys)

This adds cookie support as a Connect middleware layer for use in Express apps, allowing inbound cookies to be read using req.cookies.get and outbound cookies to be set using res.cookies.set.

cookies.get(name [, options])

This extracts the cookie with the given name from the Cookie header in the request. If such a cookie exists, its value is returned. Otherwise, nothing is returned.

{ signed: true } can optionally be passed as the second parameter options. In this case, a signature cookie (a cookie of same name ending with the .sig suffix appended) is fetched. If no such cookie exists, nothing is returned.

If the signature cookie does exist, the provided Keygrip object is used to check whether the hash of cookie-name=cookie-value matches that of any registered key:

cookies.set(name [, values [, options]])

This sets the given cookie in the response and returns the current context to allow chaining.

If the value is omitted, an outbound header with an expired date is used to delete the cookie.

If the options object is provided, it will be used to generate the outbound cookie header as follows:

Secure cookies

To send a secure cookie, you set a cookie with the secure: true option.

HTTPS is necessary for secure cookies. When cookies.set is called with secure: true and a secure connection is not detected, the cookie will not be set and an error will be thrown.

This module will test each request to see if it's secure by checking:

If your server is running behind a proxy and you are using secure: true, you need to configure your server to read the request headers added by your proxy to determine whether the request is using a secure connection.

For more information about working behind proxies, consult the framework you are using:

If your Koa or Express server is properly configured, the protocol property of the request will be set to match the protocol reported by the proxy in the X-Forwarded-Proto header.

Example

var http = require('http')
var Cookies = require('cookies')

// Optionally define keys to sign cookie values
// to prevent client tampering
var keys = ['keyboard cat']

var server = http.createServer(function (req, res) {
  // Create a cookies object
  var cookies = new Cookies(req, res, { keys: keys })

  // Get a cookie
  var lastVisit = cookies.get('LastVisit', { signed: true })

  // Set the cookie to a value
  cookies.set('LastVisit', new Date().toISOString(), { signed: true })

  if (!lastVisit) {
    res.setHeader('Content-Type', 'text/plain')
    res.end('Welcome, first time visitor!')
  } else {
    res.setHeader('Content-Type', 'text/plain')
    res.end('Welcome back! Nothing much changed since your last visit at ' + lastVisit + '.')
  }
})

server.listen(3000, function () {
  console.log('Visit us at http://127.0.0.1:3000/ !')
})

License

MIT