Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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

AsciiSmoke commented Dec 1, 2015

I like it.

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

Copy link

justin-cook commented Dec 14, 2015

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

claushellsing commented May 22, 2016

yep , i just find it :)

Copy link

kverawat commented Jun 10, 2016

Awesome, I found it too. Thank

Copy link

SpacemanPete commented Jun 21, 2016

Just found this gist too. Great share, thanks!

Copy link

awitherow commented Jan 14, 2017

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

mindfulmike commented Nov 7, 2017


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

prakarangs commented Aug 24, 2018

7 years and still very helpful. Thank you!

Copy link

adc91 commented Sep 3, 2018

Good contributions endure over time. Thank you.

Copy link

dysonspherelab commented Oct 24, 2018

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