HTML5 Storage Timeout

Posted by brian on 10-16-2016
posts

Storing information in the browser has been made easier with widely accepted implementation of HTML5 Local Storage and Session Storage. The issue is that without proper management storage can become cluttered or invalid. I wanted a basic ‘Storage Service’ that could help me manage storage information and expire items when necessary.

Problem:

I needed to assign a Time To Live (TTL) to my storage objects so they would become invalid and clean themselves up. My specific use can was for OAuth authentication and the information that is stored temporarily that process.

Solution:

An service that sits on top of a browsers storage service that will assign a TTL to storage objects, evaluate and invalidate when necessary.

The service is simple, there are set and get methods for both Local and Session storage along with a remove method. Additionally, there are methods to determine when the TTL should expire and if an item has expired and needs to be removed.

First, lets set the storage object. NOTE: The methods and process for objects for localStorage and sessionStorage will be the same. Session storage has been ignored for brevity.

Set

The set takes three parameters:

  • Key: The reference back to the object
  • Value: The item itself, what you’re trying to store
  • Time: (Optional) A time that the object should be considered valid. Ex: 10, would mean an item was valid for 10 seconds after being set.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
setLocalItem(key, value, time?) {

// If time was not defined, set time to 0. 0 is considered infinite so
// these items will persist

time = time || 0;

// Generate a timestamp for the item
let timestamp = this.setTimeToLive(time);

// Set up the storage item by creating a simple object that will be
// stringified
let storageObj = {
'timestamp': timestamp,
'value': value
};

return localStorage.setItem(key, JSON.stringify(storageObj));
}
```

#### Set Time to Live
```js
setTimeToLive(lifespan) {
let currentTime = new Date().getTime();

let timeToLive;

if (lifespan !== 0) {
timeToLive = currentTime + lifespan;
} else {
timeToLive = 0; // Lifespan is now infinite and dependent only browser
}

return timeToLive;

}

Get

The get method handles parsing the item, handling cleanup if an item expired, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
getLocalItem(key) {

let item = JSON.parse(sessionStorage.getItem(key));

if (item) { // If item exists evaluate, else return
let time = this.evaluateTimeToLive(item.timestamp);
if (time) {
return item.value;
} else {
this.removeSessionItem(key);
return false;
}
} else {

return false;

}
}

Evaluate Time to Live

The evaluateTimeToLive method simply makes a quick determination if the item being evaluated is still within it’s expiration window. The evaluation uses the Javascript Date() method to get the current time. Because the time use to set an item and get an item are all local to the users device, there shouldn’t be any issues around time not aligning and items not expiring or expiring when they shouldn’t.

1
2
3
4
5
6
7
8
9
10
11
evaluateTimeToLive(timestamp) {

let currentTime = new Date().getTime();

if (currentTime <= timestamp || timestamp === 0) {
return true;
} else {
return false;
}

}

Remove

The remove method simply removes the item from storage.

1
2
3
removeLocalItem(key) {
return localStorage.removeItem(key);
}

Because this functionality is setup in a simple service we can use this throughout out application.