Back to all posts

Local storage


Local storage, also knows as web storage, is a feature provided by modern web browsers that allows web applications to store data locally on the user’s device. It provide a way to store persistent data that can be accessed and that can be accessed and retrieved even after the user closes the browser or navigate away from the website. Unlike cookies, local storage has a larger storage capacity and does not send data to the server with every request.

Local storage uses a key-value pair model, where data is stored as strings with associated keys.

Let’s consider an example to illustrate how to local storage works:

// Storing data in local storage
localStorage.setItem('username', 'John');
localStorage.setItem('email', 'john@example.com');

// Retrieving data from local storage
const username = localStorage.getItem('username');
const email = localStorage.getItem('email');

console.log(username); // Output: John
console.log(email); // Output: john@example.com

The stored data remains accessible even if the user closes the browser or visits the website again at a later time. To remove an item from the local storage, you can use the removeItem() method:

// Removing data from local storage
localStorage.removeItem('email');

In this case, the ’email’ key and its associated value will be removed from the local storage.

It’s important to note that the data stored in local storage is specific to the domain and protocol (HTTP or HTTPS) of the website that sets it. Different websites will have their own separate local storage.

Local storage provides a convenient way to store and retrieve user-specific data, preferences, or other relevant information on the client-side, enhancing the user experience and enabling offline functionality in web applications.