skip to Main Content

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.

2

Answers


  1. you can retrieve the cookie by name and domain like so

    import Cookie from 'js-cookie';
    
    function getCookieByDomain(name, domain) {
      const cookies = Cookie.get();
      const matchingCookies = Object.entries(cookies).filter(([cookieName]) => cookieName === name);
    
      // Search for a cookie with the specified domain
      const cookieWithDomain = matchingCookies.find(([cookieName, cookieValue]) => {
        const cookieOptions = Cookie.getJSON(cookieName, { raw: true });
        return cookieOptions.domain === domain;
      });
    
      if (cookieWithDomain) {
        const [cookieName, cookieValue] = cookieWithDomain;
        return { [cookieName]: cookieValue };
      }
    
      return null; // Cookie not found with the specified domain
    }
    
    // Usage:
    const cookieForDomain = getCookieByDomain('myCookie', '.domain.com');
    console.log(cookieForDomain); // Outputs: { myCookie: 'myValue1' } if it exists, otherwise null
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search