This post will explain how to implement expiry times for items stored in the browsers localStorage.
If you’re familiar with the browsers localStorage 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 localStorage after a certain period of time elapses.
If you just want to see a working example, you can skip to the last section
Here’s an overview of how we can achieve this:
- Store the expected time of expiry along with the original information to be stored
- When getting the item, compare the current time with the stored expiry time
- 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 localStorage, 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.
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
localStorage.removeItem(key)
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.
Full Example
Let’s create a small HTML page which demonstrates how we can use localStorage with expiry:
- The “Set” button store the value in the input box to localStorage with a 5 second expiry
- The “Get” button fetches the value from localStorage and displays it below
- We make use of the
setWithExpiry
andgetWithExpiry
functions defined in the script
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>LocalStorage Expiry Example</title>
</head>
<body>
<button id="btn-set">Set</button>
<input id="input-set" />
<br /><br />
<button id="btn-get">Get</button>
<div>Value: <span id="value"></span></div>
<script>
const btnSet = document.getElementById("btn-set")
const btnGet = document.getElementById("btn-get")
const inputSet = document.getElementById("input-set")
const valueDisplay = document.getElementById("value")
btnSet.addEventListener("click", () => {
setWithExpiry("myKey", inputSet.value, 5000)
})
btnGet.addEventListener("click", () => {
const value = getWithExpiry("myKey")
valueDisplay.innerHTML = value
})
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))
}
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
localStorage.removeItem(key)
return null
}
return item.value
}
</script>
</body>
</html>