Skip to content

Instantly share code, notes, and snippets.

Created July 20, 2011 23:07
Show Gist options
  • Save anhang/1096149 to your computer and use it in GitHub Desktop.
Save anhang/1096149 to your computer and use it in GitHub Desktop.
HTML5 Local Storage with Expiration = {
save : function(key, jsonData, expirationMin){
if (!Modernizr.localstorage){return false;}
var expirationMS = expirationMin * 60 * 1000;
var record = {value: JSON.stringify(jsonData), timestamp: new Date().getTime() + expirationMS}
localStorage.setItem(key, JSON.stringify(record));
return jsonData;
load : function(key){
if (!Modernizr.localstorage){return false;}
var record = JSON.parse(localStorage.getItem(key));
if (!record){return false;}
return (new Date().getTime() < record.timestamp && JSON.parse(record.value));
Copy link

boiawang commented Jul 6, 2015

if(!localStorage.getItem(key)) {
  return false;

Copy link

I like it.

I switched the Modernizr check for just:
if (typeof (Storage) == "undefined") { return false; }

Copy link

Put together a fiddle showing this in action:

Copy link

benmort commented Jan 6, 2016

cheers for this

Copy link

anhang commented May 3, 2016

Ha, after 5 years, people are finding this gist!

Copy link

yep , i just find it :)

Copy link

Awesome, I found it too. Thank

Copy link

Just found this gist too. Great share, thanks!

Copy link

Thanks for this @anhang!

Copy link

JimmyCrawford commented Mar 30, 2017

I can't believe that this is 6 years old and despite looking for how long local storage is valid for this is the (seemingly) only function that allows you to add an expiry date. Good Stuff @anhang!

Copy link

ashmohd commented Aug 11, 2017


Copy link


Copy link

tomek-f commented Nov 23, 2017


Copy link

karladler commented May 16, 2018

This would just not load the storage, while it is still available in the browser for other scripts.
Maybe a safer solution could be to encrypt the local storage and store the key in an cookie with expiry date?

Copy link

7 years and still very helpful. Thank you!

Copy link

adc91 commented Sep 3, 2018

Good contributions endure over time. Thank you.

Copy link

Copy link

voku commented Nov 27, 2018

This code has one problem (as I see!?), it didn't delete the expired cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment