Tag Archive for: cookies

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.

AngularJS and Cookies

AngularJS has built in support for cookies. A cookie may be added by simply injecting $cookies into your service or controller and creating a cookie by:

$cookies.MyToken = value;

The value can then also be read from the cookies easily by:

var myToken = $cookies.MyToken;

This obviously is a nice feature which abstracts away much of the javascript usually written for creating and reading cookies.

The problem with the current way angular cookies are created is that all cookies by default are set to expire at the end of the browsing session and as of this post there isn’t a way to change that. The problem has been recognized and the creators of angular are working on allowing expiration to be set on cookies in a future update. For the time being we have stopped using $cookies and are using some simple javascript to create cookies but then use angular to read and delete cookies.

Here is some javascript on how to create a new cookie with an expiration of 30 days:

var expirationDate = new Date();
var myValue;

expirationDate.setDate(expirationDate.getDate() + 30);
document.cookie = "MyToken" + "=" + myValue + "; expires=" + expirationDate.toUTCString();

In order to delete an angular cookie simply use:

delete $cookies["MyToken"];