I am using javascript k6 load testing tool to make a http.post request to our application server.
The server sends me a response back and it also sends the response headers.
One of the response headers is the below Set-Cookie header sent back to me: Set-Cookie : xx00000000xxxxxxxxxx0000000000xx-jwt=<jwt_token>; path=/; expires=Fri, 23 Apr 2021 04:15:19 GMT; domain=.somedomain.com; samesite=none; secure
For making subsequent requests through my k6 testing tool to my server - i would like to parse the Set-Cookie value above and fetch the jwt value only of <jwt_token> and store in a variable like => fetched_jwt=<jwt_token>
How can i fetch the value for jwt from the Set-Cookie headers that has multiple values sent back to me by the server?
According to MDN, Set-Cookie syntax is like this
Set-Cookie: <cookie-name>=<cookie-value>
// and also can be followed by other attribute
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
// but no matter what attributes behind it, cookie name and value will be on first
So, if you want parse it, just get the first attribute. You can do it with String.prototype.split()
, and then get the first.
const myCookie = unparsedCookie.split(';')[0];
And use String.prototype.split()
again to get its name and value.
const [name, value] = myCookie.split('=');
const unparsedCookie = 'xx00000000xxxxxxxxxx0000000000xx-jwt=<jwt_token>; path=/; expires=Fri, 23 Apr 2021 04:15:19 GMT; domain=.somedomain.com; samesite=none; secure';
const myCookie = unparsedCookie.split(';')[0];
const [name, value] = myCookie.split('=');
console.log(name);
console.log(value);
But keep in mind that Set-cookie might be encoded as URI Component.
A
<cookie-value>
can optionally be wrapped in double quotes and include any US-ASCII characters excluding control characters, Whitespace, double quotes, comma, semicolon, and backslash. Encoding: Many implementations perform URL encoding on cookie values, however it is not required per the RFC specification. It does help satisfying the requirements about which characters are allowed for though.
So, you might be needed to decode it with decodeURIComponent()
.
But, since your case is JWT token, you don't have to worry about that. JWT should be generated as base64url which friendly to url.