Skip to content

Instantly share code, notes, and snippets.

@vwochnik vwochnik/storage.js

Created Aug 25, 2016
What would you like to do?
Local Storage getter/setter with expiration
* Retrieves or stores a value inside local storage.
* If only the first parameter is specified, the value is retrieved from local storage.
* If a value to store is specified, maxAge must also be specified after which the value is
* considered invalid and removed during successive retrievals.
* @param name key name to set or retrieve
* @param value value to store
* @param maxAge number of hours until expiration
function storage(name, value, maxAge) {
if (value !== void 0) {
var expires = new Date( + maxAge * 3600000);
window.localStorage.setItem(name, JSON.stringify({
value: JSON.stringify(value),
expires: expires.toUTCString()
return value;
try {
var obj = JSON.parse(window.localStorage.getItem(name));
if (new Date(obj.expires) < new Date()) {
return JSON.parse(obj.value);
} catch (e) { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.