Data saved with localStorage never expires. A value you write today is still there next year unless the user clears their browser data or your code removes it. That is fine for a theme preference. It is a problem for a cached API response that goes stale, a dismissed banner that should return after a week, or a form draft that should not outlive the day.
Cookies have an Expires and Max-Age setting. localStorage has nothing like it, so you add the expiry yourself. This guide shows the pattern, a basic version, a reusable helper that handles the failure cases, and how to test it.
How the expiry pattern works
You can't ask the browser to delete an item later. A setTimeout() doesn't help either, because a timer only lives while the page is open. Close the tab and it is gone, and the item stays in storage.
The fix is to save a timestamp next to the value and check it when you read:
- When saving, store an object with two fields: the
valueand anexpiresAttime in milliseconds (Date.now()plus the lifetime you want). - When reading, parse the object and compare
expiresAtwithDate.now(). - If the time has passed, remove the item and return
null. Otherwise return the value.
Basic version
This is the smallest working implementation. Use it to understand the idea, but not as the final code, because it breaks on bad data and when storage is unavailable.
function setWithExpiry(key, value, ttlMs) {
const item = { value, expiresAt: Date.now() + ttlMs };
localStorage.setItem(key, JSON.stringify(item));
}
function getWithExpiry(key) {
const raw = localStorage.getItem(key);
if (!raw) return null;
const item = JSON.parse(raw);
if (Date.now() >= item.expiresAt) {
localStorage.removeItem(key); // expired, so clean it up
return null;
}
return item.value;
}
Usage looks like this. The third argument is the lifetime in milliseconds, so one hour is 60 * 60 * 1000:
setWithExpiry("greeting", "Hello", 60 * 60 * 1000);
getWithExpiry("greeting"); // "Hello" for the next hour, then null
What can go wrong
The basic version fails in several ordinary situations. Each one is handled in the final helper.
| Situation | What happens | How the helper handles it |
|---|---|---|
| The stored value is not JSON, for example old data or another script's key | JSON.parse() throws a SyntaxError. |
The read is wrapped in try/catch. The item is treated as missing and left untouched. |
The stored JSON has no expiresAt |
The comparison with undefined is always false, so the item never expires. |
Only records with a numeric expiresAt are accepted. |
| Storage is full | setItem() throws QuotaExceededError. |
The error is caught and set() returns false. |
| The browser blocks storage | Even touching localStorage can throw a SecurityError. |
Every storage call sits inside try/catch. |
The value is 0, false or an empty string |
A check like if (!value) treats real data as missing. |
The helper tests whether a record exists, not whether the value is truthy. |
| An item is never read again | It stays in storage forever. | clearExpired() removes every expired item with your prefix. |
Reusable helper
This version adds a key prefix, validation, error handling and the cleanup method. The prefix keeps your keys apart from other scripts on the same origin and limits the cleanup loop to your own items.
function createExpiringStorage(prefix = "") {
const fullKey = (key) => prefix + key;
// Returns the saved value, or undefined when the item is missing, expired or not ours.
function read(storageKey) {
let raw;
try {
raw = localStorage.getItem(storageKey);
} catch {
return undefined; // storage blocked by the browser
}
if (raw === null) return undefined;
try {
const record = JSON.parse(raw);
if (record && typeof record === "object" && typeof record.expiresAt === "number") {
if (Date.now() >= record.expiresAt) {
localStorage.removeItem(storageKey);
return undefined;
}
return record;
}
} catch {
// Not JSON, so it was not saved by this helper. Leave it alone.
}
return undefined;
}
return {
set(key, value, ttlMs) {
if (!(ttlMs > 0)) throw new RangeError("ttlMs must be a positive number of milliseconds");
try {
localStorage.setItem(
fullKey(key),
JSON.stringify({ value, expiresAt: Date.now() + ttlMs })
);
return true;
} catch (error) {
console.warn(`Could not save "${key}":`, error.name);
return false; // quota exceeded or storage unavailable
}
},
get(key, fallback = null) {
const record = read(fullKey(key));
return record ? record.value : fallback;
},
remove(key) {
try {
localStorage.removeItem(fullKey(key));
} catch {}
},
// Deletes every expired item that belongs to this prefix.
clearExpired() {
try {
for (let i = localStorage.length - 1; i >= 0; i--) {
const storageKey = localStorage.key(i);
if (storageKey && storageKey.startsWith(prefix)) read(storageKey);
}
} catch {}
},
};
}
The methods returned at the end keep access to prefix after createExpiringStorage() has finished running. That is a closure, and it is why each store you create remembers its own prefix.
One detail in clearExpired(): the loop counts down from the last index. Removing an item shifts the indexes of everything after it, so counting up would skip entries.
Using it
const MINUTE = 60 * 1000;
const DAY = 24 * 60 * MINUTE;
const store = createExpiringStorage("app:");
// Run once when the page loads.
store.clearExpired();
// Remember that the visitor closed a banner for 7 days.
store.set("promo-dismissed", true, 7 * DAY);
// Cache an API response for 10 minutes.
store.set("latest-posts", [{ id: 1, title: "Hello" }], 10 * MINUTE);
if (!store.get("promo-dismissed")) {
showPromoBanner(); // your own function
}
const posts = store.get("latest-posts"); // null once the 10 minutes are up
Call clearExpired() once when the page loads. It only touches keys that start with your prefix, so it stays cheap even when other scripts use storage on the same site.
Choosing a lifetime
| Use case | Typical lifetime | Reason |
|---|---|---|
| Dismissed promo banner | 7 days | The banner can return after a reasonable pause. |
| Cached API response | 5 to 15 minutes | Data goes stale quickly, but repeat visits still skip a request. |
| Form draft | 24 hours | Recovers work after an accidental refresh without keeping old drafts. |
| A/B test bucket | 30 days | Keeps a visitor in the same variant for a full test period. |
| Theme or language preference | None | It should last until the user changes it, so plain localStorage is enough. |
localStorage, with or without an expiry. Any script that runs on your page can read it, which includes a script injected through a cross-site scripting (XSS) bug. An expiry limits how long data sits there, but it does not protect it. Anyone can also edit the stored expiresAt in DevTools, so never use it as a security check.
Test it
- Open any page on your site and press F12 to open DevTools.
- Paste the helper into the Console and press Enter.
- Create a store and save a value that lasts five seconds, using the commands below. The first
get()returns the value. - Wait six seconds and run
store.get("test")again. It now returnsnull. - Open Application, then Local Storage, and confirm the
app:testentry is gone.
const store = createExpiringStorage("app:");
store.set("test", "hello", 5000);
store.get("test"); // "hello"
// wait 6 seconds, then run:
store.get("test"); // null
Expiry is a maximum, not a guarantee
Your expiry sets the latest moment an item can be returned. Browsers can delete it sooner.
localStorage, after seven days of Safari use without the user interacting with your site. A 30-day lifetime can therefore end early on Safari. Write your code so a missing value is normal, and fall back to a default.
The device clock matters too. Date.now() reads the user's system time, so a visitor who changes their clock can shorten or extend an expiry. For anything where that matters, compare against a timestamp from your server instead.
localStorage with expiry, sessionStorage or cookies
| Feature | localStorage + expiry | sessionStorage | Cookie |
|---|---|---|---|
| Lifetime | Set by your code, enforced when read | Ends when the tab closes | Set with Expires or Max-Age, enforced by the browser |
| Sent to the server | No | No | Yes, with every matching request |
| Size | Around 5 MB per origin in most browsers | Around 5 MB per origin in most browsers | About 4 KB per cookie |
| Hidden from JavaScript | No | No | Yes, with the HttpOnly flag |
| Best for | Client-only data that should last a set time | Temporary state for one tab | Data the server needs, such as a session ID |
If the server needs the value, use a cookie. If it only matters for the current tab, use sessionStorage. If it is client-only and should live for a defined period, use the helper above.
Troubleshooting
get() always returns null
Check three things. First, localStorage is separate for each origin, so http and https, or www and the bare domain, do not share data. Second, make sure you use the same prefix for set() and get(). Third, confirm the lifetime is in milliseconds. Passing 7 instead of 7 * 24 * 60 * 60 * 1000 expires the item after seven milliseconds.
SyntaxError from JSON.parse
The key holds something that was not written by the helper, usually plain text from older code. The helper ignores those values, but the basic version throws. If the Console message is unclear, how to read error messages like a developer shows how to find the useful line. Open Application, then Local Storage, and delete the bad entry.
set() returns false
The browser rejected the write. The usual causes are a full quota, or storage disabled in a private window or an embedded frame. Save less data, or treat the cache as optional and continue without it.
FAQs
Does localStorage have a built-in expiration time?
No. Items stay until your code removes them or the user clears site data. To add an expiry, save a timestamp with the value and check it every time you read.
Why not use setTimeout() to delete the item?
A timer only runs while the page is open. If the visitor closes the tab after two minutes, the timer never fires and the item stays in storage. A saved timestamp works across visits.
Can I reset the expiry every time the user visits?
Yes. This is called a sliding expiry. Read the value, then save it again with a fresh lifetime. A small wrapper around the helper does it:
function getAndRenew(store, key, ttlMs) {
const value = store.get(key);
if (value !== null) store.set(key, value, ttlMs);
return value;
}
Is an expiry time in localStorage secure?
No. Anyone can open DevTools and change or delete the stored timestamp, and any script on the page can read the data. Use the expiry for convenience features such as caching and reminders, never for authentication or access control.
Do other tabs see the same expiry?
Yes. All tabs on the same origin share one localStorage, so an item that expires or gets removed in one tab is gone in the others. The browser also fires a storage event in other tabs when an item changes, if you need to react to it.
Conclusion
localStorage has no expiry, but saving expiresAt beside each value and checking it on read gives you one. Use the helper with a prefix, handle failed writes, and run clearExpired() on page load so old items don't pile up. Treat a missing value as normal, since browsers can clear storage before your expiry arrives, and keep sensitive data out of it.