Set data in localStorage with a limited time to live (TTL)

Yevheniia - Aug 11 - - Dev Community

Sometimes we need to set data in browser localStorage with a time to live (TTL).

Real-world example
We have an online store with a cart and liked products. A new customer comes to our store and, without authorization, starts adding products to the cart or liked list. In this case, we store each product from the shopping cart in browser localStorage. However, we don’t need to keep them there forever, localStorage is not infinite. If the user doesn’t continue the purchase within the next month, it means he/she might have lost interest, and we can clean that data from localStorage.

How can we do that?
Obviously, we can’t achieve this simply using the setTimeout method🙂

Option 1. We can set data in localStorage with the current date and expiration date fields and manually implement a function that checks whether the data has expired every time the page is reloaded and removes it if it has.
Option 2. This is much easier. Just use a ready-made solution— localstorage-slim. We can set values in localStorage with a TTL, and this package will handle the expiration and removal for us, so no extra checks are needed.

Here is an example of a vanilla JavaScript implementation:

**index.html**
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Test localstorage-slim</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="../favicon.ico" />
    <link rel="stylesheet" href="./css/main.css" type="text/css">
</head>

<body>
        <script src="https://cdn.jsdelivr.net/npm/localstorage-slim"></script>
    <script src="./js/main.js">
    </script>
</body>

</html>

**main.js**
const localStorageKey = ""; //your key here
const goodsIds = ["1", "2", "3"];

//set data
ls.set(localStorageKey, JSON.stringify(goodsIds), {
  ttl: 604800,
}); //one week in seconds

//get data
const dataFromLs = ls.get(localStorageKey);
Enter fullscreen mode Exit fullscreen mode
. . . .
Terabox Video Player