HTML5 localStorage with expiry with vanilla JavaScript

Using HTML5 localStorage with expiry

HTML5 comes with a lot of handy features which can really improve user experience of your web application significantly if you use them wisely. Caching cold data on the client, such as lookups can significantly save the amount of traffic, page load time and even you backed services load.

One of the HTML5 features that can help you do this are sessionStorage and localStorage. Both of them have pretty much the same role, but what is different is their scope.

sessionStorage lives only while the browser window lives. Once you close the browser window your data is gone.

localStorage on the other hand comes with unlimited expiry. Well almost unlimited. It is on to a browser to decide when to clear the localStorage, but essentially, you do not know when the local storage will be cleared from the browser.

Both are saved on the domain level, meaning browser will only allow your page to access storage data which it saved, so you do not have to worry about the keys since they are saved per domain. This sounds familiar, right? 

Doesn't cookie do the same? Well yes and no. Here are some facts why you should use localStorage or sessionStorage instead of using cookie for temporary storing the data on the client side:

  • Maximum side of data stored in cookie is 4KB and for localStorage and sessionStorage it's 5MB
  • Cookie is sent in every request, although some of the data stored in it is not really necessary to be sent back in each and every request to the server. This is not the case with localStorage or sessionStorage.
  • You can set expiry date for the Cookie, sessionStorage expires when browser is close and localStorage persist until you explicitly remove the values from it.

The last point is something we will focus in this article.

It is obvious that localStorage is superior for storing temporary data on the client, but you want it to expiry at some time. I mean caching is good, but caching until undefined, is kinda not so reliable.

Luckily we can always wrap this in a good old vanilla JavaScript and have our issue solved, so here is a script that I used in couple of the pages which helps me control the expiry of localStorage.

var localStorageEx = {
	get: function (key) {
		var value = localStorage[key];
		if (value != null) {
			var model = JSON.parse(value);
			if (model.payload != null && model.expiry != null) {
				var now = new Date();
				if (now > Date.parse(model.expiry)) {
					localStorage.removeItem(key);
					return null;
				}
			}
			return JSON.parse(value).payload;
		}
		return null;
	},
	set: function (key, value, expirySeconds) {
		var expiryDate = new Date();
		expiryDate.setSeconds(expiryDate.getSeconds() + expirySeconds);
		localStorage[key] = JSON.stringify({
			payload: value,
			expiry: expiryDate
		});
	}
};
    
Note

both localStorage and sessionStorage can store string values, so the script heavily relies on JSON.stringify and JSON.parse functions in order to store expiry along with the data

Unlike native localStorage get and set, this wrapper function does not require you to serialize using JSON.stringify. It is doing this for you, so both get and set methods return and take object for retrieving and storing.

If you already have key set in the localStorage, the function will just return it and will not handle it's expiry, so if you want to use this piece of script on already running page, you should not have any issues.

Enough of the talks and let's spin this code in a browser to see how it works. I created a simple script on the page which will initially set the simple string value and set it to expire in 5 seconds. Next we have a loot that will check the value every 1 second for the next 10 seconds.

localStorageEx.set("key1", "Some text data", 5);
for (i = 1; i < 11; i++) {
	setTimeout(function () {
		console.log(localStorageEx.get("key1"));
	}, 1000 * i);
}
    

Now you can just put this in your page HTML and check out the output of the console.

Console Out

You can see that 4 times we are retrieving value and for the other 6 times we are getting null value. This is because our get function of localStorageEx object is checking the expiry of the object stored in a localStorage and takes care of removing the value from localStorage.

I hope you find this piece of vanilla JavaScript useful, happy coding. 

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

.NET

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article