When working on web applications, you can store data locally in the user’s browser using the HTML5 Web Storage feature.
Web storage allows you to store data, such as user preferences, session information, etc., locally within the user’s browser. This improves user experience and reduces the need to repeatedly fetch data from the server.
The saved data stays in the browser and can not be transferred anywhere else. You can access and manipulate this data to enhance your web applications and create a smoother user experience.
Web storage has two main types:
- Local Storage
- Session Storage
What are Local Storage and Session Storage?
Local Storage and Session Storage are types of web storage provided by modern web browsers to store data in the user’s browser.
They both allow you to store data in the form of key-value pairs that stay in the browser even after the user closes the browser tab or the entire browser session.
Now, you might be wondering that both storage options allow you to store data, but what sets them apart from each other?
So, let’s learn about local storage and session storage individually to gain a better understanding of each.
Local Storage
Local Storage is a web storage option that allows you to store data in key-value pairs in a web browser with no expiration time.
This means that data stored in Local Storage persists within the browser even after the user closes the browser tab, ends the entire browser session, or navigates away from the page.
To work with Local Storage, you can use the localStorage
object in JavaScript.
Here’s how you can store, access, and remove data using Local Storage:
Storing Data Item
Syntax:
localStorage.setItem(key, value);
Here, key
is the name or identifier for the data item you want to store, and value
is the value for that specified key.
Example:
// Storing data item in Local Storage
localStorage.setItem("firstName", "Johan"); // stores key 'firstName' with value 'Johan'
localStorage.setItem("lastName", "Fortner"); // stores key 'lastName' with value 'Fortner'
localStorage.setItem("email", "johan@example.com"); // stores key 'email' with value 'johan@example.com'
Your browser is storing this data like:
{
"firstName": "Johan",
"lastName": "Fortner",
"email": "johan@example.com"
}
Note: All data in localStorage is stored as strings. If you want to store objects or arrays, you need to use JSON.stringify()
.
For example:
// This won’t work as expected
localStorage.setItem("user", { name: "Shefali", age: 26 });
// Correct way using JSON.stringify()
const user = {
name: "Shefali",
age: 24,
isLoggedIn: true,
};
// Convert object to string before storing
localStorage.setItem("user", JSON.stringify(user));
Accessing Data Item
Syntax:
localStorage.getItem(key);
Here, key
is the name of the data item you want to retrieve (must match exactly how it was stored). It returns the value stored for that key, or null
if the key doesn't exist.
Example:
// Accessing data item from Local Storage
const firstName = localStorage.getItem("firstName");
const lastName = localStorage.getItem("lastName");
const email = localStorage.getItem("email");
console.log(firstName); // Output: Johan
console.log(lastName); // Output: Fortner
console.log(email); // Output: johan@example.com
Note: If you stored data using JSON.stringify()
(like an object or array), you’ll need to use JSON.parse()
to convert it back.
For example:
const userData = JSON.parse(localStorage.getItem("user"));
console.log(userData.name);
Removing Data Item
Syntax:
localStorage.removeItem(key);
Example:
// Removing data item from Local Storage
localStorage.removeItem("lastName");
Removing All the Local Storage Items
localStorage.clear();
Session Storage
Session Storage is similar to Local Storage, but it stores data only for the duration of a page session.
That means when the user closes the tab or browser, data stored in Session Storage will be deleted.
To work with Session Storage, you can use the sessionStorage
object in JavaScript.
Here’s how you can store, access, and remove data using Session Storage:
Storing Data Item
Syntax:
sessionStorage.setItem(key, value);
Here, key
is the name or identifier for the data item you want to store, and value
is the value for that specified key.
Just like localStorage, all values are stored as strings.
Example:
// Storing data item in Session Storage
sessionStorage.setItem("firstName", "Johan");
sessionStorage.setItem("lastName", "Fortner");
sessionStorage.setItem("email", "johan@example.com");
Accessing Data Item
Syntax:
sessionStorage.getItem(key);
Here, key
is the name of the data you want to retrieve (must match exactly how it was stored). It returns the value (as a string) for that key, or null
if the key doesn’t exist.
Example:
// Accessing data item from Session Storage
const firstName = sessionStorage.getItem("firstName");
const lastName = sessionStorage.getItem("lastName");
const email = sessionStorage.getItem("email");
console.log(firstName); // Output: Johan
console.log(lastName); // Output: Fortner
console.log(email); // Output: johan@example.com
Removing Data Item
Syntax:
sessionStorage.removeItem(key);
Example:
// Removing data item from Session Storage
sessionStorage.removeItem("lastName");
Removing All the Session Storage Items
sessionStorage.clear();
Checking Browser Support for Local and Session Storage
Here’s how you can check browser support for local and session storage.
// Check for localStorage browser support
const localStorageSupported = typeof localStorage !== "undefined";
// Check for sessionStorage browser support
const sessionStorageSupported = typeof sessionStorage !== "undefined";
console.log(`localStorage supported: ${localStorageSupported}`);
console.log(`sessionStorage supported: ${sessionStorageSupported}`);
Here,
-
localStorageSupported
checks the type oflocalStorage
and if the type oflocalStorage
is not equal to ‘undefined’, then the value of this variable will be set totrue
, which means the browser supports local storage. Otherwise, it is set tofalse
, which means the browser does not support local storage. -
sessionStorageSupported
checks the type ofsessionStorage
and if the type ofsessionStorage
is not equal to ‘undefined’, then the value of this variable will be set totrue
, which means the browser supports session storage. Otherwise, it is set tofalse,
which means the browser does not support session storage.
Differences Between Local Storage and Session Storage
Here are the key differences between local storage and session storage.
-
Data Lifespan: Data stored in local storage persists within the browser even after the user closes the browser tab, ends the entire browser session, or navigates away from the page. This is like long-term memory. Data stored in session storage will be lost when the user closes the tab or browser. This is like short-term memory.
-
Storage Capacity: The capacity of Local Storage can range from 5 to 10 MB per domain, depending on the browser. Session Storage also provides a similar storage capacity, but usually enough for temporary needs.
-
Scope: Data stored in Local Storage in one tab or window is accessible to scripts running in other tabs or windows of the same origin domain. Data stored in Session Storage in one tab is not accessible to scripts running in other tabs or windows, even if they belong to the same domain.
-
Use Cases: Local Storage is used for storing data such as user preferences, cached data, remembering user login info, etc. Session Storage is used for storing data such as multi-page form progress, shopping cart, game states, etc.
Best Practices for localStorage & sessionStorage
-
Store Only Small, Non-Sensitive Data:
- Web storage is not encrypted. Never store passwords, tokens, or personal user data.
- Ideal for things like UI preferences, theme settings, or temporary form data.
-
Always Convert Complex Data:
- Use
JSON.stringify()
to store objects or arrays. - Use
JSON.parse()
to read them back.
- Use
-
Use Meaningful Keys:
Keep your keys consistent and clear (e.g.,
"user_theme"
instead of"data1"
). -
Check for Availability
Not all environments (e.g., private browsing or older browsers) support it. Always check availability before using it.
-
Handle Missing or Invalid Data Gracefully:
Always check if data exists before using it.
const theme = localStorage.getItem("theme") || "light";
-
Use
try...catch
When Parsing JSON:Prevent your app from crashing if the stored data is invalid.
try { const data = JSON.parse(localStorage.getItem("settings")); } catch (e) { console.error("Invalid JSON in localStorage"); }
-
Use sessionStorage for Temporary Data:
Great for form steps, quiz progress, etc., that shouldn't persist beyond a tab session.
-
Avoid Polluting Storage:
Remove outdated or unused keys with
removeItem()
orclear()
when needed. -
Sync Across Tabs (If Needed):
Use the storage event to react to changes made in other tabs/windows.
window.addEventListener("storage", (event) => { console.log("Storage changed:", event.key, event.newValue); });