localStorage

1. Set expiry time(TTL) for LocalStorage

1
2
3
4
5
6
7
8
9
10
11
function setWithExpiry(key, value, ttl){
const new = new Date()

const item = {
value : value
expiry : new.getTime() + ttl
}

localstorage.setItem(key, JSON.stringify(item))
}

2. Get items from LocalStorage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getWithExpiry(key){
const itemStr = localstorage.getItem(key)

if(!itemStr){
return null
}

const item = JSON.parse(itemStr)
const now = new Date()
if( now.getTime() > item.expiry ){
localStorage.removeItem(key)
}
return item.value
}