Reputation: 891
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, '/');
}
}
Upvotes: 7
Views: 4198
Reputation: 119
I had the same problem, I realized that the "extra" cookie that is added brings the same data that the 1st, except the path is different, the path that I defined in my default cookie was "/" to cover my routes, but Later when the 2nd cookie was added I realized that my path should be that of this 2nd cookie, since although my initial path is "/" (mydomain.com /) because I am in a login, but as soon as I access my session my path will change to mydomain.com /admin /home
At that time my original cookie comes in with "/", but if I navigate to a section of my site for example mydomain.com/admin/users
and I press F5, the new cookie is added with the path in "/admin", because indeed I am in another path, I am not in "/".
So I left my cookie with the path in "/admin", to make sure that if I reload the page that will be my path even if the sections change, this solved my problem.
Pd:
This is my actual cookie, only I use a 1 cookie for the moment in my site:
TokenContants.ts
export const COOKIE_KEY = 'current_user';
export const COOKIE_PATH = '/admin';
Auth.service.ts
this.cookieService.set(COOKIE_KEY, JSON.stringify(user), { path: COOKIE_PATH, sameSite: "Strict" });
Additional info:
In this case, if you want the cookie to be accessible in all sections of your site, including different paths, you should set the path of the cookie to "/" when creating it, as long as your path that you will navigate to is more sections of your site is that "/", but if when you change the section your path changes and you press F5 and it creates a new cookie then you will have to change the path to the path of the cookie that has just been added.
I hope to help you, happy coding.
Upvotes: 1
Reputation: 365
import { CookieService } from 'ngx-cookie-service';
...
let Future = toInteger(Date.now()) + 5 * 60000;
this.cookies.set('session', data, {
expires: Future,
path: '/',
sameSite: 'Strict'
});
Upvotes: 4