What is the difference between using $cookieStore and &window.sessionStorage? Are there times when one should be used over the other? Security Issues?

Here is what I know so far:

The AngularJS docs state that the $cookieStore service is backed by "session cookies" (https://docs.angularjs.org/api/ngCookies/service/$cookieStore). So, it appears that information stored with $cookieStore is tied to the window/tab where it is used. This is affirmed by the use of the mysterious $browser service in the code for $cookieStore: https://github.com/angular/angular.js/blob/master/src/ngCookies/cookies.js#L125.

However, since $browser is an internal service and subject to change, I can't see how it is storing the data, to see if it is similar to sessionStorage.

The same browser/tab/window scope seems to apply to $window.sessionStorage (Scope of sessionStorage and localStorage).


$cookieStore using session cookies means that data is persisted as cookies that are scoped to the session, i.e. not persistent. A cookie is scoped to the particular domain it is registered on, but may be shared between subdomains. The big deal about the cookie store is that those cookie values will be sent to the server for any requests to that domain. It would be shared between windows and tabs in the same session on the same domain.

$window.sessionStorage just accesses the window.sessionStorage, which really has nothing to do with Angular. Accessing it through $window just gives you the ability to test more easily using a mocked version of $window. Session storage is scoped to the current window, so unlike cookies, if you open a new tab to the exact same URL it will be a new sessionStorage object. There is also more room for storage than cookies. A cookie is limited to 4K, sessionStorage can differ per browser but is usually around 5MB.

There's also window.localStorage (or $window.localStorage) which is basically the same as sessionStorage, except it is scoped by domain (two tabs can share the same data - there's even a storage event so you can find out when another tab changes it) and persists when you close your browser.

  • 1
    Thanks, clarified now. I was looking for how to store/send a simple token with every request, looks like cookieStore will take care of that without having to do a manual pull from sessionStorage each time. – oberger Jun 6 '14 at 17:16
  • Can you please look into this Question @David Boike stackoverflow.com/questions/29251702/… – forgottofly Mar 25 '15 at 9:36
  • I want to store the value(token) so that it will be persisted even if I open in different tab of same(preferable) or different browser – forgottofly Mar 25 '15 at 9:38
  • Other linked question appears to have valid answer. – David Boike Mar 26 '15 at 16:09

Your Answer

