nfriedly / set-cookie-parser Goto Github PK
View Code? Open in Web Editor NEWParse HTTP set-cookie headers in JavaScript
License: MIT License
Parse HTTP set-cookie headers in JavaScript
License: MIT License
max-age property shoud be returned in ms, not in seconds.
Express framework use for set cookie options maxAge in ms.
I was wondering if you'd be open to a PR to convert to ESM and what your thoughts are about ESM vs CJS, etc.
I made PR: joeferraro/react-native-cookies#97
which parses multiple comma separated cookies in one string.
Discussion here as well:
#13
Probably this functionality should go here instead?
This method returns array of cookie strings which this library can parse.
This might not be a related question, but I tried very very long time but I cannot find a way to get Set-Cookie. Plus, there is an answer said Set-Cookie is forbidden to get from client
https://stackoverflow.com/questions/54214657/not-able-to-read-set-cookie-response-header
But I saw this library, is there any way I can get Set-Cookie header? Thanks.
Hi @nfriedly
Thank you for the utility. I have a specific need for the utility. My node app sits between 2 apps and the app rewrites the set cookie on the response object by intercepting it. The parse function gives me the whole array so i have to rebuild the whole cookie object. The specific utility function parseString
will make my life easy. Could you please export the function
The cookie parser does not recognize response returned by the Fetch API. That makes it nearly impossible to use the library in browser/Node.js/React Native environments.
The library assumes response to be a plain object with the set-cookie
property. However, the Fetch Response has a different interface:
response.headers.get('Set-Cookie')
response.headers.getAll('Set-Cookie')
Reproduction code
import { parse as parseCookies } from "set-cookie-parser";
const mycookieString =
"oam.Flash.RENDERMAP.TOKEN=-11nju699kw; Path=/app; HttpOnly, JSESSIONID=00008-Moez7CnaOd4Ekb0kU14Rq:1cov06vt5; Path=/app; Secure; HttpOnly";
const myCookies = parseCookies(mycookieString, { map: true });
console.log(myCookies);
// Current console log
// {
// "oam.Flash.RENDERMAP.TOKEN": {
// "name": "oam.Flash.RENDERMAP.TOKEN",
// "value": "-11nju699kw",
// "path": "/app",
// "httponly, jsessionid": "00008-Moez7CnaOd4Ekb0kU14Rq:1cov06vt5",
// "secure": true,
// "httpOnly": true
// }
// }
// Expected Console log
// Current console log
// {
// "oam.Flash.RENDERMAP.TOKEN": {
// "name": "oam.Flash.RENDERMAP.TOKEN",
// "value": "-11nju699kw",
// "path": "/app",
// "secure": true,
// "httpOnly": true
// },
// "JSESSIONID": {
// "name": "JSESSIONID",
// "value": "00008-Moez7CnaOd4Ekb0kU14Rq:1cov06vt5",
// "path": "/app",
// "secure": true,
// "httpOnly": true
// }
// }
I was testing the code out to see if I could use this module because the popular cookie-parser package lacks good documentation. However, when I ran the snippet in the documentation all I got was an empty object. I know cookies exists because I set them using nodejs.
Environment:
NodeJS v13.11.0
Express v4.17.1
The following is the code I ran.
const http = require("http");
const CookieParser = require("set-cookie-parser");
http.createServer((req, res) =>
{
var cookies = CookieParser.parse(res,
{
decodeValues: true,
map: true
});
console.log(cookies);
}).listen(8080, "localhost");
When analyzing the request and response object, I found that the cookie it only exists in the request object under the request.headers.cookie. However, it does not display the other attributes, such as, path, domain, secure, httpOnly, sameSite, signed.
I have found that set-cookie-parser doesn't abide by RFC 6265 for some set-cookie strings.
parseString("testcookie;SameSite=None;Secure");
>>> { name: 'testcookie', value: '', sameSite: 'None', secure: true }
Looking at above, the name is parsed as "testcookie" and the value is empty.
However, according to RFC 6265, this should actually be ignored (page 17):
A user agent MUST use an algorithm equivalent to the following algorithm to parse a "set-cookie-string":
....
1. If the set-cookie-string contains a %x3B (";") character:
The name-value-pair string consists of the characters up to,
but not including, the first %x3B (";"), and the unparsed-
attributes consist of the remainder of the set-cookie-string
(including the %x3B (";") in question).
....
2. If the name-value-pair string lacks a %x3D ("=") character, ignore the set-cookie-string entirely.
....
So, I think in this case, that the cookie should be ignored, as it's invalid.
Otherwise I have a second proposal:
If we want to mimic what the browsers (I tested in Chrome and Firefox - latest versions) actually do, they parse the above string as an empty name and use testcookie
as the value.
However, that will again not abide by the RFC 6265 spec:
5. If the name string is empty, ignore the set-cookie-string
entirely.
This is how the set-cookie string works in Chrome 103.0.5060.114:
Thanks for the explanation on what RN is doing! I noticed it was different but I couldn't figure out why in my research. Super helpful thank you!
Hello!
As I can see the latest version of the package on npm is 2.2.1
. I installed it using npm i set-cookie-parser@latest
. But in github project releases the latest version is 2.3.0
.
Also, 2.2.1
version does not support map
option.
Snippet:
const setCookie = require('set-cookie-parser');
const cookiesMap = setCookie.parse('foo=bar; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 3000 10:01:11 GMT; HttpOnly; Secure', { map: true });
console.log(cookiesMap);
Result:
[ { name: 'foo',
value: 'bar',
maxAge: 1000,
domain: '.example.com',
path: '/',
expires: 3000-07-01T10:01:11.000Z,
httpOnly: true,
secure: true } ]
Is there also included a mechanism to convert the object with cookies into Cookie:
HTTP header?
Suppose I parsed the set-cookie
– How do I stringify it back after modifying it?
Although its a very useful module but it lacks a basic feature to get a specific cookie by name. Whenever i have to get cookie , i will be doing a search on cookies array returned by this module. Can you add one utility function for the same task or i can submit a pull request regarding the same if you also feel that this feature should be added. Let me know. Thanks
Now that whatwg/fetch#1346 is landed, the fetch()
spec has a new response.headers.getSetCookie()
method for getting individual (non-combined) set-cookie headers.
We should detect the presence of getSetCookie()
and call it when available.
Additionally the documentation should be cleaned up to clarify that splitCookiesString()
is only necessary when working with older implementations.
When you use fetch()
and the endpoint sets multiple Set-Cookie
headers they all get serialized under the same key in the Headers
object. It would be nice if this library supported passing multiple cookies in a single string for that use case.
So for example if a request returns
Set-Cookie: foo=foo; Expires=Tue, 30 Jan 2024 14:04:53 GMT; SameSite=Lax
Set-Cookie: bar=bar; HttpOnly
Calling res.headers.get('set-cookie')
just returns both of those cookies as one string, separated by a comma:
{
"Set-Cookie": "foo=foo; Expires=Tue, 30 Dec 2023 14:04:53 GMT; SameSite=Lax, Set-Cookie: bar=bar; HttpOnly"
}
I know there is a new getSetCookie
function in the headers API but it does not have the greatest support as of yet.
Maybe you could consume all the known cookie parameters until you reach and unknown one (the name of the next cookie) and then recursively continue parsing? I could have a go at a PR if you are open to that
Travis CI and David DM isn't working for this project, just wanted to inform you.
Since version 2.2.0 there's a const declaration that break older Safari browsers.
const cookiesStrings = [];
Safari throws SyntaxError: Unexpected keyword 'const'. Const declarations are not supported in strict mode.
exception.
returns Invalid Date for Expires=Thu, 26-Mar-2020 07:55:35 GMT as an example
Noticed that the github link in package.json is incorrect. It should be
Hi @nfriedly, thanks for this useful library!
I was looking to use parseString
method and I noticed that the map
option doesn't really change the result. In both cases, the result is in the same form, unlike the Readme example. Here is the result:
{
name: 'authorization',
value: 'somecrazyvalue'
}
Any idea what might be going on?
Input string:
refreshToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NWEwZWM1MmYzOTE4YTlhMTE2MjBmMDUiLCJpYXQiOjE3MDUwNDUwNzUsImV4cCI6MTcxMDIyOTA3NX0.YbyImGmGSRI6Lz5aXXA0keaMaFJiQFz1qo_IILRZxqY; Path=/; Expires=Tue, 12 Mar 2024 07:37:55 GMT; HttpOnly, accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NThhZTFiNWMzYzFhYWZmODJlZjk5ZjAiLCJpYXQiOjE3MDUwNDUwNzUsImV4cCI6MTcwNTA0NTY3NX0.uQqUEN6LxDDHHqcYp24qh8rFn-1LDVH88wGVw3Gzu48; Path=/; Expires=Fri, 12 Jan 2024 07:47:55 GMT; HttpOnly
Output:
{
name: 'refreshToken',
value: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NWEwZWM1MmYzOTE4YTlhMTE2MjBmMDUiLCJpYXQiOjE3MDUwNDUwNzUsImV4cCI6MTcxMDIyOTA3NX0.YbyImGmGSRI6Lz5aXXA0keaMaFJiQFz1qo_IILRZxqY',
path: '/',
expires: 2024-01-12T07:47:55.000Z,
httponly, accesstoken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NThhZTFiNWMzYzFhYWZmODJlZjk5ZjAiLCJpYXQiOjE3MDUwNDUwNzUsImV4cCI6MTcwNTA0NTY3NX0.uQqUEN6LxDDHHqcYp24qh8rFn-1LDVH88wGVw3Gzu48',
httpOnly: true
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.