JavaScript Storage & Cookies
HTTP is stateless. That means every time you load a page, the browser starts fresh. To remember user preferences, sessions, or cart items, we need persistent memory in the client's browser.
localStorage
The localStorage object allows you to save key/value pairs in the browser. The data saved in localStorage has no expiration date, meaning it survives browser restarts. You get roughly 5MB of space.
// Save data
localStorage.setItem("theme", "dark");
// Read data
let theme = localStorage.getItem("theme");sessionStorage
sessionStorage uses the exact same API as localStorage, but data is only persisted until the window or tab is closed. It's perfect for multi-page forms or state that you only need during the current session.
Cookies
Cookies are older, smaller (4KB max), but very powerful because they are automatically sent to the server with every HTTP request. This makes them the standard for handling authentication sessions. Setting them in JavaScript is done via the document.cookie string.
Security Warning: XSS+
Never store highly sensitive information (like passwords) in localStorage. Any JavaScript running on your page (even malicious code injected via Cross-Site Scripting - XSS) can access localStorage. For auth tokens, HttpOnly cookies are much safer as they are invisible to JS.
