• Stars
    star
    154
  • Rank 242,095 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Parse HTTP set-cookie headers in JavaScript

set-cookie-parser

Node.js CI NPM version npm downloads

Parses set-cookie headers into objects

Accepts a single set-cookie header value, an array of set-cookie header values, a Node.js response object, or a fetch() Response object that may have 0 or more set-cookie headers.

Also accepts an optional options object. Defaults:

{
    decodeValues: true,  // Calls decodeURIComponent on each value - default: true
    map: false,          // Return an object instead of an array - default: false
    silent: false,       // Suppress the warning that is logged when called on a request instead of a response - default: false
}

Returns either an array of cookie objects or a map of name => cookie object with {map: true}. Each cookie object will have, at a minimum name and value properties, and may have additional properties depending on the set-cookie header:

  • name - cookie name (string)
  • value - cookie value (string)
  • path - cookie path (string or undefined)
  • domain - domain for the cookie (string or undefined, may begin with "." to indicate the named domain or any subdomain of it)
  • expires - absolute expiration date for the cookie (Date object or undefined)
  • maxAge - relative max age of the cookie in seconds from when the client receives it (integer or undefined)
  • secure - indicates that this cookie should only be sent over HTTPs (true or undefined)
  • httpOnly - indicates that this cookie should not be accessible to client-side JavaScript (true or undefined)
  • sameSite - indicates a cookie ought not to be sent along with cross-site requests (string or undefined)

(The output format is loosely based on the input format of https://www.npmjs.com/package/cookie)

Install

$ npm install --save set-cookie-parser

Usage

Get array of cookie objects

var http = require('http');
var setCookie = require('set-cookie-parser');

http.get('http://example.com', function(res) {
  var cookies = setCookie.parse(res, {
    decodeValues: true  // default: true
  });

  cookies.forEach(console.log);
}

Example output:

[
    {
        name: 'bam',
        value: 'baz'
    },
    {
        name: 'foo',
        value: 'bar',
        path: '/',
        expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'),
        maxAge: 1000,
        domain: '.example.com',
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    }
]

Get map of cookie objects

var http = require('http');
var setCookie = require('set-cookie-parser');

http.get('http://example.com', function(res) {
  var cookies = setCookie.parse(res, {
    decodeValues: true,  // default: true
    map: true            // default: false
  });

  var desiredCookie = cookies['session'];
  console.log(desiredCookie);
});

Example output:

{
    bam: {
        name: 'bam',
        value: 'baz'
    },
    foo: {
        name: 'foo',
        value: 'bar',
        path: '/',
        expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'),
        maxAge: 1000,
        domain: '.example.com',
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    }
}

Creating a new, modified set-cookie header

This library can be used in conjunction with the cookie library to modify and replace set-cookie headers:

const libCookie = require('cookie');
const setCookie = require('set-cookie-parser');

function modifySetCookie(res){
  // parse the set-cookie headers with this library
  let cookies = setCookie.parse(res);
  
  // modify the cookies here
  // ...
  
  // create new set-cookie headers using the cookie library
  res.headers['set-cookie'] = cookies.map(function(cookie) {
      return libCookie.serialize(cookie.name, cookie.value, cookie);
  });
}

See a real-world example of this in unblocker

Usage in React Native (and with some other fetch implementations)

React Native follows the Fetch spec more closely and combines all of the Set-Cookie header values into a single string. The splitCookiesString method reverses this.

var setCookie = require('set-cookie-parser');

var response = fetch(/*...*/);

// This is mainly for React Native; Node.js does not combine set-cookie headers.
var combinedCookieHeader = response.headers.get('Set-Cookie');
var splitCookieHeaders = setCookie.splitCookiesString(combinedCookieHeader)
var cookies = setCookie.parse(splitCookieHeaders);

console.log(cookies); // should be an array of cookies

This behavior may become a default part of parse in the next major release, but requires the extra step for now.

Note that the fetch() spec now includes a getSetCookie() method that provides un-combined Set-Cookie headers. This library will automatically use that method if it is present.

API

parse(input, [options])

Parses cookies from a string, array of strings, or a http response object. Always returns an array, regardless of input format. (Unless the map option is set, in which case it always returns an object.)

parseString(individualSetCookieHeader, [options])

Parses a single set-cookie header value string. Options default is {decodeValues: true}. Used under-the-hood by parse(). Returns an object.

splitCookiesString(combinedSetCookieHeader)

It's uncommon, but the HTTP spec does allow for multiple of the same header to have their values combined (comma-separated) into a single header. This method splits apart a combined header without choking on commas that appear within a cookie's value (or expiration date). Returns an array of strings that may be passed to parse().

V2 Changes

  • Added decodeValues option (calls decodeURIComponent() on each cookie value), enabled by default.
  • Added splitCookiesString method.

References

License

MIT Β© Nathan Friedly

More Repositories

1

node-unblocker

Web proxy for evading internet censorship, and general-purpose Node.js library for proxying and rewriting remote webpages
JavaScript
391
star
2

nodeunblocker.com

Evade internet censorship!
HTML
150
star
3

Javascript-Flash-Cookies

Cross-domain flash cookie library for javascript. ~ 4kb total when JS is minified and gzipped.
JavaScript
107
star
4

node-bestzip

Provides a `bestzip` command that uses the system `zip` if avaliable, and a Node.js implimentation otherwise.
JavaScript
80
star
5

spam-free-php-contact-form

Simple, human-friendly contact form (no captchas). Uses JavaScript and hidden fields to thwart spammers.
HTML
70
star
6

Coin-Allocator

Bitcoin/Altcoin/USD trading bot. Was moderately profitable, until the exchange got hacked. No longer under active development.
JavaScript
49
star
7

DuckDuckGo-GoogleSuggest

Node JS server that proxies google suggest queries for the Duck Duck Go search box, and adds the !'s back on when google removes them.
HTML
40
star
8

facebook-js-sdk

Facebook's debug.js (what gets minified into sdk.js), updated every 10 minutes
JavaScript
39
star
9

approximate-number

Converts numbers into a more human-friendly format. E.g. 123456 becomes 123k. Similar to `ls -lh` or Stack Overflow's reputation numbers.
JavaScript
37
star
10

get-user-media-promise

Basic wrapper for navigator.mediaDevices.getUserMedia with automatic fallback to navigator.getUserMedia
JavaScript
22
star
11

node-pagerank

Node.js library for looking up the Google PageRank of a given site. No longer functional.
JavaScript
17
star
12

miyoo-toolchain

Dockerfile to build an image with the toolchain and other dependencies to compile software the Miyoo Custom Firmware (CFW)
Dockerfile
12
star
13

nodemcu-weather-station

Displays current weather conditions inside and out
Lua
12
star
14

nfriedly.com

My personal website. Contact info, portfolio, links, etc.
JavaScript
12
star
15

couchdb-backup-restore

Node.js library for simple backup and restore of CouchDB databases
JavaScript
12
star
16

node-gatling

A simple node.js script that turns a single-threaded server into a multi-threaded server with automatic restarting.
JavaScript
8
star
17

contentful-dictate

A UI Extension for Contentful that uses IBM Watson Speech to Text to enable voice dictation.
JavaScript
7
star
18

node-dreamhost-dns-updater

A quick script I build to set a given hostname to my current IP via Dreamhost's API
JavaScript
5
star
19

dog-food

Gadget that answers the question of "Did anyone feed the dog yet?"
Python
4
star
20

node-whats-my-ip

Simple text-based service to find your public IP. Can be run for free on heroku (and likely other similar services)
HTML
4
star
21

docpad-plugin-cloudant

Cloudant importer for DocPad (Cloudant is a hosted couchdb service)
CoffeeScript
3
star
22

docpad-plugin-mongodb

MongoDB importer for DocPad
CoffeeScript
3
star
23

gps.bb.tracking

Blackberry GPS tracker similar to google's android one.
Java
3
star
24

prefix-stream

Prepend each chunk in a node.js text stream with the given prefix
JavaScript
3
star
25

aplexa

Web App that shows what song the Plex skill for Alexa is currently playing
JavaScript
2
star
26

Meteor-ODB-II

A quick ODB-II (vehicle diagnostic code) search website built with Meteor
JavaScript
2
star
27

running-average

Memory-efficient module that tracks the average value of an unlimited quantity of numbers
JavaScript
2
star
28

vzw-bot

Bot that automatically logs into My Verizon, reports data usage, and can spend "smart rewards" points on avaliable sweepstakes.
JavaScript
2
star
29

space-jump

A cross between Lunar Lander and Doodle Jump
JavaScript
2
star
30

dreamhost

DreamHost API client for Node.js and Browsers
JavaScript
2
star
31

hn-avatars

UserScript to generate avatars next to usernames on Hacker News
JavaScript
2
star
32

docpad-plugin-redirector

DocPad plugin for redirecting URLs to other websites via configuration.
CoffeeScript
2
star
33

Stripe-CTF-2014-level2

Dynamic ingress filter to fight off a DDOS while allowing legitimate traffic through
JavaScript
1
star
34

eleventy-plugin-less

Plugin for eleventy (11ty) to convert Less stylesheets to CSS
JavaScript
1
star
35

wdc-deep-dive

Code from my Technical Deep Dive presentation on the IBM Watson Developer Cloud Node.js SDK
JavaScript
1
star
36

MacAdSense

An updated version of Kai 'Oswald' Seidler's MacAdSense dashboard widget
1
star
37

sweetspot

"Sweeps Bot" - Bot to help you remember & enter sweepstakes
JavaScript
1
star
38

aoc-2022-02

Advent of Code 2022 - Day 2
Rust
1
star
39

rss-xslt

A tool I built in college to add a custom XSLT theme to an arbitrary RSS feed. Moving it here for safe keeping.
PHP
1
star
40

ua.nfriedly.com

Static User Agent parser, previously at whatsmyua.com
HTML
1
star
41

contributor-locations

List the locations of all contributors to a GitHub repo.
JavaScript
1
star
42

aoc-2022-1

Advent of Code 2022 - Day 1
Rust
1
star
43

oled-saver-watchface

Watchface for Wear OS that randomly moves the time around to avoid burn-in on OLED displays
Java
1
star
44

JS-Mini-Shell

A Super-lightweight interactive JavaScript shell that fits into a bookmarklet
CSS
1
star
45

picsync-server

Accepts uploaded photos and stores them privately, allowing you to later review them and post your favorites to Facebook. Written for node.js
CSS
1
star
46

BiblePeople

RoR based website with details on people and family lines in the Bible
Ruby
1
star
47

grunt-swf

Compiles .as files to .swf via the Apache Flex SDK (free but must be installed seperately)
JavaScript
1
star
48

Arduino-Fan-Controler

Controls a whole-house fan for energy-efficient home automation
Arduino
1
star
49

puck.js-media-control

Remote control to pause, resume, and rewind audiobooks playing from my phone
JavaScript
1
star
50

aoc-2022

Advent of Code 2022
Rust
1
star
51

web-shell

Interactive command prompt for locked down app servers (such as Bluemix). Highly insecure.
JavaScript
1
star
52

value-averaging

A website to help make the value averaging investment strategy easier.
JavaScript
1
star
53

socket.io-example

Just a quick demo I put together
JavaScript
1
star
54

aoc-2022-03

Advent of Code 2022 - Day 3
Rust
1
star
55

ypool-xpm-miner-watcher

A node.js script to watch ypool.net's PrimeCoin jhPrimeminer and restart it every time it crashes
JavaScript
1
star