Search code examples
javascriptregexcookies

Split a Set-Cookie header with multiple cookies


I'm working with Serverless framework (Javascript) and it requires me to split a single Set-Cookie into an array of cookies for it to be correctly set on the client. Why? No idea, but this seems to be what is going on.

I do not have access to the code that generates the Set-Cookies string, so I have to manually split it into an array.

My string looks like this:

cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT;

You can probably guess my issue, if I do string.split(', ') my string is split in three:

  1. cookie1=value
  2. cookie2=value2; Expires=Thu
  3. 06 Jul 2023 14:45:25 GMT;

I've Googled but I cannot find an already existing answer anywhere. I know I can probably resolve this with Regex, but it's far too complex for me to figure it out.


Solution

  • After trying some suggestions I happened to discover the getSetCookie() method on mdn.

    For some reason this isn't typed on the Headers class but it does work.

    So if your response returns a header Object you can pass it to the header class and then use the built-in method.

    const headers = new Headers(res.headers);
    const setCookies = headers.getSetCookie()
    console.log(setCookies)
    // ["cookie1=value", "cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT;"
    

    Depending on what you're doing your response might already return headers as an instance of Headers, so keep an eye on that.