All the modern browsers have multiple types of storage mechanisms for using in your web applications. You may have already heard of cookies which are small bits of information you can store and they will be automatically expired. However, cookies can only store small amounts of information. The other kind of storage is sessionStorage, where you can store big chunks of information. However all the data stored in this will be lost as soon as you close the browser tab.
This is supported in almost all browsers. As per the website https://caniuse.com, this is supported in more than 98% of the browsers. Here is the browser support chart for this feature.
The solution is to wrap localStorage API with a utility. Your application’s logic for accessing should encapsulated in a single class. Using localStorage revolves around storing item with a key and fetching the item previously stored.
The utility we are going to create can provide utility methods to save and load from localStorage. The save method will store the item along with the timestamp, where are load method should first check if the item has already expired before returning it. Here is the that does just that.
const EXPIRY_IN_HOURS = 6;
In this snippet, we have one auxiliary method to help with detection of expiration. The method hasExpired will calculate the difference in hours. It uses the current timestamp and the and timestamp stored along with data to calculate the age. If the age of the item is more than the expire hours we set, we return true from this method. The load method invokes the hasExpired method to check if the item is expired and return null after deleting the item from localStorage.
Keep note of the issues that can arise out of this, if the user happens to travel between timezones the expiry may not work appropriately, the solution is to use UTC timestamps all the time.
Also, we only remove the items when user tries to access them so, if we store an item and never read it again, we may leave that item forever in localStorage. We can solve that as well but it is for a different post.
There can be other frameworks that may solve this problem elegantly, but what is more interesting than solving problems ourselves.