Web Storage API - Local and Session Storage
An introduction to web storage API and how to use them
Table of contents
Web Storage API
Web storage API is the mechanism that allows data to be stored inside a web browser. It enables web developers to store and retrieve data without the need for a server. Web storage is like a very big object of key-value pairs of strings. It also allows for faster data retrieval since the data is stored locally and doesn't need to be fetched from a server.
However, it's important to note that data stored in it is not encrypted, so sensitive data should not be stored in it. In this blog, we will be looking into two types of web storage provided by the browser - local storage and session storage. Web storage, both local and session, is synchronous, therefore it can cause performance issues if the amount of data being stored or retrieved is large, as it can block the UI and make the web page unresponsive.
Local Storage
Local storage stores data in key-value pairs. It can only store primitive data types such as - boolean, string, number, undefined, null, etc as the value. The data stored in local storage is persisted until it is manually deleted. Local storage is often used for caching data. It can be used to store data such as theme settings or language preferences. The size of local storage is limited to about 5MB.
We cannot store objects or arrays as a value in local storage, so to tackle this problem we use the stringify method provided by JSON. It converts whatever is passed into it into a string format.
To retrieve the object/array after it is converted into a string we use the parse method provided by JSON.
Let's look at some code for better understanding.
Saving data in local storage
// Saving a number in local storage
localStorage.setItem('number', 1);
// Saving a string in local storage
localStorage.setItem('string', 'Hello, world!');
// Saving an array in local storage
const stringiFiedArray = JSON.stringify([1, 2, 3]);
localStorage.setItem('array', stringiFiedArray);
// Saving an object in local storage
const stringiFiedObject = JSON.stringify({ name: 'John', age: 30 });
localStorage.setItem('object', stringiFiedObject);
Retrieving data from local storage
// Retrieving a number from local storage
const number = localStorage.getItem('number');
console.log(number); // 1
// Retrieving a string from local storage
const string = localStorage.getItem('string');
console.log(string); // Hello, world!
// Retrieving an array from local storage
const array = JSON.parse(localStorage.getItem('array'));
console.log(array); // [1, 2, 3]
// Retrieving an object from local storage
const object = JSON.parse(localStorage.getItem('object'));
console.log(object); // { name: 'John', age: 30 }
Removing an item from local storage
// Removing an item from local storage
localStorage.removeItem('number'); //this will remove the item with key number
Removing all items from local storage
// Clearing all items from local storage
localStorage.clear(); //this will clear all items stored in local storage
Session Storage
Session storage allows data to be stored in the browser temporarily. The data is persisted until the tab or the window is not closed. As soon as the tab is closed the session is terminated and all the data stored in session storage is deleted automatically. Like local storage, session storage uses key-value pairs to store data, and the data can be in various formats such as strings, numbers, booleans, or JSON objects.
Session storage is a useful tool for web developers looking to store temporary data that is only needed for a single-user session.
Code for setting and getting data from session storage -
Saving data in session storage
// Saving a number in session storage
sessionStorage.setItem('number', 1);
// Saving a string in session storage
sessionStorage.setItem('string', 'Hello World');
// Saving an array in session storage
const stringifiedArray = JSON.stringify(['Hello', 'World']);
sessionStorage.setItem('array', stringifiedArray);
// Saving an object in session storage
const stringifiedObject = JSON.stringify({ name: 'John', age: 30 });
sessionStorage.setItem('object', stringifiedObject);
Retrieving data from session storage
// Retrieveing a number from session storage
const number = sessionStorage.getItem('number');
console.log(number); // 1
// Retrieveing a string from session storage
const string = sessionStorage.getItem('string');
console.log(string); // Hello World
// Retrieveing an array from session storage
const array = JSON.parse(sessionStorage.getItem('array'));
console.log(array); // ['Hello', 'World']
// Retrieveing an object from session storage
console.log(JSON.parse(sessionStorage.getItem('object'))); // { name: 'John', age: 30 }
Removing an item from session storage
// Remove an item from session storage
sessionStorage.removeItem('string');
Removing all items from session storage
// Remove all items from sessionStorage
sessionStorage.clear();
Same-Origin Policy
The web storage API follows the same-origin policy due to security reasons. The same origin means the same domain. For example- if you have a website mywebsite.com and you store some data in the local storage or session storage then you can only access the data on this website only. The data is not accessible from different websites. It means that you cannot access the local storage of mywebsite.com from yourwebsite.com
Thank you for reading ❤️