HTML Web Storage API

πŸ“¦ Introduction to the Web Storage API

The Web Storage API provides a simple way to store key-value data in the browser, allowing websites to save data on the client side persistently or temporarily. It's a modern alternative to cookies, offering more space and easier usage without sending data to the server on every request. 🧠

>>β€œLocal data storage for a faster, smarter web.” πŸš€

πŸ“Œ Types of Web Storage

  • localStorage: Stores data with no expiration β€” persists even after the browser is closed.
  • sessionStorage: Stores data only for the duration of the page session β€” cleared when the tab or window is closed.

βš™οΈ Basic Usage of localStorage

Saving and Retrieving Data

// Save data
localStorage.setItem('username', 'JaneDoe');

// Retrieve data
const user = localStorage.getItem('username');
console.log(user); // Outputs: JaneDoe

// Remove data
localStorage.removeItem('username');

// Clear all data
localStorage.clear();

βš™οΈ Basic Usage of sessionStorage

Saving and Retrieving Data

// Save data
sessionStorage.setItem('token', 'abc123');

// Retrieve data
const token = sessionStorage.getItem('token');
console.log(token); // Outputs: abc123

// Remove data
sessionStorage.removeItem('token');

// Clear all data
sessionStorage.clear();

🧩 Storing Objects and Complex Data

Web Storage stores data as strings. To store objects or arrays, use JSON.stringify() when saving and JSON.parse() when retrieving.

Storing Objects Example

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

// Save object
localStorage.setItem('user', JSON.stringify(user));

// Retrieve object
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // Outputs: Alice

🧠 Tips & Best Practices

  • Do not store sensitive information in Web Storage (like passwords or tokens).
  • Check for Web Storage support using 'localStorage' in window before using it.
  • Be mindful of storage limits (~5MB per origin in most browsers).
  • Clear storage when data is no longer needed to save space.

πŸ”— Useful Resources

>>β€œEffortless client-side storage powers smooth, responsive web apps.” πŸ’‘