Nearly every mobile or desktop app has some sort of convenient way to store user data. In the case of websites, however, what is the best way to store digital assets and user information? In the past, we relied on cookies, but they have serious limitations. HTML5 introduces a better solution to solve this problem. In this article, we will talk about HTML5 web storage options and give you a brief overview of web storage in general.
What are the Limitations of Cookies?
Since the early days, cookies have been a great option for data storage in web browsers, which had advantages and disadvantages for web developers.
One of the advantages of cookies is that it allows users to log in automatically to the sites they visit often, such as Gmail and Facebook. On the other hand, with cookies, privacy is a concern, as a browser’s search and browsing history can be easily tracked.
Another problem is data capacity. Many browsers can store cookies about 4 KB per cookie, and if we exceed the size of one cookie, then another cookie needs to be created. Most of the Internet browsers today allow for 30 to 50 cookies; this can become a real problem. This is part of the reason why developers prefer to only store session identifiers in cookies and use server-side databases to retrieve and store the rest of their user data.
Another often-overlooked problem with cookies is the fact that they are always sent with every HTTP request, which results in the consumption of more data bandwidth and can affect performance.
Using Web Storage with HTML5
Fortunately, HTML5 brings new features for storing data. One is IndexedDb and the other is Web storage. Web storage is a combination of two similar APIs, which we will cover later in this article. Let’s first discuss some of the strengths and advantages of Web Storage.
Benefits of Web Storage versus Cookies
The following are some of the benefits of using HTML5 web storage versus cookies:
- Ease of use: Features a simple API for getting and setting data in key/value pairs.
- More space: No less than 5 MB or 10 MB per domain (depending on the browser) can be stored in web storage, allowing developers to store data other than just basic session or user information on the client side.
- Accessibility: As Web Storage data is accessed using Javascript, it gives web developers the power to do many things with client-side scripting that previously involved server-side programming.
Web Storage Objects (localStorage and sessionStorage)
There are two types of Web Storage objects: sessionStorage and localStorage. We define each type of storage objects below:
- localStorage: localStorage holds data between browser sessions. This means data persists even if the browser is closed and reopened and retains data between tabs and windows.
- sessionStorage: sessionStorage is available only within the window session or browser tab. Data persists until the browser is closed (the same is not true for the tab). A good use case is to store temporary data of a form a user is filling out in case the user accidentally reloads the page or closes the tab.
Where to Use Web Storage Objects
- localStorage: One of the scenarios for using localStorage is saving a product that the user places in their shopping cart. It can be accessed between multiple browser tabs, page requests, and even between browser sessions. Using localStorage, the app can completely work offline. Data can then be sent and saved on the server when the user comes back online.
- sessionStorage: When we want to get rid of data as soon as the window is closed – or we don’t want the application to interfere with the same application opened in a different window (like running two instances of a Scrabble game) – we use sessionStorage. These are the types of situations where sessionStored serves best.
How to Use the Web Storage API
Now that we have learned about some of the scenarios where web storage objects can be used and what, exactly, web storage is, let’s get our hands dirty and look at some HTM5 web storage code examples.
For starters, let’s store an item and then retrieve it from localStorage. Here is the HTML5 code showing how to achieve this:
localStorage.setItem('userId', '103'); var myVar = localStorage.getItem('userId'); sessionStorage.setItem('user', 'George'); var myVar = sessionStorage.getItem('user');
The .setItem method can be used to set the key and its value, while getItem can be used to retrieve the value of that particular key. Note: There is a drawback with this method in that only strings can be stored. However, we can save and retrieve string representations of JSON objects using JSON.stringify() and JSON.parse() methods.
Set Item :
const person = { name: "Adam", location: "United States" } window.localStorage.setItem('user',JSON.stringify(person));
Get Item:
var user = JSON.parse(localStorage.getItem(user));
Removing Items:
localStorage.removeItem('user');
or:
window.localStorage.removeItem('user');
This Removes the key from storage if it exists; otherwise this method would do nothing.
Clearing storage:
window.localStorage.clear(); window.sessionStorage.clear();
Iteration over items:
We can use a for loop for iterating over the items, as there is no forEach method belonging to localStorage and sessionStorage. Here is how that looks in HTML5 code:
for (let i = 0; i < localStorage.length; i++){ let key = localStorage.key(i); let value = localStorage.getItem(key); console.log(key, value); }
Storage Events in HTML5
Whenever data is stored in localStorage, the storage event is fired in the other tabs and windows. This event is useful for synchronizing data if the user has opened the same website in different tabs (which causes quite an issue with cookies).
The storage event is fired only when the new value is not the same as the old value. The event contains properties such as – key, oldValue and newValue. Below is an example illustrating it:
Here, we have created an event listener on the window object for the storage event. Whenever the event is triggered, it logs the key, old value, and new value to the browser console.
Browser Support for Web Storage
We encourage you to start using this API today. It is implemented in all modern Internet browsers, including Firefox 3.5, Safari 4, Google Chrome 4, Opera 10.50, and IE8+. Unfortunately, IE7 and earlier versions don’t support this API.
Security Concerns for Web Storage
Please note that using the web storage feature is not entirely secure. It has great power but has great responsibility too. Never store any sensitive information like credit card details or passwords in web storage, as data is saved in the client-side (browser) and can be accessed easily; it’s not an alternative to a server-based database storage at all.
Final Notes on Web Storage and HTML5
Web Storage is a great HTML5 feature. It stores data in Javascript’s window object (window.localStorage and window.sessionStorage), so it is also referred to as DOM storage. Keep in mind that web storage can also be turned off by users (like cookies), so under such circumstances, we always need to implement a fallback mechanism.