When Do Items in Html5 Local Storage Expire

When do items in HTML5 local storage expire?

It's not possible to specify expiration. It's completely up to the user.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Of course, it's possible that something your application stores on the client may not be there later. The user can explicitly get rid of local storage, or the browser may run into space considerations. It's good to program defensively. Generally however things remain "forever" based on some practical definition of that word.

edit — obviously, your own application can actively remove stuff if it decides it's too old. That is, you can explicitly include some sort of timestamp in what you've got saved, and then use that later to decide whether or not information should be flushed.

Local Storage with Expiration

There's no built-in way to expire values in storage. One solution is to store a timestamp, then in each visit compare the stored time (if there is one) against the local time to determine if the value has expired. Example:

const expirationDuration = 1000 * 60 * 60 * 12; // 12 hours

const prevAccepted = localStorage.getItem("accepted");
const currentTime = new Date().getTime();

const notAccepted = prevAccepted == undefined;
const prevAcceptedExpired = prevAccepted != undefined && currentTime - prevAccepted > expirationDuration;
if (notAccepted || prevAcceptedExpired) {
alert("Disclaimer: ...");
localStorage.setItem("accepted", currentTime);
}

Expiration of sessionStorage

It lives and dies with your browser session and is not shared between tabs. It doesn't expire automatically. So if you never close your browser it never expires.

So when the tab/window is closed the data is lost.

Each sessionstorage area is allowed 5MB of storage (in some browsers 10MB). Whereas cookies only allow 4kb (or more in some browsers). Cookies however have a set expiration date.

As Christophe wrote in the comments, localstorage never expires. It's also shared across tabs and is the same size as sessionstorage (5MB).

When do items in HTML5 local storage expire?

It's not possible to specify expiration. It's completely up to the user.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Of course, it's possible that something your application stores on the client may not be there later. The user can explicitly get rid of local storage, or the browser may run into space considerations. It's good to program defensively. Generally however things remain "forever" based on some practical definition of that word.

edit — obviously, your own application can actively remove stuff if it decides it's too old. That is, you can explicitly include some sort of timestamp in what you've got saved, and then use that later to decide whether or not information should be flushed.

Set the time for html local storage

localStorage does not have any expiry time. But you can implement your own logic while reading/writing to localStorage.

For example, along with the actual data you can store the expiry time as well and while reading check if the time is past the expiry time then consider the value unavailable.

Example code (from here) -

function setLocalStorageItemWithExpiry(key, value, expiryTimeInMs) {
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() + expiryTimeInMs,
}
localStorage.setItem(key, JSON.stringify(item))
}

function getLocalStorageItemWithExpiry(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
}

Usage -

const value = getLocalStorageItemWithExpiry('myKey');
if (!value) {
// Your logic
setLocalStorageItemWithExpiry('myKey', 'testvalue', 60000); // 60000 ms = 1 min
}

When is localStorage cleared?

W3C draft says this

User agents should expire data from the local storage areas only for security reasons or when requested to do so by the user. User agents should always avoid deleting data while a script that could access that data is running.

So if browsers follow the spec it should persist untill the user removes it on all browsers, I have not found any that have deleted on any off my projects.

A good article to read is also http://ejohn.org/blog/dom-storage/

Lifetime of window.localStorage.setItem()

It is completely upto the u.There is no definite lifetime of it.you can have a look at the following.It might help you.
http://ejohn.org/blog/dom-storage/

make localStorage or sessionStorage expire like cookies

The best you can do is to set a timestamp in storage, and if the user visits your site after a specified amount of time, then you can delete the stored data.

sessionStorage should work the same way, except when it doesn't even last long enough for your timed expiration. In that case, it'll expire sooner.

How to set expiration time for data stored in ReactJs localStorage

localStorage does not have support for expiration dates.

You can although save in localStorage a timestamp and next time the app starts up, check the timestamp and if it is too old than clean your app's localStorage.

Another way, if you want to set an expiration date on something, you can try with Cookies

There are some packages that help with this like js-cookie

Local Storage vs Cookies

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You'll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.



Related Topics



Leave a reply



Submit