DEV Community

Cover image for LocalStorage vs SessionStorage vs Cookies — When to Use What?
Manu Kumar Pal
Manu Kumar Pal

Posted on

LocalStorage vs SessionStorage vs Cookies — When to Use What?

Modern web apps store a lot of data in the browser — user preferences, tokens, UI states, cart items, and even feature flags.

But which storage should you use?
👉 LocalStorage? SessionStorage? Cookies? Let’s break it down in a simple!

🗃️ 1. LocalStorage

✅ Persistent storage for long-term use

Property

⏳ Lifespan -> Until manually cleared (stays even after browser restart)
📦 Capacity -> ~5–10 MB
🔐 Sent to server? ❌ No
🌐 Accessible from JS? ✔️ Yes

👍 Best for:

✔️ Saving theme preferences (dark/light mode)

✔️ User settings that don’t need to expire

✔️ Caching small API responses

✔️ Store cart items for returning users

👎 Avoid for:

Sensitive info like JWT tokens (risk of XSS)

Anything requiring expiration control

💡 Example:

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
Enter fullscreen mode Exit fullscreen mode

🕒 2. SessionStorage

✅ Short-term storage tied to a single tab

Property

⏳ Lifespan -> Until the tab is closed
📦 Capacity -> ~5 MB
🔐 Sent to server? ❌ No
🌐 Accessible from JS? ✔️ Yes

👍 Best for:

✔️ Multi-step forms (wizard forms)

✔️ Temporary UI state

✔️ Session-based data that should not persist

👎 Avoid for:

Anything you want users to keep after closing the browser

Sharing data across tabs

💡 Example:

sessionStorage.setItem("step", "2");
Enter fullscreen mode Exit fullscreen mode

🍪 3. Cookies

✅ Small pieces of data stored by the browser and optionally sent to the server

Property

⏳ Lifespan -> Configurable (expires in X days/minutes)
📦 Capacity -> ~4 KB (very small)
🔐 Sent to server? ✔️ Yes (unless HttpOnly is used)
🌐 Accessible from JS? Optional (depends on HttpOnly flag)

👍 Best for:

✔️ Authentication sessions

✔️ Storing secure tokens with HttpOnly + Secure + SameSite

✔️ Remember-me functionality

👎 Avoid for:

Storing large data

Anything that doesn’t need to be sent to the server

💡 Example:

document.cookie = "user=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
Enter fullscreen mode Exit fullscreen mode

🧭 When to Use What?

✅ Use LocalStorage when:

You want data to persist long term

Data is non-sensitive

You don’t need the server to read it

Example: theme settings, UI preferences, cart items

✅ Use SessionStorage when:

Data should reset on tab close

You need temporary state

It’s fine the server never sees it

Example: multi-step form progress

✅ Use Cookies when:

The server needs the data

You need secure auth

You need expiration control

Example: JWT tokens stored as HttpOnly cookies

🎉 Final Thoughts

Understanding browser storage makes your app safer, faster, and more reliable.

Top comments (0)