JavaScript
Tutorial: save data in the browser with localStorage
Learn to use localStorage to remember user information between visits to your page.
If you reload your page and everything you did disappears, your app has goldfish memory. localStorage is the simplest fix so it remembers something, even if the user closes the browser.
Step 1: save a value
localStorage.setItem('name', 'Sofia');
localStorage.setItem(key, value) stores data in the user's own browser, on their own computer, no server required. It survives page reloads and even computer restarts.
Step 2: read the saved value
const name = localStorage.getItem('name');
console.log(name); // 'Sofia'
If the key doesn't exist, getItem returns null instead of throwing an error. It's always a good idea to check for that before using the value.
Step 3: save objects (not just text)
localStorage only stores strings, so for objects you need to convert them with JSON:
const user = { name: 'Sofia', level: 'beginner' };
localStorage.setItem('user', JSON.stringify(user));
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log(savedUser.level); // 'beginner'
JSON.stringify turns an object into text so it can be stored. JSON.parse does the opposite: turns that text back into a usable object. Without this, JavaScript will hand you the string "[object Object]", which is useless for absolutely everything.
Step 4: remove saved data
localStorage.removeItem('user'); // deletes just that key
localStorage.clear(); // deletes EVERYTHING saved (careful)
What did you just learn?
- How to save and read data with
setItemandgetItem. - Why you need
JSON.stringify/JSON.parseto store objects. - How to remove saved data without regretting it later.