Local & Session Storage

Illustration of Local & Session Storage
Illustration of Local & Session Storage

Web Storage API provides two ways to store data on the client side:

  • Local Storage: Stores data with no expiration date.
  • Session Storage: Stores data for the duration of the page session.

💡 Key Difference

Local Storage persists data even after the browser is closed. Session Storage data is cleared when the tab or window is closed.

Local Storage vs Session Storage
FeatureLocal StorageSession Storage
LifetimePersistent, no expirationUntil tab/window closes
ScopeShared across all tabs/windows from the same originUnique per tab/window
Storage limitTypically 5-10 MBTypically 5-10 MB
Accesswindow.localStoragewindow.sessionStorage

Basic API Methods

  • setItem(key, value): Stores a key-value pair.
  • getItem(key): Retrieves the value by key.
  • removeItem(key): Deletes the key and its value.
  • clear(): Clears all stored data.
  • key(index): Returns the key at the given index.
  • length: Property indicating number of stored items.

⚠️ Important!

Both storage types only store strings. To store objects or arrays, convert them to JSON strings using JSON.stringify() and parse with JSON.parse() when retrieving.

📌 Deep Dive: Storing and Retrieving an Object in Local Storage

JAVASCRIPT
const user = { name: "Alice", age: 30 };

// Save object as string
localStorage.setItem("user", JSON.stringify(user));

// Retrieve and parse back to object
const storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // Alice
Output
Alice

Use Cases

  • Local Storage: Saving user preferences, themes, or tokens that persist across sessions.
  • Session Storage: Storing temporary data like form inputs or session-specific info that shouldn't persist after closing the tab.

💡 Security Consideration

Never store sensitive data like passwords or personal info in web storage, as it is accessible by any script from the origin.

Example: Using Session Storage

  • Store user input temporarily:

📌 Deep Dive: Session Storage Example

JAVASCRIPT
// Store data for this session
sessionStorage.setItem("visitedPage", "home");

// Retrieve data
console.log(sessionStorage.getItem("visitedPage")); // home

// Data removed when tab closes
Output
home

⚠️ Browser Support

Modern browsers support web storage, but always check compatibility if targeting older browsers.