πŸ—„️ LocalStorage and SessionStorage in JavaScript: Complete Guide

  


Today, for any modern website, managing client-side data efficiently is essential. JavaScript provides two powerful tools for this purpose: LocalStorage and SessionStorage. Both allow you to save information in the user's browser, but with different features and purposes.

πŸ”— Do you like Techelopment? Check out the site for all the details!

πŸ“š What is the Web Storage API?

The Web Storage API is a W3C specification that provides a simple mechanism to store key/value pairs in the browser. This API includes:

  • πŸ—ƒ️ localStorage → stores data permanently
  • 🧭 sessionStorage → stores data temporarily, for a single session

Both are more efficient and easier to use than cookies, and are not automatically sent to the server in every HTTP request, thus improving performance.


πŸ” Main differences between LocalStorage and SessionStorage

πŸ”§ Feature πŸ—ƒ️ local
Storage
🧭 session
Storage
⏳ Persistence Permanent (until removed) Temporary (as long as the tab is open)
πŸ“ Scope All tabs in the same domain Only in the current tab
πŸ“¦ Free space About 5–10 MB (depends on browser) About 5–10 MB (depends on browser)
🧩 Sharing Between windows/tabs of the same domain Not shared between tabs
πŸ› ️ Syntax/API Same for both Same for both

🧰 Available APIs

Both APIs use the same methods:

  • πŸ“ setItem(key, value) → saves a data item
  • πŸ”Ž getItem(key) → reads a given
  • removeItem(key) → delete a single piece of data
  • 🧹 clear() → delete all data

✅ Add data

localStorage.setItem('username', 'Alice');
sessionStorage.setItem('sessionId', 'abc123');

πŸ” Recover data

const name = localStorage.getItem('username');
const id = sessionStorage.getItem('sessionId');

❌ Delete data

localStorage.removeItem('username');
sessionStorage.removeItem('sessionId');

🧼 Clean everything

localStorage.clear();
sessionStorage.clear();

πŸ§ͺ Practical Examples of Use

πŸ—ƒ️ LocalStorage: saving user preferences

// Save user's theme preference
localStorage.setItem('theme', 'dark');keep data between logins

🧭 Use sessionStorage if:

  • πŸ” The data is sensitive and should disappear at the end of the session
  • πŸ§ͺ You have a multi-step form to complete in a single visit
  • πŸͺŸ You want to avoid interference between multiple open tabs
  • πŸ”„ You are handling temporary data such as a scroll state

⚠️ Important limitations

⛔ Do not save sensitive data

All data stored in LocalStorage or SessionStorage is accessible by JavaScript and not encrypted. Do not use them to store passwords, authentication tokens, personal or sensitive data.

πŸ”€ Strings only

Both APIs save only strings. To save complex objects, you should use JSON.stringify() and then JSON.parse() when retrieving them.

const user = { name: 'Alice', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// Later...
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log(savedUser.name); // Alice

πŸ“‰ Size limit

The amount of data you can save is limited (usually between 5MB and 10MB, depending on the browser). Exceeding the limit will throw an exception.


🧠 Best Practices

  • πŸ” Never save sensitive data. Use secure, encrypted cookies or server storage.
  • 🧹 Clean up unused data. Overloaded LocalStorage can slow down your application.
  • πŸ§ͺ Use try/catch. You may encounter errors if the user has their browser in private mode or has disabled storage.
  • try {
    localStorage.setItem('key', 'value');
    } catch (e) {
    console.warn('Storage failed:', e);
    }

🧭 Conclusion

LocalStorage and SessionStorage are simple but very powerful tools for client-side data storage. Knowing how to use them correctly can significantly improve the user experience, reduce server calls and speed up your application.

πŸ’‘ Golden rule: use localStorage for persistent data and sessionStorage for temporary data within a single session or browser tab.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
/>telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment 

// Load preference on next visit const savedTheme = localStorage.getItem('theme'); if (savedTheme) { document.body.classList.add(savedTheme); }

🧭 SessionStorage: temporary state during the session

// Save current step of a multi-step form
sessionStorage.setItem('formStep', '2');

// Restore step on reload (same tab only)
const step = sessionStorage.getItem('formStep');
if (step) { 
goToFormStep(parseInt(step, 10));
}

πŸ“‹ When to use LocalStorage or SessionStorage?

πŸ—ƒ️ Use localStorage if:

  • πŸ’Ύ You want long-term persistence, even after browser restarts
  • 🎨 You save user preferences (e.g. theme, language)
  • πŸ”„ You store data to be used across multiple sessions
  • πŸ”Œ You have an offline web app that needskeep data between logins

🧭 Use sessionStorage if:

  • πŸ” The data is sensitive and should disappear at the end of the session
  • πŸ§ͺ You have a multi-step form to complete in a single visit
  • πŸͺŸ You want to avoid interference between multiple open tabs
  • πŸ”„ You are handling temporary data such as a scroll state

⚠️ Important limitations

⛔ Do not save sensitive data

All data stored in LocalStorage or SessionStorage is accessible by JavaScript and not encrypted. Do not use them to store passwords, authentication tokens, personal or sensitive data.

πŸ”€ Strings only

Both APIs save only strings. To save complex objects, you should use JSON.stringify() and then JSON.parse() when retrieving them.

const user = { name: 'Alice', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// Later...
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log(savedUser.name); // Alice

πŸ“‰ Size limit

The amount of data you can save is limited (usually between 5MB and 10MB, depending on the browser). Exceeding the limit will throw an exception.


🧠 Best Practices

  • πŸ” Never save sensitive data. Use secure, encrypted cookies or server storage.
  • 🧹 Clean up unused data. Overloaded LocalStorage can slow down your application.
  • πŸ§ͺ Use try/catch. You may encounter errors if the user has their browser in private mode or has disabled storage.
  • try {
    localStorage.setItem('key', 'value');
    } catch (e) {
    console.warn('Storage failed:', e);
    }

🧭 Conclusion

LocalStorage and SessionStorage are simple but very powerful tools for client-side data storage. Knowing how to use them correctly can significantly improve the user experience, reduce server calls and speed up your application.

πŸ’‘ Golden rule: use localStorage for persistent data and sessionStorage for temporary data within a single session or browser tab.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment