How to set expiration date for cookie in AngularJS

This is possible in the 1.4.0 build of angular using the ngCookies module:

https://docs.angularjs.org/api/ngCookies/service/$cookies

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Find tomorrow's date.
  var expireDate = new Date();
  expireDate.setDate(expireDate.getDate() + 1);
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal', {'expires': expireDate});
}]);

For 1.4: As noted in the comment here and others below, as of 1.4, Angular's native cookie support now provides the ability to edit cookies:

Due to 38fbe3ee, $cookies will no longer expose properties that represent the current browser cookie values. $cookies no longer polls the browser for changes to the cookies and no longer copies cookie values onto the $cookies object.

This was changed because the polling is expensive and caused issues with the $cookies properties not synchronizing correctly with the actual browser cookie values (The reason the polling was originally added was to allow communication between different tabs, but there are better ways to do this today, for example localStorage.)

The new API on $cookies is as follows:

get put getObject putObject getAll remove You must explictly use the methods above in order to access cookie data. This also means that you can no longer watch the properties on $cookies to detect changes that occur on the browsers cookies.

This feature is generally only needed if a 3rd party library was programmatically changing the cookies at runtime. If you rely on this then you must either write code that can react to the 3rd party library making the changes to cookies or implement your own polling mechanism.

The actual implementation is done via a $cookiesProvider object, which can be passed via the put call.

For 1.3 and below: For those of you who have done your best to avoid having to load jQuery plugins, this appears to be a nice replacement for angular - https://github.com/ivpusic/angular-cookie


In Angular v1.4 you can finally set some options for the cookies, such as the expiration. Here's a very simple example:

var now = new Date(),
    // this will set the expiration to 12 months
    exp = new Date(now.getFullYear()+1, now.getMonth(), now.getDate());

$cookies.put('someToken','blabla',{
  expires: exp
});

var cookie = $cookies.get('someToken');
console.log(cookie); // logs 'blabla'

If you check your cookies after running this code you will see that the expiration will be properly set to the cookie named someToken.

The object passed as a third param to the put function above allows for other options as well, such as setting path, domain and secure. Check the docs for an overview.

PS - As a side note if you are upgrading mind that $cookieStore has been deprecated, so $cookies is now the only method to deal with cookies. see docs