How to Use localStorage in JavaScript
Saving data in the browser so it's still there after a refresh.
You may want something to stick around after the user refreshes the page, like a
dark mode setting or the items in a cart. You don't need a database for that.
The browser has localStorage built in. Think of it as a local database for the
user's browser.
localStorage stores key/value pairs in the browser with no expiration date.
Saving and Reading a Value
Save a value with setItem and read it back with getItem:
localStorage.setItem("theme", "dark")localStorage.getItem("theme") // "dark"localStorage.getItem("language") // null
getItem returns null when nothing is saved under that key.
Removing Values
Remove one key with removeItem, or everything for your site with clear:
localStorage.removeItem("theme")localStorage.clear()
Storing Objects and Arrays
Note: localStorage only stores strings.
If you save an object directly, it gets turned into a not so useful string:
localStorage.setItem("user", { name: "Jim" })localStorage.getItem("user") // "[object Object]"
Turn it into JSON with JSON.stringify when saving, and back into an object
with JSON.parse when reading:
const user = { name: "Jim", theme: "dark" }localStorage.setItem("user", JSON.stringify(user))const savedUser = JSON.parse(localStorage.getItem("user"))savedUser.name // "Jim"
The same goes for numbers and booleans. Save 5 and you'll get back "5", so
use JSON.parse or Number on the way out.
A Practical Example
Here's a theme toggle that remembers your choice:
const button = document.querySelector("#theme-toggle")document.body.className = localStorage.getItem("theme") || "light"button.addEventListener("click", () => {const nextTheme = document.body.className === "dark" ? "light" : "dark"document.body.className = nextThemelocalStorage.setItem("theme", nextTheme)})
On page load it applies the saved theme, or "light" if there isn't one. Each
click flips the theme and saves it.
Things to Keep in Mind
- Data is saved per site, so one site can't read another site's storage.
- Most browsers give you around 5MB.
- Any JavaScript on the page can read it, so keep passwords and tokens out of it.
sessionStoragehas the exact same methods, but it's cleared when the tab is closed.
For small settings and preferences, localStorage is about as easy as it gets.
Have some feedback on this post? .