EN ES
Home > Web development > Javascript Tutorials > How to Use localStorage and sessionStorage in JavaScript to Store Data

How to Use localStorage and sessionStorage in JavaScript to Store Data

Diego Cortés
Diego Cortés
September 27, 2024
How to Use localStorage and sessionStorage in JavaScript to Store Data

Web storage in JavaScript provides two very useful methods: localStorage and sessionStorage. Both allow developers to store data in the client's browser, which can be helpful for enhancing user experience and functionality in web applications. In this article, we will explore how localStorage and sessionStorage work, their differences, and how to use them effectively.

What is localStorage?

localStorage is a feature of the Web Storage API that allows data to be stored in the user's browser persistently. Data stored in localStorage does not have an expiration date and remains available even after closing the browser.

Features of localStorage

  • Persistent: Data is saved indefinitely unless explicitly deleted.
  • Capacity: Most browsers allow at least 5 MB of data to be stored.
  • Accessibility: Stored data can be accessed from any tab or window of the same origin.

What is sessionStorage?

sessionStorage, on the other hand, is also part of the Web Storage API, but the data stored in it has a scope limited to the browser session. This means that data will only be available while the browser tab or window is open.

Features of sessionStorage

  • Temporary: Data is only retained during the current browser session.
  • Scope: Unlike localStorage, data is not accessible from different tabs or windows, even if the origin is the same.
  • Capacity: It also allows for at least 5 MB of data to be stored in most browsers.

Key Differences Between localStorage and sessionStorage

Both types of storage may seem similar, but their differences are crucial for deciding which to use based on the application's needs:


Feature localStorage sessionStorage
| Persistence  | Data persists indefinitely  | Only persists for the session
| Accessibility  | Available in multiple tabs  | Only available in the current tab
| Capacity  | Generally 5-10 MB  | Generally 5-10 MB

How to Use localStorage

Storing Data in localStorage

To store data in localStorage, we use the setItem() method. This method requires two arguments: a key and a value.

localStorage.setItem('name', 'John');
localStorage.setItem('age', '30');

Retrieving Data from localStorage

To retrieve data, we use the getItem() method, providing the corresponding key.

const name = localStorage.getItem('name');
const age = localStorage.getItem('age');

console.log(name); // John
console.log(age);   // 30

Removing Data from localStorage

If you want to remove a specific item, use the removeItem() method.

localStorage.removeItem('age');

Clearing All Data in localStorage

To remove all data stored in localStorage, use the clear() method.

localStorage.clear();

How to Use sessionStorage

Storing Data in sessionStorage

Similar to localStorage, you can store data in sessionStorage using setItem().

sessionStorage.setItem('sessionID', '12345ABC');
sessionStorage.setItem('user', 'admin');

Retrieving Data from sessionStorage

To retrieve data, we use getItem() in the same way as with localStorage.

const sessionID = sessionStorage.getItem('sessionID');
const user = sessionStorage.getItem('user');

console.log(sessionID);  // 12345ABC
console.log(user);       // admin

Removing Data from sessionStorage

To remove a specific item, use removeItem():

sessionStorage.removeItem('user');

Clearing All Data in sessionStorage

Just like with localStorage, you can clear all data from sessionStorage using clear():

sessionStorage.clear();

Practical Example of Usage

Let's imagine we want to store user preferences in our application. We can use localStorage to save these preferences in such a way that they persist even if the user closes the browser.

function savePreferences(preferences) {
    localStorage.setItem('userPreferences', JSON.stringify(preferences));
}

function getPreferences() {
    const preferences = localStorage.getItem('userPreferences');
    return preferences ? JSON.parse(preferences) : null;
}

// Usage
const preferences = {
    theme: 'dark',
    notifications: true
};

savePreferences(preferences);
console.log(getPreferences()); // { theme: 'dark', notifications: true }

On the other hand, we can use sessionStorage to store temporary information about the state of a form that we don’t want to persist once the tab is closed.

function saveForm(data) {
    sessionStorage.setItem('formData', JSON.stringify(data));
}

function getForm() {
    const data = sessionStorage.getItem('formData');
    return data ? JSON.parse(data) : null;
}

// Usage
const formData = {
    name: 'Ana',
    email: '[email protected]'
};

saveForm(formData);
console.log(getForm()); // { name: 'Ana', email: '[email protected]' }

Security Considerations

Although localStorage and sessionStorage are useful tools, they should be used with caution. Here are some important considerations:

  • Do not store sensitive information: Never store passwords, banking information, or sensitive data in browser storage.
  • Vulnerability to XSS attacks: Data in localStorage and sessionStorage is vulnerable to cross-site scripting (XSS) attacks. Be sure to validate and sanitize user inputs.
  • Compatibility: Although most modern browsers support localStorage and sessionStorage, it is always a good idea to check for compatibility.

Conclusion

localStorage and sessionStorage are powerful tools for storing data in the browser using JavaScript. Each has its own features and should be chosen based on the specific needs of your application. By learning to implement them correctly, you can improve user experience and optimize the performance of your web applications. Always remember to consider security when storing sensitive data and validate user input information.

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 49.20 ms