Local Storage with Expiration

LuVu picture LuVu · Dec 5, 2018 · Viewed 10.2k times · Source

How can I set an expiration time on a specific local storage variable?

Example: If I have a page disclaimer and once the user clicks "accept" I store a certain variable in the local storage. However after 12 hours, I want it to get deleted and ask the user to accept again.

I don't want to store the variable in session storage, because the disclaimer will prompt every time the user opens a new tab.

Cookies would be another solution, but I rather not use it if possible.

Thanks!

Answer

Aaron Beall picture Aaron Beall · Dec 11, 2018

There's no built-in way to expire values in storage. One solution is to store a timestamp, then in each visit compare the stored time (if there is one) against the local time to determine if the value has expired. Example:

const expirationDuration = 1000 * 60 * 60 * 12; // 12 hours

const prevAccepted = localStorage.getItem("accepted");
const currentTime = new Date().getTime();

const notAccepted = prevAccepted == undefined;
const prevAcceptedExpired = prevAccepted != undefined && currentTime - prevAccepted > expirationDuration;
if (notAccepted || prevAcceptedExpired) {
  alert("Disclaimer: ...");
  localStorage.setItem("accepted", currentTime);
}