Module 7: DOM and Browser APIs
localStorage, sessionStorage, and Cookies
Persist simple browser-side data and understand storage limitations.
localStorage stores string key-value pairs across browser sessions for the same origin. sessionStorage generally lasts for the lifetime of a browser tab session. Both are synchronous APIs and should be used for modest amounts of data, not large datasets.
const settings = { theme: "dark", fontSize: 16 };
localStorage.setItem("settings", JSON.stringify(settings));
const stored = localStorage.getItem("settings");
const restored = stored ? JSON.parse(stored) : null;
console.log(restored?.theme);
Storage operations and JSON parsing can fail, so production code should handle errors. Stored values can be absent, outdated, malformed, or modified by the user. Validate the data before relying on it.
Security and privacy#
Do not store passwords, session identifiers, access tokens, or other sensitive secrets in local storage. JavaScript running on the same origin can often read it, so a cross-site scripting vulnerability can expose the contents. Use appropriate server-managed session approaches for authentication.
Cookies differ because they can be sent with requests to a server and can carry attributes such as HttpOnly, Secure, and SameSite. JavaScript cannot read an HttpOnly cookie, which is useful for session protection. Cookie and session architecture needs server-side consideration.
Practice#
Persist a theme preference and restore it when the page loads. Handle the case where saved JSON is invalid, and include a reset action that removes the setting.