Parse HTTP set-cookie headers in JavaScript
Installations
npm install set-cookie-parser
Releases
Unable to fetch releases
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
20.18.0
NPM Version
10.8.2
Statistics
180 Stars
165 Commits
22 Forks
3 Watching
1 Branches
16 Contributors
Updated on 11 Nov 2024
Bundle Size
2.25 kB
Minified
1.08 kB
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
583,966,563
Last day
5.1%
1,247,941
Compared to previous day
Last week
6.8%
6,396,385
Compared to previous week
Last month
16.1%
25,473,547
Compared to previous month
Last year
28.8%
252,352,836
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
set-cookie-parser
ℹ️ Note for current users: I'm considering some changes for the next major version and would appreciate your feedback: https://github.com/nfriedly/set-cookie-parser/discussions/68
Parses set-cookie headers into JavaScript 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:
1{ 2 decodeValues: true, // Calls decodeURIComponent on each value - default: true 3 map: false, // Return an object instead of an array - default: false 4 silent: false, // Suppress the warning that is logged when called on a request instead of a response - default: false 5}
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
- URL path to limit the scope to (string or undefined)domain
- domain to expand the scope to (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 expiration time of the cookie in seconds from when the client receives it (integer or undefined)- Note: when using with express's res.cookie() method, multiply
maxAge
by 1000 to convert to milliseconds.
- Note: when using with express's res.cookie() method, multiply
secure
- indicates cookie should only be sent over HTTPs (true or undefined)httpOnly
- indicates cookie should not be accessible to client-side JavaScript (true or undefined)sameSite
- indicates if cookie should be included in cross-site requests (more info) (string or undefined)- Note: valid values are
"Strict"
,"Lax"
, and"None"
, but set-cookie-parser coppies the value verbatim and does not perform any validation.
- Note: valid values are
partitioned
- indicates cookie should be scoped to the combination of 3rd party domain + top page domain (more info) (true or undefined)
(The output format is loosely based on the input format of https://www.npmjs.com/package/cookie)
Install
1$ npm install --save set-cookie-parser
Usage
Get array of cookie objects
1var http = require('http'); 2var setCookie = require('set-cookie-parser'); 3 4http.get('http://example.com', function(res) { 5 var cookies = setCookie.parse(res, { 6 decodeValues: true // default: true 7 }); 8 9 cookies.forEach(console.log); 10}
Example output:
1[ 2 { 3 name: 'bam', 4 value: 'baz' 5 }, 6 { 7 name: 'foo', 8 value: 'bar', 9 path: '/', 10 expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'), 11 maxAge: 1000, 12 domain: '.example.com', 13 secure: true, 14 httpOnly: true, 15 sameSite: 'lax' 16 } 17]
Get map of cookie objects
1var http = require('http'); 2var setCookie = require('set-cookie-parser'); 3 4http.get('http://example.com', function(res) { 5 var cookies = setCookie.parse(res, { 6 decodeValues: true, // default: true 7 map: true // default: false 8 }); 9 10 var desiredCookie = cookies['session']; 11 console.log(desiredCookie); 12});
Example output:
1{ 2 bam: { 3 name: 'bam', 4 value: 'baz' 5 }, 6 foo: { 7 name: 'foo', 8 value: 'bar', 9 path: '/', 10 expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'), 11 maxAge: 1000, 12 domain: '.example.com', 13 secure: true, 14 httpOnly: true, 15 sameSite: 'lax' 16 } 17}
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:
1const libCookie = require('cookie'); 2const setCookie = require('set-cookie-parser'); 3 4function modifySetCookie(res){ 5 // parse the set-cookie headers with this library 6 let cookies = setCookie.parse(res); 7 8 // modify the cookies here 9 // ... 10 11 // create new set-cookie headers using the cookie library 12 res.headers['set-cookie'] = cookies.map(function(cookie) { 13 return libCookie.serialize(cookie.name, cookie.value, cookie); 14 }); 15}
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.
1var setCookie = require('set-cookie-parser'); 2 3var response = fetch(/*...*/); 4 5// This is mainly for React Native; Node.js does not combine set-cookie headers. 6var combinedCookieHeader = response.headers.get('Set-Cookie'); 7var splitCookieHeaders = setCookie.splitCookiesString(combinedCookieHeader) 8var cookies = setCookie.parse(splitCookieHeaders); 9 10console.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()
.
References
License
MIT © Nathan Friedly
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
2 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
Reason
5 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/nfriedly/set-cookie-parser/node.js.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/nfriedly/set-cookie-parser/node.js.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/nfriedly/set-cookie-parser/node.js.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:36: update your workflow using https://app.stepsecurity.io/secureworkflow/nfriedly/set-cookie-parser/node.js.yml/master?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 2 out of 2 npmCommand dependencies pinned
Reason
Found 2/21 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: jobLevel 'contents' permission set to 'write': .github/workflows/node.js.yml:31
- Warn: no topLevel permission defined: .github/workflows/node.js.yml:1
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 11 are checked with a SAST tool
Score
3.9
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More