LocalStorage Expiry Mechanism

Home / LocalStorage Expiry Mechanism

LocalStorage Expiry Mechanism

October 28, 2019 | Coding | No Comments

programming code

HTML5 LocalStorage is a great tool, but it never expires. To contrast, SessionStorage expires when the browser tab is closed. But what if you want a longer expiry while preserving data if the browser is closed?

Here are two simple functions to add and check a expiry value to your storage object.

// get from LocalStorage (if the value expired it is destroyed)
/**
 * @return {null}
 */
function LocalStorageGet(key) {
  let stringValue = window.LocalStorage.getItem(key);
    if (stringValue !== null) {
      let value = JSON.parse(stringValue);
        let expirationDate = new Date(value.expirationDate);
        if (expirationDate > new Date()) {
          return value.value
        } else {
          window.LocalStorage.removeItem(key);
        }
    }
    return null;
}

// add into LocalStorage
function LocalStorageSet(key, value, expirationInMin = 10) {
  let expirationDate = new Date(new Date().getTime() + (60000 * expirationInMin));
    let newValue = {
    value: value,
    expirationDate: expirationDate.toISOString()
  };
  window.LocalStorage.setItem(key, JSON.stringify(newValue))
}

About Author

about author

Wayne

Jack of all trades. I.T. edition. Programmer, Systems Administrator, DevOps and whatever else comes up.