Skip to main content

Command Palette

Search for a command to run...

Web Storage in JavaScript – localStorage & sessionStorage

Updated
5 min readView as Markdown

Yesterday, I learned how JavaScript handles forms, user input, and validation.

Today, I explored Web Storage, which allows websites to store data inside the user's browser.

Until now, whenever a webpage was refreshed, most of the data stored in JavaScript variables disappeared.

Web Storage gives us a way to persist certain data on the client side.

Let's dive in.


What is Web Storage?

Web Storage is a browser feature that allows JavaScript applications to store key-value data locally.

The two main Web Storage APIs are:

  • localStorage

  • sessionStorage

Both use a simple key-value structure.


What is localStorage?

localStorage allows us to store data in the browser that remains available even after:

  • Refreshing the page

  • Closing the browser

  • Opening the website again later

Example:

localStorage.setItem("username", "Saurabh");

Now the browser stores:

username → Saurabh

Getting Data From localStorage

We can retrieve stored data using getItem().

const username = localStorage.getItem("username");

console.log(username);

Output:

Saurabh

Updating Data

If we use the same key again, its value gets replaced.

localStorage.setItem("username", "Rahul");

Now:

console.log(localStorage.getItem("username"));

Output:

Rahul

Removing Data

We can remove a specific item using removeItem().

localStorage.removeItem("username");

Now the username value no longer exists.


Clearing localStorage

We can remove everything stored by the current origin using:

localStorage.clear();

This should be used carefully because it removes all localStorage entries for that origin.


Checking Whether Data Exists

getItem() returns null when the requested key doesn't exist.

const username = localStorage.getItem("username");

if (username) {
    console.log(`Welcome back, ${username}`);
} else {
    console.log("No username found.");
}

This is useful when creating persistent user preferences.


localStorage Stores Strings

One important thing I learned today is that Web Storage stores values as strings.

For example:

localStorage.setItem("age", 22);

console.log(localStorage.getItem("age"));

The retrieved value is a string:

"22"

This becomes important when storing arrays or objects.


Storing Objects

We can't directly store a JavaScript object as an object in localStorage.

For example:

const user = {
    name: "Saurabh",
    age: 22
};

localStorage.setItem("user", user);

This does not store the object correctly.

Instead, we use JSON.stringify().


JSON.stringify()

JSON.stringify() converts a JavaScript value into a JSON string.

const user = {
    name: "Saurabh",
    age: 22
};

localStorage.setItem("user", JSON.stringify(user));

Now the object can be stored as a string.


JSON.parse()

When retrieving the object, we need to convert the JSON string back into a JavaScript object.

const storedUser = localStorage.getItem("user");

const user = JSON.parse(storedUser);

console.log(user.name);

Output:

Saurabh

The basic process is:

JavaScript Object
      ↓
JSON.stringify()
      ↓
String
      ↓
localStorage
      ↓
JSON.parse()
      ↓
JavaScript Object

Storing Arrays

The same technique works with arrays.

const skills = ["HTML", "CSS", "JavaScript"];

localStorage.setItem("skills", JSON.stringify(skills));

Retrieve them:

const storedSkills = JSON.parse(
    localStorage.getItem("skills")
);

console.log(storedSkills);

Output:

["HTML", "CSS", "JavaScript"]

What is sessionStorage?

sessionStorage works similarly to localStorage, but its lifetime is different.

sessionStorage.setItem("theme", "dark");

The data remains available while the current browser tab/session remains open.

When that page session ends, the stored data is cleared.


localStorage vs sessionStorage

localStorage sessionStorage
Persists after browser restart Usually cleared when the page session ends
Data remains until removed Data is temporary
Useful for preferences Useful for temporary session data
localStorage.setItem() sessionStorage.setItem()

Both APIs use similar methods.


Common Web Storage Methods

Method Purpose
setItem() Store data
getItem() Retrieve data
removeItem() Remove specific data
clear() Remove all data

Example:

localStorage.setItem("theme", "dark");

localStorage.getItem("theme");

localStorage.removeItem("theme");

localStorage.clear();

Practical Example: Remembering Dark Mode

Suppose a user selects dark mode.

We can store that preference:

localStorage.setItem("theme", "dark");

When the page loads, we can check the stored preference:

const theme = localStorage.getItem("theme");

if (theme === "dark") {
    document.body.classList.add("dark");
}

Now the website can remember the user's preference after a refresh.

This is a simple example of how persistent browser storage can be used in real applications.


Important Security Consideration

localStorage is useful, but it should not be treated as a secure storage mechanism.

Do not store sensitive information such as:

  • Passwords

  • Authentication secrets

  • Highly sensitive personal information

JavaScript running on the page can access localStorage, so an XSS vulnerability could potentially expose stored data.


Best Practices

✔ Store only the data your application actually needs.

✔ Use JSON.stringify() for objects and arrays.

✔ Use JSON.parse() when retrieving stored JSON data.

✔ Don't store passwords or sensitive secrets in localStorage.

✔ Use meaningful storage keys.

✔ Handle missing or invalid stored data safely.


My Biggest Takeaway

Today, I learned how websites can remember information on the client side using Web Storage.

localStorage allows data to persist across browser sessions, while sessionStorage is designed for temporary data within a browser session.

I also learned an important connection between JavaScript objects, JSON, and browser storage:

Object → JSON.stringify() → Storage → JSON.parse() → Object

This is a concept I'll encounter frequently when building real-world frontend applications.

100 Days of Code: My Journey to Becoming a Full Stack Developer

Part 43 of 50

Welcome to my 100 Days of Code journey! In this series, I'll document my daily progress as I learn Full Stack Web Development from the ground up. Every post will cover what I learned, challenges I faced, mistakes I made, and the projects I built. My goal is not just to complete 100 days but to become a better developer through consistency, discipline, and learning in public. Topics I'll cover include: • Git & GitHub • HTML, CSS & JavaScript • React.js • Node.js & Express • MongoDB • APIs • Real-world Projects • AI tools for Developers Whether you're just starting out or revising your fundamentals, I hope this journey helps you learn alongside me. Let's build, learn, and grow together! 🚀

Up next

JSON in JavaScript – Working With Structured Data

Yesterday, I learned about localStorage, sessionStorage, and how JSON.stringify() and JSON.parse() allow us to store JavaScript objects and arrays. Today, I explored JSON (JavaScript Object Notation)

More from this blog

T

TheSaurceCode

73 posts

Documenting my journey to becoming a Full Stack Developer through daily blogs, coding challenges, projects, tutorials, and lessons learned. Learn, build, and grow with me