When we close and reopen a webpage, JavaScript variables usually disappear because they only exist while the page is running.
But what if we want to remember some information?
For example:
Remember a user's theme preference
Save items in a shopping cart
Remember a username
Store application settings
Keep temporary data during a browsing session
For these situations, browsers provide Web Storage, mainly through localStorage and sessionStorage.
What is Web Storage?
Web Storage is a browser feature that allows JavaScript to store data as key-value pairs on the user's device.
The two main storage mechanisms are:
localStorage
sessionStorageThey work in a similar way, but their lifetime is different.
|
|
|---|---|
Data persists after closing the browser | Data is tied to the current page session |
Stays until removed | Usually cleared when the page session ends |
Useful for persistent preferences | Useful for temporary data |
Shared across tabs/windows for the same origin | Separate for each tab/window |
Both APIs store values as strings.
localStorage
localStorage allows us to store data that should remain available across browser sessions.
For example:
localStorage.setItem("username", "John");Now "John" is stored under the key "username".
Even if the user refreshes the page or closes and reopens the browser, the value can remain available until it is removed or the browser's stored data is cleared.
Storing Data with setItem()
The basic syntax is:
localStorage.setItem("key", "value");For example:
localStorage.setItem("theme", "dark");
localStorage.setItem("language", "English");We have now stored two values.
Reading Data with getItem()
To retrieve a stored value, use getItem():
const theme = localStorage.getItem("theme");
console.log(theme);Output:
darkIf the key doesn't exist, getItem() returns:
nullFor example:
console.log(localStorage.getItem("username"));If "username" hasn't been stored, the result is:
nullUpdating Stored Data
If we store a value using an existing key, the old value is replaced.
localStorage.setItem("username", "John");
localStorage.setItem("username", "Alex");
console.log(localStorage.getItem("username"));Output:
AlexSo setItem() can be used both to create and update stored values.
Removing Data
We can remove a specific item using removeItem().
localStorage.removeItem("username");Now:
console.log(localStorage.getItem("username"));returns:
nullClearing Local Storage
If we want to remove all local storage data for the current origin, we can use:
localStorage.clear();Be careful with this because it removes everything stored by your application under that origin.
Checking the Number of Stored Items
The length property tells us how many stored entries there are.
console.log(localStorage.length);We can also get a key by its position:
console.log(localStorage.key(0));The order should not be relied upon for application logic.
Storing Objects
Here's an important limitation:
Web Storage stores strings.
Suppose we try:
const user = {
name: "John",
age: 25
};
localStorage.setItem("user", user);This does not store the object as an object. It gets converted to a string representation that isn't useful for restoring the original structure.
Instead, we use JSON.stringify().
const user = {
name: "John",
age: 25
};
localStorage.setItem("user", JSON.stringify(user));Now the object is converted into a JSON string.
Reading an Object
When retrieving the object, we need to convert the JSON string back into a JavaScript object using JSON.parse().
const data = localStorage.getItem("user");
const user = JSON.parse(data);
console.log(user.name);
console.log(user.age);Output:
John
25So the process is:
JavaScript Object
↓
JSON.stringify()
↓
String
↓
localStorage
↓
getItem()
↓
JSON.parse()
↓
JavaScript ObjectStoring Arrays
The same technique works with arrays.
const fruits = ["Apple", "Banana", "Mango"];
localStorage.setItem("fruits", JSON.stringify(fruits));To retrieve it:
const fruits = JSON.parse(
localStorage.getItem("fruits")
);
console.log(fruits);Output:
["Apple", "Banana", "Mango"]sessionStorage
sessionStorage works almost exactly like localStorage.
For example:
sessionStorage.setItem("username", "John");Read it with:
const username = sessionStorage.getItem("username");
console.log(username);Remove it with:
sessionStorage.removeItem("username");And clear it with:
sessionStorage.clear();The main difference is how long the data lasts and how it is scoped.
localStorage vs sessionStorage
Let's make the difference clearer.
localStorage
localStorage.setItem("theme", "dark");The data can remain available even after:
Refresh page
↓
Close tab
↓
Close browser
↓
Open browser again
↓
Data can still be thereIt stays until your application removes it or the browser/user clears the stored data.
sessionStorage
sessionStorage.setItem("step", "2");The data is associated with the current page session, so it's useful for temporary information.
A simple way to remember:
localStorage → Keep it around
sessionStorage → Keep it for this session
Storage Is Per Origin
Web Storage is associated with an origin, which is roughly the combination of:
protocol + hostname + portFor example, storage for:
https://example.comis separate from storage for another origin.
This is why different websites cannot simply read each other's localStorage.
A Practical Example: Saving a Theme
Suppose our website has a dark mode.
We can save the user's choice:
localStorage.setItem("theme", "dark");Later, when the page loads:
const theme = localStorage.getItem("theme");
if (theme === "dark") {
document.body.classList.add("dark");
}Now the website can remember the user's theme preference.
We could change it back:
localStorage.setItem("theme", "light");This is a very common real-world use of localStorage.
A Practical Example: Shopping Cart
Suppose we have a shopping cart:
const cart = ["Laptop", "Mouse", "Keyboard"];
localStorage.setItem("cart", JSON.stringify(cart));When the user comes back:
const savedCart = localStorage.getItem("cart");
const cart = savedCart
? JSON.parse(savedCart)
: [];
console.log(cart);Now the application can restore the previously saved cart.
Handling Invalid JSON
When using JSON.parse(), the stored data might not always contain valid JSON.
For example:
try {
const user = JSON.parse(
localStorage.getItem("user")
);
console.log(user);
} catch (error) {
console.log("Invalid stored data.");
}This is a good place to use the error-handling concepts we learned earlier.
Web Storage Is Not a Database
It's important to understand that localStorage isn't a replacement for a database.
It is designed for relatively small amounts of client-side data and has several limitations.
For example:
Data is stored as strings.
Storage capacity is limited.
It is synchronous.
Data belongs to the browser/client.
Users can clear or modify it.
It should not be treated as a trusted data source.
For larger or more sophisticated client-side storage needs, web applications can use APIs such as IndexedDB.
Don't Store Sensitive Information
You should not treat localStorage or sessionStorage as a secure storage mechanism.
For example, avoid storing things like:
Passwords
Private authentication secrets
Sensitive personal information
Long-lived security tokens without understanding the risksJavaScript running on the page can access Web Storage, so an XSS vulnerability could potentially expose stored data.
For authentication, applications should use appropriate secure server-side mechanisms and carefully configured cookies where applicable.
Useful Web Storage Methods
Method / Property | Purpose |
|---|---|
| Stores a value |
| Retrieves a value |
| Removes a value |
| Removes all stored values |
| Gets a key by index |
| Number of stored items |
The same methods are available on both:
localStorage
sessionStorageConclusion
localStorage and sessionStorage provide a simple way for JavaScript applications to store data in the browser.
The basic operations are:
localStorage.setItem("name", "John");
const name = localStorage.getItem("name");
localStorage.removeItem("name");
localStorage.clear();And when working with objects or arrays:
localStorage.setItem("user", JSON.stringify(user));
const user = JSON.parse(
localStorage.getItem("user")
);The main difference is easy to remember:
localStorage→ Data persists until it is removed or cleared.sessionStorage→ Data is tied to the current page session.
Once you understand Web Storage, you can build features like remembered preferences, shopping carts, saved settings, temporary form data, and client-side application state much more easily.