Web Storage
The Web Storage API provides a mechanism for browsers to store key/value pairs, in a much more intuitive way than using cookies. There are two types of web storage:
sessionStorage: Stores data for one session only. The data is lost when the browser tab is closed.localStorage: Stores data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year.
localStorage
The localStorage object allows you to store data that persists even after the browser is closed.
Storing Data
You can store data in localStorage using the setItem() method:
localStorage.setItem('name', 'John Doe');
Retrieving Data
You can retrieve data from localStorage using the getItem() method:
const name = localStorage.getItem('name');
console.log(name); // "John Doe"
Removing Data
You can remove a specific item from localStorage using the removeItem() method:
localStorage.removeItem('name');
Clearing All Data
You can clear all items from localStorage using the clear() method:
localStorage.clear();
sessionStorage
The sessionStorage object works in the same way as localStorage, but the data is only stored for the current session.
// Store data
sessionStorage.setItem('username', 'johndoe123');
// Retrieve data
const username = sessionStorage.getItem('username');
console.log(username); // "johndoe123"
Important Notes
- Web storage can only store strings. If you want to store an object or an array, you need to convert it to a string first using
JSON.stringify(), and then parse it back withJSON.parse()when you retrieve it. - Web storage is synchronous, which means that each operation will block the main thread until it is complete. For this reason, you should avoid using it for large amounts of data.
- The storage limit for web storage is around 5MB per domain, but this can vary between browsers.