DEV Community

Cover image for LocalStorage vs SessionStorage vs Cookies: A Complete Guide πŸ—„οΈ
Anthony Max Subscriber for HMPL.js

Posted on

LocalStorage vs SessionStorage vs Cookies: A Complete Guide πŸ—„οΈ

When we talk about such a topic as data storage, we immediately remember these 3 concepts. But here's the problem, we often use them unconsciously.

We are used to storing tokens in sessionStorage, but not everyone can answer why exactly. Other concepts follow the same scenario. All these issues have long been decided for us by the modules that we use, and this is sad, because you need to know about this, even if you do not understand websites at all.

In this article, I tried to prepare for you the ultimate guide so that you do not have any misunderstandings about what is used and for what.

Well, let's get started!


πŸ—„οΈ LocalStorage

Before we start with LocalStorage, it's worth taking a short detour and talking about what storage is.

Simply put, storage is a dedicated place where the browser stores information. In JavaScript, such storages are represented as objects available via the window object’s properties with reserved names, or through dedicated variables.

Now, let's go back. There is a LocalStorage storage, which we access through the localStorage object. In this object itself, what is important now, the data is stored even when we close the tab or the browser itself. Suitable for large amounts of data.

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

// Retrieve a value
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"

// Remove a value
localStorage.removeItem("theme");

// Clear all storage
localStorage.clear();
Enter fullscreen mode Exit fullscreen mode

It's a good place to store long-lived data, such as settings, cached data, etc.


πŸ•“ SessionStorage

SessionStorage is similar to LocalStorage; the difference is that while localStorage is partitioned by origin only, sessionStorage is partitioned by both origin and browser tabs (top-level browsing contexts). The data in sessionStorage is only kept for the duration of the page session. Suitable for large amounts of data.

That is, if you close a tab in your browser, all your data in this storage will be cleared.

// Save a value
sessionStorage.setItem("authToken", "123456");

// Retrieve a value
const token = sessionStorage.getItem("authToken");
console.log(token); // "123456"

const templateFn = hmpl.compile(
  `<div>
    {{#request src="/api/my-component.html"}}
      {{#indicator trigger="pending"}}
        <p>Loading...</p>
      {{/indicator}}
    {{/request}}
  </div>`
);

const content = templateFn(() => ({
  body: JSON.stringify({ token })
})).response;

// Remove a value
sessionStorage.removeItem("authToken");

// Clear all storage
sessionStorage.clear();
Enter fullscreen mode Exit fullscreen mode

Suitable for temporary tokens, as well as for data that is needed within the framework of while you are sitting at the site, that is, session data.


πŸͺ Cookies

And now, probably the most popular storage, which is on everyone's lips with modern web application users, is cookies. The banner with them is constantly displayed, but many miss the point: "what are they for?" In fact, this is a small storage (in size later), which stores temporary data (that is, data that will be deleted after a certain period). Suitable for small amounts of data.

// Set a cookie
document.cookie = "username=John; path=/; max-age=3600"; // expires in 1 hour

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

// Update a cookie
document.cookie = "username=Mike; path=/; max-age=3600";

// Delete a cookie
document.cookie = "username=; path=/; max-age=0";
Enter fullscreen mode Exit fullscreen mode

This data is often used in all sorts of tracking on websites. How many people clicked, how someone moves the cursor, etc. Also, when working with authentication, this storage is often used.


βœ… Conclusion

In this article, we looked at LocalStorage, SessionStorage, and Cookies, which perform different tasks for storing data in the browser. Choosing the right storage method depends on the lifetime of the data, the volume limitation, and the need to access it from the server. The right choice will allow you to improve performance, security, and the quality of the user experience.


Thank you very much for reading this article ❀️!

P.S. Also, don't forget to help me and star HMPL!

🌱 Star HMPL

Top comments (6)

Collapse
 
anik_sikder_313 profile image
Anik Sikder • Edited

Great breakdown of a topic that so many developers (myself included at one point) tend to use without fully thinking it through. πŸ™Œ

I really appreciate how you framed the problem we often use tools like localStorage, sessionStorage, and cookies out of habit, or because a library defaults to it, not because we understand why. This article does a great job clarifying when and why to use each.

I especially liked how you emphasized:

  • localStorage for long-term, client-side data like user preferences
  • sessionStorage for temporary, tab-specific data like session tokens
  • cookies for small bits of data that need to travel with HTTP requests (especially for auth or tracking)

Simple examples + real context = super helpful. Bookmarking this as a reference guide. Thanks for sharing!

Collapse
 
anthonymax profile image
Anthony Max HMPL.js

Thanks!

Collapse
 
alexjohn_21 profile image
alexjohn_21

Interesting article!

Collapse
 
anthonymax profile image
Anthony Max HMPL.js

100%

Collapse
 
anthonymax profile image
Anthony Max HMPL.js

After a long time of posting the same thing, I decided to make a really useful article that will help you understand the storage in the browser

Some comments may only be visible to logged-in visitors. Sign in to view all comments.