The Insider Guide to Cookies, LocalStorage, and SessionStorage in JavaScript

Peter BamigboyePeter Bamigboye
4 min read

Modern web applications often need to store data directly in the browser, from user preferences to authentication tokens. JavaScript provides three main ways to do this on the client side:

  • Cookies

  • LocalStorage

  • SessionStorage

While they all serve the purpose of storing data, each one behaves differently and is suited to different use cases. In this article, we'll walk through what they are, how they work, and provide clear examples for using each.

1. Cookies

What are Cookies?

Cookies are small pieces of data (up to ~4KB) that a server or client can store in the user's browser. They are typically used for session management, authentication, and tracking.

They are sent with every HTTP request to the server, which makes them useful for things like login sessions but not ideal for storing large or frequent data.

Example: Setting and Getting Cookies

// Set a cookie
document.cookie = "username=Peter; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";

// Read all cookies
console.log(document.cookie); // "username=Peter"

When to Use Cookies

  • Maintaining user sessions (e.g., keeping a user logged in)

  • Passing small amounts of data back to the server on every request

  • Setting values that need to persist across different tabs or windows

2. LocalStorage

What is LocalStorage?

LocalStorage provides a way to store key-value pairs in the browser with no expiration date. It can store up to about 5MB, depending on the browser.

The data stored in LocalStorage is accessible only by JavaScript on the same origin and persists even when the browser is closed and reopened.

Example: Using LocalStorage

// Save data
localStorage.setItem("theme", "dark");

// Get data
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"

// Remove data
localStorage.removeItem("theme");

// Clear all local storage
localStorage.clear();

When to Use LocalStorage

  • Storing user preferences (like theme or layout settings)

  • Keeping data that should persist between visits

  • Caching non-sensitive data for performance

LocalStorage Caveats

  • Synchronous API : It can block the main thread on large operations.

  • No automatic expiration : You need to manage stale data manually.

  • Not secure for sensitive data : All JavaScript on the same origin can read/write to it.

3. SessionStorage

What is SessionStorage?

SessionStorage is very similar to LocalStorage but with one key difference: the data is only available for the duration of the page session, as long as the tab is open.

Once the tab or browser window is closed, the data is lost.

Example: Using SessionStorage

// Save data
sessionStorage.setItem("isLoggedIn", "true");

// Get data
console.log(sessionStorage.getItem("isLoggedIn")); // "true"

// Remove data
sessionStorage.removeItem("isLoggedIn");

// Clear all session storage
sessionStorage.clear();

When to Use SessionStorage

  • Temporary data that shouldn’t persist after the user leaves the page (e.g., form progress)

  • Tracking a session state (like whether a modal has been shown)

  • One-time user flow storage (like multi-step forms)

Comparison Table

FeatureCookiesLocalStorageSessionStorage
Size Limit~4KB~5MB~5MB
ExpirationManual or with expiresStays until manually clearedClears when tab closes
Automatically Sent to Server✅ Yes❌ No❌ No
Accessible in JS✅ Yes✅ Yes✅ Yes
Use CasesAuth, session trackingPreferences, cachingOne-time session data

Real-World Use Cases

Here are examples of how these can be used in real applications:

Cookies Example: Keep a user logged in

// After login
document.cookie = "token=abc123; path=/; expires=Fri, 31 Dec 2025 23:59:59 GMT;";

This token will be sent automatically on every request, enabling session management on the server.

LocalStorage Example: Theme Preference

// Save user's theme choice
localStorage.setItem("theme", "dark");

// On page load
const userTheme = localStorage.getItem("theme");
if (userTheme === "dark") {
  document.body.classList.add("dark-theme");
}

SessionStorage Example: Multi-step Form

// Step 1 of a form
sessionStorage.setItem("step1Data", JSON.stringify({ name: "Jane", age: 25 }));

// Retrieve on Step 2
const step1 = JSON.parse(sessionStorage.getItem("step1Data"));
console.log(step1.name); // "Jane"

Best Practices

  • Never store sensitive data like passwords or access tokens in LocalStorage or SessionStorage.

  • For authentication, use cookies (especially HttpOnly cookies) and server-side sessions.

  • Use LocalStorage/SessionStorage for client-side convenience (not security).

  • Always validate and sanitize data from any storage before using it.

Conclusion

Cookies, LocalStorage, and SessionStorage each have their strengths and ideal use cases. Knowing the differences will help you design better, more efficient, and more secure web applications.

Whether you're saving a dark theme preference, managing a login session, or temporarily storing form data, choosing the right tool makes your application faster and easier to maintain.

4
Subscribe to my newsletter

Read articles from Peter Bamigboye directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Peter Bamigboye
Peter Bamigboye

I am Peter, a front-end web developer who writes on current technologies that I'm learning or technologies that I feel the need to simplify.