• 0

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/post.php

Line Number: 190


File: /home2/naijacod/public_html/application/views/post.php
Line: 190
Function: _error_handler

File: /home2/naijacod/public_html/application/controllers/Posts.php
Line: 420
Function: view

File: /home2/naijacod/public_html/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

How to set expiry time for local storage items with javascript

This post will explain how to implement expiry times for items stored in the browsers localStorage.

If you’re familiar with the browsers locaStorage object, you know that there’s no provision for providing an expiry time. However, we can use Javascript to add a TTL (Time to live) to invalidate items in locaStorage after a certain period of time elapses.

  1. Store the expected time of expiry along with the original information to be stored
  2. When getting the item, compare the current time with the stored expiry time
  3. If the current time is greater than to stored expiry time, return null and remove the item from storage, otherwise, return the original information.

Let’s see how we can implement this using Javascript.

Storing Items with Expiry Time

Let’s create a function that allows you to set a key in local storage, and store the expiry time along with it:

function setWithExpiry(key, value, ttl) {
  const now = new Date()
  // `item` is an object which contains the original value
  // as well as the time when it's supposed to expire
 const item = {
  value: value,
  expiry: now.getTime() + ttl
 localStorage.setItem(key, JSON.stringify(item))

Here, we create a new object with the original value as well as the expiry time, which is calculated by adding the TTL value in milliseconds to the current millisecond time.

set item diagram

We convert the item to a JSON string, since we can only store strings in localStorage.

Getting Items from Storage

We can verify the expiry time while retrieving items from the store:

function getWithExpiry(key) {
 const itemStr = localStorage.getItem(key)
 // if the item doesn't exist, return null
 if (!itemStr) {
  return null
 const item = JSON.parse(itemStr)
 const now = new Date()
 // compare the expiry time of the item with the current time
 if (now.getTime() > item.expiry) {
  // If the item is expired, delete the item from storage
  // and return null
  return null
 return item.value

Here we are expiring the item “lazily” - which is to say we check the expiry condition only when we want to retrieve it from storage. If the item has, in-fact expired, we remove the key from localStorage.

get item diagram

If you have any questions, add them below.