Giter Club home page Giter Club logo

node-cookie's Introduction

Node Cookie

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

NPM Version Build Status Appveyor Coveralls

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

  1. node-req
  2. node-res

Basic Setup

const http = require('http')
const nodeCookie = require('node-cookie')

http.createServer(function (req, res) {

  // this will update set-cookie header on res object.
  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)

API

Cookie

Cookie parser is a simple utility module to read and write cookies on Node.js HTTP requests. It supports cookie signing and encryption.

parse(req, [secret], [decrypt]) ⇒ Object

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.

Kind: inner method of Cookie

Param Type Default
req http.IncomingRequest
[secret] String
[decrypt] Boolean false

Example

nodeCookie.parse(req)

// or if cookies were signed when writing
nodeCookie.parse(req, 'SECRET')

// also if cookies were encrypted
nodeCookie.parse(req, 'SECRET', true)

get(req, key, [secret], [decrypt], [cookies]) ⇒ Mixed

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.

Kind: inner method of Cookie

Param Type Default Description
req http.IncomingRequest
key String
[secret] String
[decrypt] Boolean false
[cookies] Object Use existing cookies object over re-parsing them from the header.

Example

nodeCookie.get(req, 'sessionId')

// if cookie was signed
nodeCookie.get(req, 'sessionId', 'SECRET')

// if cookie was encrypted
nodeCookie.get(req, 'sessionId', 'SECRET', true)

unPackValue(value, secret, decrypt) ⇒ String

Unpack cookie value by unsigning and decrypting it. Infact you can unpack any value packed via the packValue method.

Kind: inner method of Cookie

Param Type
value String
secret String
decrypt Boolean

packValue(value, [secret], [encrypt]) ⇒ String

Pack the value by properly formatting, signing and encrypting it.

Kind: inner method of Cookie

Param Type Default
value String
[secret] String
[encrypt] Boolean false

create(res, key, value, [options], [secret], [encrypt]) ⇒ void

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

Kind: inner method of Cookie

Param Type Default
res http.ServerResponse
key String
value *
[options] Object {}
[secret] String
[encrypt] Boolean false

Example

nodeCookie.create(res, 'sessionId', 1)

// sign session id
nodeCookie.create(res, 'sessionId', 1, {}, 'SECRET')

// sign and encrypt session id
nodeCookie.create(res, 'sessionId', 1, {}, 'SECRET', true)

clear(res, key, [options]) ⇒ void

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.

Kind: inner method of Cookie

Param Type Default
res http.ServerResponse
key String
[options] Object {}

Example

nodeCookie.clear(res, 'sessionId')

node-cookie's People

Contributors

leangseu avatar luukhoeben avatar richie3366 avatar thetutlage avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

node-cookie's Issues

Bug in Cookie._append

I found a weird bug affecting new visitors having no cookie at their first request (my project uses adonuxt ssr).

ERROR  cookies.map is not a function
  at Object.Cookie._append (/var/www/shared/node_modules/node-cookie/src/Cookie/index.js:164:39)
  at Object.Cookie.create (/var/www/shared/node_modules/node-cookie/src/Cookie/index.js:389:10)
  at Response.cookie (/var/www/shared/node_modules/@adonisjs/framework/src/Response/index.js:503:16)

And indeed, when you look at that line of code, you see that the cookies variable is not affected by the else-case of the ternary condition:

node-cookie/index.js

Lines 162 to 166 in 07f12f6

Cookie._append = function (res, cookie) {
const cookies = res.getHeader('Set-Cookie') || []
Array.isArray(cookies) ? cookies.push(cookie) : [cookies].push(cookie)
res.setHeader('Set-Cookie', cookies.map(String))
}

So, my quick workaround was to change it like so:

  Array.isArray(cookies) ? cookies.push(cookie) : (cookies = [cookies]).push(cookie)

And it solved it. (I also changed the cookies declaration to let instead of const)

I don't know if you are comfortable with parenthesis assignment allowing to use directly the assigned value.

If so, I can make a PR to merge my fix into the lib. ;)

Trying to denodeify fails

Looks like this method fails. Here's a sample the code:

const denodeify = require('es6-denodeify')(Promise)
const fetch = require('node-fetch');
const tough = require('tough-cookie');
const cookiejar = new tough.CookieJar();

const setCookie = denodeify(cookiejar.setCookie.bind(cookiejar));
const getCookies = denodeify(cookiejar.getCookies.bind(cookiejar));

(async function () {
    const response = await fetch('https://google.com');
    const cookieString = await response.headers.get('set-cookie');
    console.log(cookieString);
    await setCookie(cookieString);
    await getCookies();
})();

Any idea for a fix? Error:
TypeError: Cannot read property 'loose' of undefined
Can be run here:
https://repl.it

Adonis framework installation error

Hi @thetutlage
Thank you for adonis. :) I have an installation error on windows machine.
It's linked with this row in package file:
"keygrip": "git://github.com/crypto-utils/keygrip.git"
Could you change it to standard description with version?

npm log:

npm install node-cookie
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "node-cookie"
npm ERR! node v7.3.0
npm ERR! npm v3.10.10
npm ERR! path C:\npm-cache_git-remotes\git-github-com-crypto-utils-keygrip-git-7cf0e7e1\HEAD
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall scandir

npm ERR! enoent ENOENT: no such file or directory, scandir 'C:\npm-cache_git-remotes\git-github-com-crypto-utils-keygrip-git-7cf0e7e1\HEAD'
npm ERR! enoent ENOENT: no such file or directory, scandir 'C:\npm-cache_git-remotes\git-github-com-crypto-utils-keygrip-git-7cf0e7e1\HEAD'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR! C:\OpenServerLight\domains\localhost\adonis_basic_server\npm-debug.log

you cookie lib cant overwrite same cookie key

I have used adonis for my app, I found that i cant overwrite same cookie key. For example,
old

# old request cookie
SESSION:111;DEVICE_INFO:111

response,

# response set cookie
set-cookie: SESSION:111;DEVICE_INFO:111
set-cookie: SESSION:222

then, in the browser, cookie is

SESSION:111;DEVICE_INFO:111;SESSION:222

Use keygrip version 1.0.1 rather then repository release

This module uses the keygrip master repository which has major API changes compared to the npm release this causes other modules to break since they use the npm release that uses the release API.

I know that this module makes use of the new API functions which aren't available in the npm releases but it also causes conflicts with other modules causing them to break.

Is there any chance for this module to use the keygrip npm releases rather then the master repository?

Cannot read unencrypted cookies

Hello!

I've been trying to read a cookie set by user in browser. I found that adonis will read only self encrypted cookies. My cookie isn't that valuable, just a flag to tell the server what to render.

Given the adonis header like this :

cookie: 'BSID=4b3502957762fc598fd87865101bbc04a0258991; BUW.SERVER.logDetail={%22isVendor%22:true%2C%22id%22:803105%2C%22isPublished%22:false};' }

why can't i read BSID or BUW.SERVER.logDetail using nodeCookie.parse(req) ? (it gives me an empty object)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.