angularcookiessetcookieangular-cookiesngx-cookie-service

Angular 9 - ngx-cookie-service troubles with path


I'm using ngx-cookie-service package to store some data relevant to my application. I need to save this cookie on the base path '/', so each time I know exactly how to retrieve it. This cookie of mine needs to be updated and when such happens, the new cookie must be stored in the same path (so in '/'). The problem is that sometimes when I refresh the page, a new cookie is saved in a new path, so when I try to retrieve it with this.cookieService.get(cookieName, '/') it obviously fails. This happens though I explicitly state to use '/' as path. It doesn't occur always and this cause the debugging even harder.

This is the service where I use cookies

const urlParamsCookieName = 'errepiuapp-url-params';

/**
 * This service keeps track of the keys used to retrieve objects from the backend.
 */
@Injectable({
  providedIn: 'root'
})
export class KeyLookupService {

  private _lookupUrlSegments = ['students', 'macro', 'lto', 'sto', 'reports'];
  private _paramsMap$: BehaviorSubject<Map<string, any>>;

  private get paramsMap() {
    return this._paramsMap$.getValue()
  }

  constructor(
    private cookieService: CookieService,
    private router: Router 
  ) {
    if (!this.router.url.includes('auth') && !this.cookieService.check(urlParamsCookieName)) {
      this.router.navigate(['/auth']);
    }
    this._paramsMap$ = new BehaviorSubject<Map<string, any>>(
      new Map<string, any>(
        this.cookieService.check(urlParamsCookieName) ? 
          this.getParamsFromCookie().map((value, i) => [this._lookupUrlSegments[i], value]) : 
          this._lookupUrlSegments.map(segment => [segment, null])
      )
    );
    this._paramsMap$.subscribe(_ => {
      this.updateCookie();    //*********** PROBLEM HERE ***********
    });
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(event => {
        this.updateCookie();    //*********** PROBLEM HERE ***********
      })
    ).subscribe();
    this.updateCookie();    //*********** PROBLEM HERE ***********
  }

  addParam(key: string, value: any) {
    this._paramsMap$.next(this.paramsMap.set(key, value));
  }

  public getParams(...lookupKeyword: string[]): Map<string, any> {
    if (lookupKeyword) {
      return new Map<string, any>([...this.paramsMap.keys()]
        .filter(key => lookupKeyword.includes(key))
        .map(key => [key, this.paramsMap.get(key)]));
    }
    return this.paramsMap;
  }

  private getParamsFromCookie(): any[] {
    return Array.from(this.cookieService.get(urlParamsCookieName).split(','));
  }

  private updateCookie() {
    if (this.cookieService.check(urlParamsCookieName)) {
      this.cookieService.delete(urlParamsCookieName, '/');
    }
    this.setCookie();
  }

  private setCookie() {
    this.cookieService.set(urlParamsCookieName, [...this.paramsMap.values()].toLocaleString(), undefined, '/');
  }

}

Solution

  • import { CookieService } from 'ngx-cookie-service';
    ...
    let Future = toInteger(Date.now()) + 5 * 60000;
    this.cookies.set('session', data, { 
       expires: Future, 
       path: '/', 
       sameSite: 'Strict' 
    });