Understanding Web Storage
The Web Storage API allows webpages to store key-value data in the user's browser using local storage or session storage.
JavaScript can save, retrieve, update, and remove stored values without sending the information to a web server. The two storage mechanisms behave similarly, but they differ in how long their data remains available.
Local Storage
The localStorage object stores data for an origin without automatically removing it when the browser tab or window is closed.
localStorage.setItem("name", "Alex");
A value saved in local storage can therefore remain available when the user returns to the same website later, unless the data is removed by the webpage, the user, or the browser.
Local storage can be useful for information such as interface preferences, settings, or other small pieces of data that should remain available between browsing sessions.
Session Storage
The sessionStorage object uses the same basic key-value approach as local storage, but its lifetime is tied to the page's browsing session.
sessionStorage.setItem("name", "Alex");
Session storage is separated by browser tab or browsing context. Reloading the page normally preserves the stored values, but closing the tab or window ends that page session and removes its session storage.
This makes session storage useful for temporary information that should survive page reloads but does not need to remain after the browsing session ends.
Local Storage vs. Session Storage
Local storage and session storage provide similar methods, so the primary difference is the lifetime and scope of the stored data.
| Feature | localStorage | sessionStorage |
|---|---|---|
| Storage type | Key-value storage | Key-value storage |
| After page reload | Remains available | Remains available |
| After tab closes | Normally remains available | Removed when the page session ends |
| Shared between same-origin tabs | Generally yes | No, each page session has its own storage |
| Common use | Persistent preferences and settings | Temporary session information |
Storing Data
The setItem() method stores a value using a key that identifies it.
localStorage.setItem("username", "Alex");
The first argument is the key and the second argument is the value being stored.
The same method is available with session storage:
sessionStorage.setItem("username", "Alex");
Retrieving Data
The getItem() method retrieves the value associated with a stored key.
const username = localStorage.getItem("username");
If the requested key does not exist, getItem() returns null.
const color = localStorage.getItem("favoriteColor");
if (color === null) {
console.log("No color has been saved.");
}
Updating Stored Data
Calling setItem() with a key that already exists replaces the value stored under that key.
localStorage.setItem("theme", "light");
localStorage.setItem("theme", "dark");
After these statements run, the value associated with theme is dark.
There is no separate update method because setItem() handles both creating and replacing stored values.
Removing Stored Data
The removeItem() method removes a specific key and its value.
localStorage.removeItem("username");
The clear() method removes all entries from that storage object for the current origin.
localStorage.clear();
Use clear() carefully because it affects all values stored in that storage area for the origin, not just the data associated with one feature.
Web Storage Stores Strings
Web Storage stores keys and values as strings. Values such as numbers and Boolean values are converted to strings when they are stored.
localStorage.setItem("score", 25);
const score = localStorage.getItem("score");
console.log(typeof score);
The retrieved value is the string "25", not a JavaScript number. Convert stored values back to the required data type when necessary.
const score = Number(localStorage.getItem("score"));
Storing Objects and Arrays
JavaScript objects and arrays cannot be stored directly as their original structures in Web Storage. A common approach is to convert them to JSON text before storing them.
const user = {
name: "Alex",
theme: "dark"
};
localStorage.setItem("user", JSON.stringify(user));
When the information is retrieved, JSON.parse() can convert the stored JSON text back into a JavaScript value.
const storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name);
Code should still account for missing or invalid stored data rather than assuming that parsing will always succeed.
The Storage Event
The storage event can notify other same-origin documents when certain Web Storage data changes.
window.addEventListener("storage", (event) => {
console.log(event.key);
console.log(event.newValue);
});
For local storage, this can be useful when multiple tabs from the same origin need to respond when another tab changes stored information.
The event is delivered to other relevant documents rather than the same window that made the storage change.
Privacy and Security
Web Storage is convenient, but it should not be treated as a secure location for sensitive information. JavaScript running within the same origin can potentially access stored values.
Do not store passwords, private authentication credentials, or other secrets in local storage or session storage simply because the browser makes the storage easy to use.
Web Storage is also subject to browser storage and privacy policies. Users can clear stored site data, browsers can restrict storage in some circumstances, and applications should not assume that stored information will remain available forever.
Complete Web Storage Example
The following example allows a user to enter a name, save it in local storage, display the saved value, and remove it.
<label for="name">Name:</label>
<input type="text" id="name">
<button type="button" id="save">Save Name</button>
<button type="button" id="remove">Remove Name</button>
<p id="result"></p>
<script>
const nameInput = document.querySelector("#name");
const saveButton = document.querySelector("#save");
const removeButton = document.querySelector("#remove");
const result = document.querySelector("#result");
function showSavedName() {
const savedName = localStorage.getItem("name");
if (savedName) {
result.textContent = "Saved name: " + savedName;
} else {
result.textContent = "No name has been saved.";
}
}
saveButton.addEventListener("click", () => {
localStorage.setItem("name", nameInput.value);
showSavedName();
});
removeButton.addEventListener("click", () => {
localStorage.removeItem("name");
showSavedName();
});
showSavedName();
</script>
Because the example uses local storage, the saved name remains available after the page is refreshed. It can also remain available after the browser is closed and the page is visited again later.
Common Web Storage Mistakes
| Mistake | Better Approach |
|---|---|
| Expecting session storage to remain after the page session ends | Use local storage when information needs to persist between sessions. |
| Expecting stored numbers to remain numbers | Remember that Web Storage stores string values and convert them when necessary. |
| Trying to store an object directly | Serialize suitable objects with JSON.stringify() and restore them with JSON.parse(). |
Using clear() to remove one setting |
Use removeItem() when only one stored value should be removed. |
| Storing passwords or other secrets | Do not treat browser Web Storage as secure storage for sensitive credentials. |
| Assuming stored data always exists | Handle missing values and the possibility that users or browsers have cleared site data. |
Best Practices
- Choose local storage when data should normally persist between browsing sessions.
- Choose session storage when data should exist only for the current page session.
- Use clear and specific key names, especially when a website stores values for several features.
- Remember that Web Storage stores string values.
- Use JSON when suitable objects or arrays need to be represented as stored text.
- Check for missing or invalid stored values before using them.
- Use
removeItem()when removing a specific value instead of unnecessarily clearing all storage. - Do not use Web Storage for passwords, authentication secrets, or other sensitive credentials.
- Do not assume stored data will remain available permanently.
- Store only the information the webpage actually needs.
Summary
The Web Storage API provides localStorage and sessionStorage for storing key-value data in the browser. Both provide methods such as setItem(), getItem(), removeItem(), and clear(), but they differ in how long and where their data remains available.
Local storage is useful when small amounts of data should persist between browsing sessions, while session storage is designed for temporary data associated with a page session. Next, we will look at the History API and how JavaScript can interact with the browser's session history.
