Set an Expiration Date and Time for a localStorage Item
Last updated: January 20, 2023.
Unlike cookies, localStorage has no native option for setting an expiration time to an item.
But you can mimic this behavior with localStorage by adding a expiration timestamp when storing an item:
const obj = { value: "value", expires: new Date().setDate(new Date().getDate() + 30).toString() };
// Saves timestamp for 30 days in the future
localStorage.setItem('test-expiration', JSON.stringify(obj));
// Stores obj as string in localStorage
Then, you check the timestamp you have saved when a user visits your site.
If the value of the expiration timestamp is greater than the timestamp for now, the set expiration time has passed and the item should be deleted:
const res = new Date().getTime().toString() > JSON.parse(localStorage.getItem('test-expiration')).expires;
// Returns true if timestamp for now is greater than expiration (item has 'expired')
if (res) {
localStorage.removeItem('test-expiration');
// item is removed if the value of res is true
}
If you want an item in storage to only persist for a current session, use the sessionStorage method.
It works in exactly the same way as localStorage except all items are automatically cleared once a user closes the current tab:
sessionStorage.setItem('test', 'value');
// Stores test item in sessionStorage space
Run this code and then close the current tab.
When you return the item will not longer exist:
sessionStorage.getItem('test' === null);
// true