Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
How set expiration date to an localStoarge item in Javascript?

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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');
  } 
}  
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!