Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML5 Local Storage with Expiration
AZHU.storage = {
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));
}
}
@boiawang
Copy link

boiawang commented Jul 6, 2015

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

@AsciiSmoke
Copy link

AsciiSmoke commented Dec 1, 2015

I like it.

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

@justin-cook
Copy link

justin-cook commented Dec 14, 2015

Put together a fiddle showing this in action: http://jsfiddle.net/7nzdzvj8/1/

@benmort
Copy link

benmort commented Jan 6, 2016

cheers for this

@anhang
Copy link
Author

anhang commented May 3, 2016

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

@claushellsing
Copy link

claushellsing commented May 22, 2016

yep , i just find it :)

@kverawat
Copy link

kverawat commented Jun 10, 2016

Awesome, I found it too. Thank

@SpacemanPete
Copy link

SpacemanPete commented Jun 21, 2016

Just found this gist too. Great share, thanks!

@awitherow
Copy link

awitherow commented Jan 14, 2017

Thanks for this @anhang!

@JimmyCrawford
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!

@ashmohd
Copy link

ashmohd commented Aug 11, 2017

Thanks

@mindfulmike
Copy link

mindfulmike commented Nov 7, 2017

👍

@tomek-f
Copy link

tomek-f commented Nov 23, 2017

👍

@karladler
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?

@prakarangs
Copy link

prakarangs commented Aug 24, 2018

7 years and still very helpful. Thank you!

@adc91
Copy link

adc91 commented Sep 3, 2018

Good contributions endure over time. Thank you.

@dysonspherelab
Copy link

dysonspherelab commented Oct 24, 2018

@voku
Copy link

voku commented Nov 27, 2018

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

https://github.com/liesislukas/localstorage-ttl/blob/master/index.js

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