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?

  1. Reducing Server Requests: Storing data locally minimizes API calls, leading to faster page loads and reduced server load.

  2. Enhancing User Experience: Persistent storage allows users to retain their preferences, such as themes, settings, and login status.

  3. Improved Performance: Faster access to locally stored data enhances overall application performance.

  4. 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

FeatureLocal StorageSession Storage
Storage Limit~5-10 MB~5-10 MB
Data ExpiryNever (until manually cleared)Expires when the session (tab) is closed
AccessibilityOnly accessible within the same originOnly accessible within the same origin
Stored FormatKey-value pairs (string)Key-value pairs (string)
Security ConcernData is available permanently, so sensitive data should not be stored hereTemporary storage, safer for sensitive data
Use CaseUser preferences, themes, saved settingsForm 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.