Node Cookie
Easily parse and write signed & encrypted cookies on Node.js HTTP requests.

node-cookie
makes it simpler to create encrypted and signed cookies for HTTP requests.
You can use it with any framework or library of your choice.
See also
Basic Setup
const http = require('http')
const nodeCookie = require('node-cookie')
http.createServer(function (req, res) {
nodeCookie.create(res, 'user', 'virk')
}).listen(3000)
Signing cookies with a secret
const http = require('http')
const nodeCookie = require('node-cookie')
http.createServer(function (req, res) {
nodeCookie.create(res, 'user', 'virk', '16charlongsecret')
}).listen(3000)
Signing & encrypting cookies with a secret
const http = require('http')
const nodeCookie = require('node-cookie')
http.createServer(function (req, res) {
nodeCookie.create(res, 'user', 'virk', '16charlongsecret', true)
}).listen(3000)
Methods
parse
Parses cookies from HTTP header Cookie
into
a javascript object. Also it will unsign
and decrypt cookies encrypted and signed
by this library using a secret.
Params
req | Object | Yes | |
secret | String | No | |
decrypt | Boolean | No | |
Returns
Object
Example
nodeCookie.parse(req)
nodeCookie.parse(req, 'SECRET')
nodeCookie.parse(req, 'SECRET', true)
get
Returns value for a single cookie by its key. It is
recommended to make use of this function when you
want to pull a single cookie. Since the parse
method will eagerly unsign and decrypt all the
cookies.
Params
req | Object | Yes | |
key | String | Yes | |
secret | String | No | |
decrypt | Boolean | No | |
cookies | Object | No | Use existing cookies object over re-parsing them from the header. |
Returns
Mixed
Example
nodeCookie.get(req, 'sessionId')
nodeCookie.get(req, 'sessionId', 'SECRET')
nodeCookie.get(req, 'sessionId', 'SECRET', true)
create
Write cookie to the HTTP response object. It will append
duplicate cookies to the Set-Cookie
header, since
browsers discard the duplicate cookies by themselves
Params
res | Object | Yes | |
key | String | Yes | |
value | * | Yes | |
options | Object | No | |
secret | String | No | |
encrypt | Boolean | No | |
Returns
Void
Example
nodeCookie.create(res, 'sessionId', 1)
nodeCookie.create(res, 'sessionId', 1, {}, 'SECRET')
nodeCookie.create(res, 'sessionId', 1, {}, 'SECRET', true)
clear
Clears the cookie from browser by setting it's expiry
in past. This is required since there is no other
way to instruct the browser to delete a cookie.
Also this method will override the expires
value on
the options object.
Params
res | Object | Yes | |
key | String | Yes | |
options | Object | No | |
Returns
Void
Example
nodeCookie.clear(res, 'sessionId')