Search code examples
angularjssessioncachingsession-storage

Caching session data only between page loads in Angular SPA


I'm working on an Angular SPA and I'm now attempting to implement some level of client-side caching for session data. This is data that is used across routes/controllers so I don't want to be hitting the server/database repeatedly unnecessarily to retrieve it.

I initially have implemented caching using sessionStorage, but have noticed that when I log out then log back in, the previous session data is still there. When thinking about how I'd clear the cached session data appropriately, it seems like the safest way to handle it is to only retain the session data in my SPA between page loads/refreshes. Even if I were to clear the cache on log out, a user could potentially navigate directly to the login page and log in, subverting the logout process, resulting in different session data existing.

Assuming this is a reasonable approach, is there a way to configure sessionStorage or another caching mechanism to only retain the cache between page loads/refreshes? If there is not a built-in configuration, I could store a unique identifier (guid) as a hidden field and use that in my sessionStorage key.

Thanks in advance.


Solution

  • The simple way is to use $rootScope but will always reset when the page refreshes, since it's a single-page app.

    You need to use something that persists client-side, such as a cookie or sessionStorage (as they both have an expiration time). For the cookies see $cookieStore: https://docs.angularjs.org/api/ngCookies/service/$cookieStore