How to use Web Storage API?
Jatin Sharma
Posted on November 19, 2021
In this article, we are going to look at the different types of web storage such as Local Storage, Session Storage, and Cookies to be more precise. Storing data in the browser is a fairly simple task, but there are three different ways to do it and it can be difficult to know which storage option is best for your particular use case. I will be covering all three of the different ways to store data in a user’s browser so you can choose the exact option that works best for you.
Table of Contents
- What is Web Storage?
- What Are Cookies, Local Storage, And Session Storage Used For?
- Comparison
- Local Storage
- Session Storage
- Cookies
- Conclusion
What is Web Storage?
The Web Storage is one of the great features of HTML5. With the Web Storage feature, web applications can locally store data within the browser on the client side. It stores data in the form of key/value pair on the browser. Web Storage sometimes also known as DOM storage.
What Are Cookies, Local Storage, And Session Storage Used For?
Before I dive into the many differences between the various storage options I first need to talk about what they are used for. All three methods of storage are used to store information on the user’s browser which can be accessed even after navigating to new pages on your site. This data is also saved to the user’s exact browser they are using so if they have your site open in Chrome it will only save the information to their Chrome browser on the device they are currently on. This means if they open your site later in a different browser the data will no longer be there. Now let’s jump into the many differences between each option.
Comparison
Storage | Limit | Data-type Supported | Expiration |
---|---|---|---|
Local Storage | 5MB per app per browser | String only, as key-value pairs | Never |
Session Storage | Limited only by system memory | String only, as key-value pairs | After Tab Closed |
Cookies | at least 4096 bytes per cookie | text file (not sure) | It has Expiration Date (manually) |
Local Storage
Local storage is a form of web storage that stores data for a long time. This could be a day, a week, or even a year . This depends upon the developer’s preference. It is important to note that local storage only stores strings so, if you wish to store objects, lists, or arrays, you must convert them into a string using JSON.stringify()
.
Storing Data
In order to set data using local storage you simple use the setItem
This function takes two string parameters. The first parameter is the name and the second parameter is the value to associate with that name. You can think of this very similar to a key value pair in a JSON object.
localStorage.setItem("day", "monday");
Just like that, you can store the key/value pair in this. You can not only store this strings. you can store the Javascript array or object as strings, let's see how -
// Storing Object
const usesInfo = {
name: "John",
age: 34,
};
localStorage.setItem("user-info", JSON.stringify(userInfo));
// Storing Array
const languages = ["Python", "React", "Javascript", "Go"];
localStorage.setItem("languages", JSON.stringify(languages));
The
JSON.stringify()
method converts a JavaScript object or value to a JSON string,
Read Data
In order to get data from local storage it is as easy as calling the getItem
method. This method takes a single parameter which is the name of the key value pair and will return the value.
We are reading the data which we just add in the previous section
// Reading String
const name = localStorage.getItem("name");
// Reading Object
const userInfo = JSON.parse(localStorage.getItem("user-info"));
// Reading Array
const languages = JSON.parse(localStorage.getItem("languages"));
The
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string
It returns null
if it does not find that key
Removing Data
As like the previous examples removing data from local storage is as easy as calling a single method. This method is the removeItem
method and takes a single parameter which is the name of the key value pair to remove.
localStorage.removeItem("name");
Session Storage
Session storage is a popular choice when it comes to storing data on a browser. It enables developers to save and retrieve different values. Unlike local storage, session storage only keeps data for a particular session. The data is cleared once the user closes the browser window.
Storing Data
Session Storage works on the same concepts as the local storage. we just need to use sessionStorage
object -
// Storing Key-Value Pairs
sessionStorage.setItem("day", "monday");
// Storing Object
const userInfo = {
name: "John",
age: 34,
};
sessionStorage.setItem("user-info", JSON.stringify(userInfo));
// Storing Array
const languages = ["Python", "React", "Javascript", "Go"];
sessionStorage.setItem("languages", JSON.stringify(languages));
Read Data
Reading data is also the same as the local storage.
// Reading String
const name = sessionStorage.getItem("name");
// Reading Object
const userInfo = JSON.parse(sessionStorage.getItem("user-info"));
// Reading Array
const languages = JSON.parse(sessionStorage.getItem("languages"));
Removing Data
Removing data is also the same as the local storage.
sessionStorage.removeItem("name");
Cookies
A cookie is usually a tiny text file stored in your web browser. A cookie was initially used to store information about the websites that you visit. But with the advances in technology, a cookie can track your web activities and retrieve your content preferences.
Storing Data
In order to store the data in cookies . You need to access the document.cookie
object and set that to your cookie. To do this all you need to do is set document.cookie
to a string where the name and value are separated by an equals sign.
document.cookie = "name=Smith";
This will create a cookie with the name name
and the value Smith
, but this cookie will be expired since the default expiration date is in the past. In order to set an expiration date manually we need to pass the expires
key a UTC date value. We also need to make sure we separate the expires
key from our name
key with a semicolon ;
.
document.cookie = `name=Smith; expires=${new Date(9999, 0, 1).toUTCString()}`;
This creates a cookie with an expiration date of 01/01/9999 which essentially is like creating a cookie that never expires.
Read Data
Cookies are a bit more difficult since there is no way to get an individual cookie. The only way to get cookies is to get all the cookies at once by accessing the document.cookie
object.
const cookie = document.cookie; // "name=Smith; username=John";
it returns string as the default but as you know it is a little difficult to use it in our code so we can create an function which will take the cookies and returns as the object. Let's see how it will look in the code
// Covert String to Object
function cookiesToObject(cookie) {
var output = {};
cookie.split(/\s*;\s*/).forEach(function (pair) {
pair = pair.split(/\s*=\s*/);
output[pair[0]] = pair.splice(1).join("=");
});
return output;
}
// Getting Cookie Object
const cookieObject = cookiesToObject(document.cookie);
Source - Stack Overflow
Removing Data
Cookies as usual are a bit more difficult. To remove a cookie you need to set the cookie again but give it a blank value and a past expiration date.
document.cookie = "name=; expires=Thu, 01 Jan 1980 00:00:00 GMT";
Conclusion
While local storage, session storage, and cookies are similar, there are minor differences between them that give them all unique use cases. I recommend always using session storage or local storage unless you specifically need to access the data on the server since working with local storage and session storage is much easier than cookies.
You can now extend your support by buying me a Coffee.😊👇
Posted on November 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.