$window.sessionStorage vs $cookieStore

oberger picture oberger · Jun 5, 2014 · Viewed 17.1k times · Source

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).

Answer

David Boike picture David Boike · Jun 6, 2014

$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.