AngularJS and Cookies (Continued)
As my esteemed colleague Robbie Pell has pointed out in a recent post, AngularJS provides an easy mechanism for setting and retrieving cookies but this mechanism comes with several notable limitations. Robbie’s post outlines the fact that AngularJS provides no way to set an expiration date on a cookie which causes the cookie to expire when the browser session ends.
I have uncovered an additional limitation. It appears that AngularJS also does not provide a way to specify which subdirectories of a domain the cookie applies to. This causes the cookie to, by default, only be applied to the subdirectory in which it is set. For example, if I set a cookie from a page at http://dev1.derby.reurgency.net/derby/racetracker/index.html using AngularJS the cookie will not be visible at http://dev1.derby.reurgency.net/derby/api/ causing all API calls which require that specific cookie to fail.
The solution to this is to, once again, set the cookies manually outside of AngularJS. I have built on Robbie’s example below:
var expirationDate = new Date();
var myValue;
var path = "/";
expirationDate.setDate(expirationDate.getDate() + 30);
document.cookie = "MyToken" + "=" + myValue + "; path=" + path + "; expires=" + expirationDate.toUTCString();
In the example above, the cookie will be applied to all subdirectories within the current domain. Alternatively, you can specify a subdirectory to apply the cookie to by altering the “path” variable.