Reputation: 17
I am running into a silly issue but can't seem to find a solution.
Once a user has been logged in on my web app, I create a cookie with a JWT token so I can send it to my backend on every requests to validate the token/cookie.
if (idToken) {
document.cookie = "token=" + idToken;
window.location.assign('/dashboard');
}
This is working great for all pages that do not page sub routes, example: ("/dashboard", "/help", "/etc").
The problem:
Now I have a sub route which is: www.domain.com/abc/xyz
When the request goes to that route /abc/xyz, I see two cookies being created in the browser, one on / (root path) and another one on /abc path. This is causing my trouble because my backend retrieves the requests.cookie for the current path which is /abc and eventually I get an invalid cookie.
How can I handle this properly? I tried to set a "global" cookie with root path but it did not seem to work for me:
document.cookie = "token=" + idToken + ";path=/";
Upvotes: 0
Views: 3034
Reputation: 2580
According to MDN, specifying a path of path=/
will indeed match all subdirectories. Your proposed solution should therefore work, and it's likely that you just need to clean your cookies for a to make sure the previous cookie does not interfere.
According to the standard:
Cookies with longer paths are listed before cookies with shorter paths.
If your old cookie on /abc
does still exist, it will take precedence over your new correct one.
Depending on where your idToken
comes from, it might be a good idea to escape it before setting a cookie. If your token for some reason includes a ;
, then this won't break your website.
document.cookie = "token=" + encodeURIComponent(idToken) + ";path=/";
Upvotes: 1