What Every Developer Must Know About Types of Browser Storage
Tags: javascript, webdev, codenewbie, tutorial
Published: 2022-07-15 14:00:51

This post was originally published on [Hackmamba](https://hackmamba.io/blog/2022/07/what-every-developer-must-know-about-types-of-browser-storage/)

We use the browser every day to access the internet and view web pages but have we ever thought of how it stores data? The browser is crucial for saving information about the websites we visit. Storage types used by browsers differ, and it is vital to understand how they work.

This article will discuss the types of storage used by the browser and how they work. 

## Prerequisite

To follow along with this article, we will need the following:

- Basic understanding of HTML and JavaScript
- We can use [Visual Studio Code](https://code.visualstudio.com/download) or any other IDE of our choice

## What Is Browser Web Storage?

Web storage is also known as Document object model storage (DOM storage). It is a client-side feature that gives web apps access to data storage methods and protocols. By client-side, we mean that the processing takes place on the user's computer. 

## Types of Storage in a Browser?

Here is a list of some common browser storage types:

- Web Storage API (localStorage, sessionStorage)
- Cookies 
- IndexedDB


## Web Storage API

WebStorage API, also known as **HTML5 storage**, is a form of persistent storage that stores data on the client's computer. It consists of the following:

- LocalStorage
- SessionStorage

### What Are LocalStorage and SessionStorage?

[LocalStorage](https://www.atatus.com/blog/what-is-javascript-localstorage-a-complete-guide-for-beginners/) is one of the most used browser storage options. We store all our data on our computer permanently in localStorage. It saves our data to the point where we can still access it after we close and reopen our browser.

The data saved in localStorage does not expire until we delete it manually. To erase data from localStorage, use **JavaScript** or clear the **browser cache**.

[SessionStorage](https://www.javascripttutorial.net/web-apis/javascript-sessionstorage/) is like localStorage but with a few differences. It only keeps data for a particular session. We store all our data on our computer temporarily in sessionStorage. When the session expires, i.e., when we close that browser or tab, our data is erased.

Each time we open two tabs with the same URL, the web browser creates its sessionStorage. A different window tab cannot access another sessionStorage data. For example, we can conduct separate transactions on an e-commerce site even if we open two browser tabs.

LocalStorage and sessionStorage store data as a **key-value** pair, but it must be either a number or a string.

**Note:** To store other data types like arrays or objects, we use  `JSON.stringify()` to convert them into strings. 


### Where Is LocalStorage Stored?

In the user's profile, [Goggle chrome](https://en.wikipedia.org/wiki/Web_storage#:~:text=Google%20Chrome%20records%20Web%20storage,%2FLocal%20Storage%20%22%20on%20macOS.) saves web storage data in an SQLite file. We can find this file in the subfolder: 

On Windows:

```JS
    \AppData\Local\Google\Chrome\User Data\Default\Local Storage
```

On MacOS:

```JS
    ~/Library/Application Support/Google/Chrome/Default/Local Storage 
```

Firefox also saves storage objects in the user's profile in an SQLite file called `webappsstore.sqlite`.

### How to View LocalStorage and SessionStorage Data?

Follow these steps to view the data in localStorage and sessionStorage:

- Open developer tools in Google chrome
- Click on the application tab
- Click on localStorage or sessionStorage


![How to view localStorage and sessionStorage data img](https://paper-attachments.dropbox.com/s_D1773B74628DB13DB398CEAAA8D5E83473208BAEA83300A1D226936F7DEBBD28_1656013777405_Untitled+design+1.png)


### How Do Localstorage and Sessionstorage Work?  

Both localStorage and sessionStorage use the following methods:

- **setItem():** Add key/value to both local and sessionStorage 
- **getItem():** Access a value stored in local and sessionStorage 
- **removeItem():** Delete an item from local and sessionStorage 
- **clear():** Delete all items from local and sessionStorage 
- **key():**  It helps us retrieve a key of an item from local and sessionStorage

```JS
    // setItem()
    window.localStorage.setItem('name', 'cess'); // The key is 'name', and the value is 
    'cess'
    
    // To convert arrays or objects to strings 
     const detail = { 
           name: 'cess',    
           job: 'developer',
     }; 
     window.localStorage.setItem('profile', JSON.stringify(detail));  // failure to convert to strings will result in 
     // an error
    
    // getItem() - it takes only one parameter, the key, and returns a string as the 
    // value. To retreieve the above "detail" object:
    window.localStorage.getItem('profile');  // "{name:"cess",job:"developer"}"
    
    // removeItem() -  It requires a key as a parameter 
    window.localStorage.removeItem('name');  // It will remove 'name' from the above 
    // object. To confirm if it worked:
    console.log(localStorage.getItem('name'));  
    
    // clear() - It does not accept any parameters
    window.localStorage.clear(); // will delete all the items stored in localStorage
    
    // key() - It allows us to get the key of a localStorage item using its index.
    var ourKey = window.localStorage.key(index);
```


### Limitations of Using LocalStorage and SessionStorage (Web Storage API)

LocalStorage and sessionStorage have the following limitations:

- **Insecure data:** Avoid storing sensitive user data in localStorage
- It can only store data on the client-side
- **Limited storage capacity:** It has a 5MB storage limit that applies to all major browsers 
- It is synchronous, meaning each localStorage operation will run one at a time


## What Is Cookie Storage?

A [cookie](https://www.w3schools.com/js/js_cookies.asp) is a small data file sent by a website to our device's hard drive or mobile browser. It saves client-side data, allowing users a more personalized web experience.

**4KB** to **1MB** is the maximum storage size for cookies, and the browser saves them in **name-value** pairs.

### What Are the Types of Cookie Storage?

There are two types of cookie storage:

- **Session cookies:** Session cookies have no expiration date. When we exit our browser tab, our saved data is erased. On e-commerce sites, a session cookie keeps track of the items in a shopping cart. It stores these items and helps the browser remember them when it is time to check out.


- **Persistent cookies:** Persistent cookies have an expiration date. It saves our information even after we close our browser, but they expire after a specific time. Its default time length is 30 minutes, but we can change it to any time using the `expire` or `max-age` attributes. 

```JS
    document.cookie = "username=cess; expires=Thu, 19 Dec 2023 11:00:00  GMT "; 
```

### How to Create and Delete Cookies with Javascript?

We can use Javascript to create cookies with the `document.cookie` property:

```JS
    document.cookie = "username=cess";
    console.log(document.cookie);  // "username=cess"
```

Set the `expire` parameter to a past date to delete cookies:

```JS
    document.cookie = "username=; expires=Wed, 19 feb 1985 01:00:00 GMT; path=/"; 
```

### Limitations of Using Cookie Storage

[Cookies](https://www.hitechwhizz.com/2021/02/6-advantages-and-disadvantages-drawbacks-benefits-of-cookies.html) have the following limitations:

- **Limited storage capacity:** It has a limit of 20 cookies per browser and a storage limit of 4KB to 1MB
- **Insecure data:** Avoid storing sensitive user data in cookies
- Since they are synchronous, web workers cannot access them 
- If the browser's security level is too high, it won't function


## What Is the Difference Between SessionStorage, LocalStorage, and Cookies?

 The following picture illustrates how cookies differ from local and sessionStorage: 

![difference between sessionStorage, localStorage and cookies img](https://paper-attachments.dropbox.com/s_D1773B74628DB13DB398CEAAA8D5E83473208BAEA83300A1D226936F7DEBBD28_1656001352425_Cookies+1.png)

## What Is IndexedDB Storage?

IndexedDB is an inbuilt browser database that we use to store large quantities of data. It allows us to create high-quality web applications that we can use both online and offline. 
 
Some of IndexDB's features include the following:

- We can use IndexedDB on all [modern browsers](https://caniuse.com/indexeddb) 
- It utilizes a [transactional database model](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology#transaction) to function
- It stores data using key-value pairs
- IndexedDB API is asynchronous and does not stop the UI rendering
- It is [object-oriented](https://en.wikipedia.org/wiki/Object_database). For more IndexDB features, [click here ](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology).

For more information on IndexedDB, [click here](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API).

## Conclusion

The browser offers various storage options, each with pros and drawbacks. This article taught us about the different types of web storage and how to use them. Now we should be able to choose the proper storage that meets our needs.

## Resources

Here are some resources we may find helpful:

- [Using HTTP Cookies ](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)
- [Different Types of Browser storage](https://developpaper.com/different-types-of-browser-storage/)
[Text](Link)