Local Storage & Session Storage
What are Local Storage and Session Storage?
In modern web development, storing data on the client side is crucial for performance and user experience. Two primary ways to achieve this in browsers are Local Storage and Session Storage.
Both are part of the Web Storage API, allowing web applications to store data in a key-value format. They help persist user-specific information without requiring frequent server communication.
Why Do We Need Local Storage and Session Storage?
Reducing Server Requests: Storing data locally minimizes API calls, leading to faster page loads and reduced server load.
Enhancing User Experience: Persistent storage allows users to retain their preferences, such as themes, settings, and login status.
Improved Performance: Faster access to locally stored data enhances overall application performance.
Managing Temporary Data: Some data should only persist during a session (e.g., form inputs, temporary cache). Session Storage is ideal for this use case.
Difference Between Local Storage and Session Storage
Feature | Local Storage | Session Storage |
Storage Limit | ~5-10 MB | ~5-10 MB |
Data Expiry | Never (until manually cleared) | Expires when the session (tab) is closed |
Accessibility | Only accessible within the same origin | Only accessible within the same origin |
Stored Format | Key-value pairs (string) | Key-value pairs (string) |
Security Concern | Data is available permanently, so sensitive data should not be stored here | Temporary storage, safer for sensitive data |
Use Case | User preferences, themes, saved settings | Form data, temporary user session, cart details |
Lifespan of Local Storage vs. Session Storage
User opens the website --> Data stored in Local Storage persists across visits
--> Data in Session Storage is cleared when the tab is closed
Code Examples
Using Local Storage
// Store data
localStorage.setItem("username", "JohnDoe");
// Retrieve data
console.log(localStorage.getItem("username")); // Output: JohnDoe
// Remove data
localStorage.removeItem("username");
Use Case: Ideal for saving user settings like theme preferences (dark/light mode).
Using Session Storage
// Store data
sessionStorage.setItem("sessionID", "123456");
// Retrieve data
console.log(sessionStorage.getItem("sessionID")); // Output: 123456
// Remove data
sessionStorage.removeItem("sessionID");
Use Case: Ideal for storing temporary data like form inputs while filling out a multi-step form.