I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out in setting expiration to the localStorage item? Here's the line of code that is setting the localStorage:
localStorage.setItem('ispremium', '1');
And my website is on Blogger platform, if that matters!
Normally this would be solved on the server side. The localStorage may be cleared if a user selects "clear browsing history" on some browsers. It may not be available across sessions if the user works with multiple browsers or incognito mode. Other than that someone with a bit of technical knowledge can insert the "ispremium" flag easily into his localStorage to gain access to your premium feature.
If you still want to solve this via client, you could store a timestamp instead of a boolean flag and check if the current time is still in the validity range. LocalStorage itself doesn't let you set an expiration date on entries.
You can set the actual value as the first time user joined and the time to expire. And whenever the user opens again the website, you need to check that expiration date. But this is extremely unsecure, you shouldn't do that for sessions. Just to answer to your question, you can do the following:
const NAMESPACE = 'MY_ID';
const TIMESTAMP_MODEL = {
initial: null,
expiresOn: null
};
const TIMESTAMP = Date.now();
if (!JSON.parse(localStorage.getItem(NAMSPACE))) {
// when the user access your website for the first time, set the initial and expiresOn values:
localStorage.setItem(NAMESPACE, JSON.stringify({
initial: TIMESTAMP,
expiresOn: TIMESTAMP + 1000*60*60*24*30 // 1month in ms
}));
} else {
// then, when user access the website again, check the expiresOn, it it's value is bigger than current date
const EXPIRE_DATE = JSON.parse(localStorage.getItem(NAMESPACE)).expiresOn;
if (Date.now() > EXPIRE_DATE) {
console.log('session expired');
}
}