javascriptcookiesjs-cookie

how to get a cookie for with the same name for both `.domain.com` and `domain.com` js-cookie


I'm using the js-cookie library library and I can't figure out how to get the a cookie with a domain value of .domain.com if a cookie with same name exists for domain.com. I've looked at the source and the get function seems to create an object indexed by the name so it will be overridden if two cookies with the same name but different domains exist.

an example:


import Cookie from 'js-cookie'

// one of these two cookies will be unavailable via Cookie.get
Cookie.set('myCookie', 'myValue1', {domain: '.domain.com'})
Cookie.set('myCookie', 'myValue2', {domain: 'domain.com'})

I thought maybe the withAttributes function could help but I think that changes attributes when creating a cookie. I'm not totally sure though the docs are sparse there and i can't figure out the code.


Solution

  • You can't have multiple different cookies with the same name being in effect at the same time. The docs say

    Note: It is not possible to read a particular cookie by passing one of the cookie attributes (which may or may not have been used when writing the cookie in question):

    Cookies.get('foo', { domain: 'sub.example.com' }) // `domain` won't have any effect
    

    The cookie with the name foo will only be available on .get() if it's visible from where the code is called; the domain and/or path attribute will not have an effect when reading.

    This is not a limitation of the library, it's the browser that makes only one cookie visible.