33. Web Storage API (LocalStorage vs SessionStorage)
Keeping data in the browser permanently
Real-life analogy
Web Storage is the browser's own small digital safe in which your name and login token stay locked, even if you close the browser and open it again!
Explanation
Storage that is many times faster and safer than Cookies:
- LocalStorage: Data kept in it is never deleted unless the user clears the browser history themselves.
- SessionStorage: Data kept in it lasts only as long as that particular tab is open. The data is gone as soon as the tab is closed.
- Syntax:
localStorage.setItem("key", "value")andlocalStorage.getItem("key").
Golden rules
- Only string (Text) data can be stored safely in local storage.
Common mistake
Saving a user's password in local storage (this is insecure).
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<div style="border: 1px solid #cbd5e1; padding: 12px; border-radius: 6px; background: #f8fafc;">
<h4 style="margin: 0 0 6px 0; color: #0284c7;">The Magic of Local Storage:</h4>
<input type="text" id="userInput" placeholder="Enter your name..." style="padding: 4px; border: 1px solid #cbd5e1; border-radius: 4px; font-size: 12px;">
<button onclick="save()" style="background: #0284c7; color: white; border: none; padding: 5px 10px; border-radius: 4px; font-size: 12px; cursor: pointer;">Save</button>
<p id="msg" style="margin: 6px 0 0 0; font-size: 12px; font-weight: bold; color: #059669;"></p>
</div>
<script>
function save() {
const v = document.getElementById('userInput').value;
localStorage.setItem('myDemoName', v);
load();
}
function load() {
const s = localStorage.getItem('myDemoName');
if (s) document.getElementById('msg').innerText = "Saved name: " + s;
}
load();
</script>
</body>
</html>
Quick quiz
Which API stores data in the browser permanently, without expiry?
- SessionStorage
- LocalStorage
- CookieStorage
- DataSaver
Show answer
Answer: LocalStorage
Data kept in LocalStorage stays safe even after the browser is closed.