Making session storage play nicely with server side sessions

Session and local storage have made the storage of data on a clients machine respectable, gone are the big cookies and, partnered with the ability to define manifest files developers can now exert control over how resources and data are cached to a level that makes Apache and IIS look embarrassing.

However, with every new feature, some things get easier and some things get harder.

Session storage is held only in a particular tab or window, allocated to the domain and lasting as long as that window persists. Opening the same domain in another tab will create a new session. Local storage is also allocated to a domain but persists between sessions, tabs and windows.

Web storage does not cater for different users, domains and windows are all it knows.

There are additional complications if users on your site are able to login, if your web storage includes data individual to the user you need to take care to clear and refresh data whenever the state changes

How to maintain state between web storage and server sessions

It might be a bit old-school, but Cookies are still the way that most back-end systems track user sessions. The simplest thing to do is to store the value of the session cookie in your web storage and to compare those values when the page loads and if the values differ clear the session of user specific data.

sLocalKey = 'StoredIdentity', 
sCookieKey = 'CookieKey', 
storedIdent = window.localStorage.getItem(sLocalKey); 
sCookieValue = readCookie(CookieKey); 

if (sCookieValue === storedIdent) { 
return true; //same cookie value 
else { 
return sCookieValue; //different value, new session 

Another case to watch for is a login/logout events, it’s unlikely the cookie value will change (the session existed before login) but either you can watch for a query-string value or particular pages like login/logout success.

Filed under: JavaScript