For a very long time, if a web developer wanted to remember a user's preferences (like a "Dark Mode" setting or items in a shopping cart) without forcing them to log into a database, they had to use Cookies.
Cookies are notoriously clunky. They can only hold a tiny amount of data (4KB), and they are sent back and forth to the server every single time an image, script, or page loads, which slows down the website.
HTML5 fixed this by introducing the Web Storage API, which allows websites to store up to 5MB of data directly on the user's local computer, securely and completely offline.
Web Storage is broken down into two distinct JavaScript objects. The one you choose depends entirely on how long you need the data to survive.
window.localStorage)Data stored in localStorage has no expiration date. If the user closes their browser, restarts their computer, and comes back to your site two years later, that data will still be sitting perfectly intact (unless they manually clear their browser history).
<script>
// Saving Data (Takes a Key and a Value)
localStorage.setItem("themePreference", "DarkMode");
// Reading Data
let userTheme = localStorage.getItem("themePreference");
// Deleting Data
localStorage.removeItem("themePreference");
</script>
window.sessionStorage)Data stored in sessionStorage is completely temporary. As soon as the user closes that specific browser tab or window, the data is instantly wiped out forever. This is perfect for single-use tasks like a multi-step checkout form.
<script>
// The syntax is identical to localStorage
sessionStorage.setItem("currentWizardStep", "3");
// Grab the step later
let step = sessionStorage.getItem("currentWizardStep");
// Clear EVERYTHING in the current session
sessionStorage.clear();
</script>
To really understand the power of Web Storage, try the counter below. Click it a few times, then reload the entire webpage. Because we are using localStorage, your clicks will be remembered perfectly even after the page refreshes!
localStorage and sessionStorage can only save data as text strings. If you want to save a complex JavaScript array or object (like a full shopping cart list), you must use JSON.stringify() before saving it, and JSON.parse() when you pull it back out!