salemdar / ngx-cookie

Implementation of Angular 1.x $cookies service to Angular 2
MIT License
318 stars 68 forks source link

Cookie cannot be parsed on server #616

Open Ben555555 opened 1 year ago

Ben555555 commented 1 year ago

I store two cookies in my application in the browser: language.code=en-US authentication=1

Now when I refresh the page and access the cookie in the server side, there are some issues retrieving the cookies by key. When i use cookieService.get('authentication') then 1;language.code=de-CH is returned. When I use cookieService.get('language.code') nothing is returned. This is weird, so I used cookieService.getAll() to get the whole dictionary, which looks like this: { 'authentication': '1;language.code=de-CH' }

So there seems to be something wrong how the cookie on the server side is stored. The first key contains a value which also contains all the other key-value-pairs after the first semicolon.

Do I have to parse the cookie in another way?

Ben555555 commented 1 year ago

I created a temporary workaround for reading the cookies on server side:

private getMap(): Map<string, string> {
    const map = new Map<string, string>();
    const all = this.cookieService.getAll();

    for (let key in all) {
      let value = all[key];
      let i = 0;

      for (let item of value.split(';')) {
        if (i === 0) {
          map.set(key, item);
        }
        else {
          const parts = item.split('=');
          const subKey = parts[0];
          const subValue = parts[1];

          map.set(subKey, subValue);
        }

        i++;
      }
    }

    return map;
  }

This will read the cookie dictionary which seems to contain the first cookie key only. The value of this cookie key contains all other key value pairs as well. It will add all the key value pairs to the map.

I hope there is a fix soon, since this is kind of an ugly workaround.