In modern web pages, storing data is the key to better performance, which can improve the user experience. There are several ways to store the data on the client-side using HTML5. In this blog, we will discuss different types of HTML5 web storage with examples.
Table of Contents:
What is Web Storage?
Web storage is used to store data, you can use it to store data for a short time as well as a long time. This allows the user to store data on the client side without needing server-side storage. There are a few modern storage options available, such as localStorage and sessionStorage, which are faster, have more space, and are secure. Cookies and caches are the traditional way of storing data.
Types of Web Storage in HTML5
The localStorage and sessionStorage are the modern types of web storage present in HTML5. Let us discuss these in detail:
What is localStorage?
It is an HTML5 web storage API that allows you to store data in the browser without an expiry date. This means the data you save will still be there, even if you close and reopen your browser. But keep in mind that it follows the same-origin policy. So, the data can’t be accessed from other websites or domains.
Syntax:
The basic operation for localStorage:
- Saving Data: localStorage.setItem(key, value);
- Retrieving Data: localStorage.getItem(key);
- Removing Data: localStorage.removeItem(key);
- Clearing Data: localStorage.clear();
Example: Storing and Retrieving Objects Using localStorage
The localStorage can only save strings, so if you want to store objects, you’ll need to convert them into JSON format first.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: purple;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="username" type="text" placeholder="Enter your username" />
<input id="email" type="email" placeholder="Enter your email" />
<button type="submit" onClick="saveUser()">
Submit
</button>
<br />
<div id="data"></div>
<script>
function saveUser() {
if (typeof Storage !== "undefined") {
let user = {
username: document.getElementById("username").value,
email: document.getElementById("email").value
};
localStorage.setItem("user", JSON.stringify(user));
displayUser();
} else {
alert("Sorry! Your browser doesn't support Web Storage");
}
}
function displayUser() {
if (localStorage.getItem("user")) {
let storedUser = JSON.parse(localStorage.getItem("user"));
document.getElementById("data").innerHTML =
"Hello, " + storedUser.username + "! Your email is " + storedUser.email + ". Welcome to Intellipaat!";
}
}
window.onload = displayUser;
</script>
</body>
</html>
Output:
Explanation: You store a user’s details, like their username and email, as an object. You save the object using JSON.stringify(user) and retrieve it later with JSON.parse(localStorage.getItem(“user”)). Finally, you display both the username and email after retrieving them.
You can easily see that local storage saves data as key/value pairs. To check this, just inspect the web page, go to the “Application” tab, and look for local storage.
What is sessionStorage?
The sessionStorage is similar to localStorage, which keeps data for the duration of the page session. Once the user closes the browser tab, all stored data is lost.
Syntax:
The basic operation for sessionStorage:
- Saving Data: sessionStorage.setItem(key, value);
- Retrieving Data: sessionStorage.getItem(key);
- Removing Data: sessionStorage.removeItem(key);
- Clearing All Data: sessionStorage.clear();
Example: Storing and Retrieving Object Using sessionStorage
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: red;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="username" type="text" placeholder="Enter your username" />
<input id="age" type="number" placeholder="Enter your age" />
<button type="submit" onClick="saveSessionData()">
Submit
</button>
<br />
<div id="data"></div>
<script>
function saveSessionData() {
if (typeof Storage !== "undefined") {
let user = {
username: document.getElementById("username").value,
age: document.getElementById("age").value
};
sessionStorage.setItem("user", JSON.stringify(user));
displaySessionMessage();
} else {
alert("Sorry! Your browser doesn't support Web Storage");
}
}
function displaySessionMessage() {
if (sessionStorage.getItem("user")) {
let storedUser = JSON.parse(sessionStorage.getItem("user"));
document.getElementById("data").innerHTML =
"Hello, " + storedUser.username + "! You are " + storedUser.age + " years old. Welcome to Intellipaat!";
}
}
window.onload = displaySessionMessage;
</script>
</body>
</html>
Output:
Explanation: You can store a user’s details, like their username and age, as an object. Before storing, you convert the object into a string using JSON.stringify(user). You can retrieve it later using JSON.parse(sessionStorage.getItem(“user”)). After retrieval, you display both the username and age. However, the data will only last for the current session and disappear when the tab is closed.
Other Web Storage
There are a few more web storage options available, which are not a part of HTML5, such as cookies, indexedDB, and cache. Let us discuss these in detail:
What are Cookies?
It is a small file of data that is saved in your browser. If a cookie has an expiration date set, it stays even after you close the browser. But if it’s a session cookie without a set expiration, it gets deleted when you close the browser. You can find it useful in activities like logging in, tracking or personalising your experience with the web pages.
Example: Storing and Retrieving Objects Using Cookies
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: purple;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="username" type="text" placeholder="Enter your username" />
<input id="email" type="email" placeholder="Enter your email" />
<button type="submit" onClick="saveUser()">
Submit
</button>
<br />
<div id="data"></div>
<script>
function setCookie(name, value, days) {
let expires = "";
if (days) {
let date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + "; path=/" + expires;
}
function getCookie(name) {
let nameEQ = name + "=";
let cookiesArray = document.cookie.split("; ");
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i];
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length);
}
}
return null;
}
function saveUser() {
let user = {
username: document.getElementById("username").value,
email: document.getElementById("email").value
};
setCookie("user", JSON.stringify(user), 7);
displayUser();
}
function displayUser() {
let userCookie = getCookie("user");
if (userCookie) {
let storedUser = JSON.parse(userCookie);
document.getElementById("data").innerHTML =
"Hello, " + storedUser.username + "! Your email is " + storedUser.email + ". Welcome to Intellipaat!";
}
}
window.onload = displayUser;
</script>
</body>
</html>
Output:
Explanation: You can use this code to save the data that is username and email using cookies. When you submit these details, they get stored for 7 days.
What is IndexedDB?
It is the database with NoSQL, which is built into your browser. You can use it to store large amounts of data, and it is suitable for complex web applications that need good storage features.
Example: Storing and Retrieving Objects Using IndexDB
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: purple;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="username" type="text" placeholder="Enter your username" />
<input id="email" type="email" placeholder="Enter your email" />
<button type="submit" onClick="saveUser()">Submit</button>
<br />
<div id="data"></div>
<script>
let db;
let request = indexedDB.open("UserDatabase", 1);
request.onupgradeneeded = function(event) {
db = event.target.result;
let objectStore = db.createObjectStore("users", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("username", "username", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};
request.onsuccess = function(event) {
db = event.target.result;
displayUser();
};
request.onerror = function(event) {
console.log("Error opening IndexedDB: ", event.target.error);
};
function saveUser() {
let user = {
username: document.getElementById("username").value,
email: document.getElementById("email").value
};
let transaction = db.transaction(["users"], "readwrite");
let objectStore = transaction.objectStore("users");
let addRequest = objectStore.add(user);
addRequest.onsuccess = function() {
console.log("User data saved successfully!");
displayUser();
};
addRequest.onerror = function() {
console.log("Error saving user data.");
};
}
function displayUser() {
let transaction = db.transaction(["users"], "readonly");
let objectStore = transaction.objectStore("users");
let getAllRequest = objectStore.getAll();
getAllRequest.onsuccess = function() {
let users = getAllRequest.result;
if (users.length > 0) {
let lastUser = users[users.length - 1];
document.getElementById("data").innerHTML =
"Hello, " + lastUser.username + "! Your email is " + lastUser.email + ". Welcome to Intellipaat!";
}
};
getAllRequest.onerror = function() {
console.log("Error retrieving user data.");
};
}
</script>
</body>
</html>
Output:
Explanation: You can use this code to save and retrieve the data, such as username and email, which is stored in the IndexedDB. In the UserDatabase, the information gets stored when you click the submit button.
Note: Transactions in IndexedDB are auto-committed, meaning you must complete all operations before the transaction closes
What is Cache?
You can save responses that you get from network requests through cache storage. You can use those responses later, which can help the web app load faster and improve its performance.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: purple;
text-align: center;
font-size: 30px;
margin-top: 30px;
font-style: italic;
}
#data {
text-align: center;
}
</style>
</head>
<body>
<input id="username" type="text" placeholder="Enter your username" />
<input id="email" type="email" placeholder="Enter your email" />
<button type="submit" onClick="saveUser()">Submit</button>
<br />
<div id="data"></div>
<script>
const cacheName = "userCache";
async function saveUser() {
let user = {
username: document.getElementById("username").value,
email: document.getElementById("email").value
};
const cache = await caches.open(cacheName);
await cache.add("/api/user");
displayUser();
}
async function displayUser() {
const cache = await caches.open(cacheName);
const response = await cache.match("user");
if (response) {
const userData = await response.json();
document.getElementById("data").innerHTML =
"Hello, " + userData.username + "! Your email is " + userData.email + ". Welcome to Intellipaat!";
} else {
document.getElementById("data").innerHTML = "No user data found in cache.";
}
}
window.onload = displayUser;
</script>
</body>
</html>
Output:
Explanation: You can use this code to save and display the data using a cache. When you click on the submit button, the data gets stored in the name of “userCache.”
Comparison of Web Storage
Features | localStorage | sessionStorage | Cookies | IndexedDB | Cache |
Persistence | Permanent | Only for a session | Can have an expiry date | Permanent | Store cached responses |
Storage Limits | Around 5 MB | Around 5 MB | 4KB per cookie | Larger storage, 50MB or more | Depending on the browser storage limits |
Speed | Fast | Fast | Comparatively slower | Maximise for large datasets | Faster loading time for cached responses |
Conclusion
There are a few web storage options available in our browsers to store and retrieve data, such as localStorage, sessionStorage, cookies, indexedDB, and cache. The localStorage and sessionStorage are used to save data directly in your browser. You can use localStorage to keep data even after the browser is closed and use sessionStorage if you only need the data while the browser is open. They’re faster and safer than cookies, and with a bit of JSON formatting, you can even store objects.
Types of Web Storage in HTML5 – FAQs
1. What is web storage in HTML5?
Web storage helps you store data on the client side(user’s browsers).
2. What are the types of web storage in HTML5?
There are two main types: localStorage and sessionStorage. And a few traditional web storage such as cookies and caches.
3. Can you store objects directly in localStorage or sessionStorage?
No, you cannot store objects directly. Both localStorage and sessionStorage only store data as strings. To store an object, you need to convert it into a string using JSON.stringify().
4. How do you retrieve an object from localStorage or sessionStorage?
Use JSON.parse() to convert the stored string back into an object.
5. What is the difference between localStorage and sessionStorage?
localStorage: Data persists even after the browser is closed and reopened. sessionStorage: Data is only available for the current session and is cleared when the tab or browser is closed.