Client-Side Storage in JavaScript
Tags: javascript, storage, webdev, tutorial
Published: 2020-12-29 03:27:12

---
title: Client-Side Storage in JavaScript
published: true
date: 2020-07-12 11:33:31 UTC
tags: JavaScript,storage,WebDevelopment,Tutorial
canonical_url: https://lo-victoria.com/client-side-storage-in-javascript
---

## What is Client-Side Storage?
As the name suggests, client-side storage allows the user to **store data on the client** (i.e. user's browser). Conversely, server-side storage will store data on the server (i.e. an external database).

> For more infomation on the difference between 'client' and 'server', check out my article on [Introduction to Back-End Programming](https://lo-victoria.com/a-beginners-intro-to-back-end-programming-ckanyrk7d02b2bbs1g9fv127k).

![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1594508523310/OuE2hLSIe.png)
*Source: https://upload.wikimedia.org/wikipedia/commons/a/a4/AppLSAC-0_LocalStorage_remote_data_fetch.svg*

In many modern browsers today, pages are dynamically loaded. This means that they use server-side storage to retrieve data and render it on the browser. However, there are still instances where client-side storage can be useful.

### When is it useful?
Client-side storage can be advantageous for the following use cases:
- **Quick and network-independent** access to data
- **Store user preferences** (i.e. custom widgets, font size, colour, etc.)
- **Store session of previous activity** (i.e. logged in an account, shopping cart, etc.)
- **Save data locally for offline use**

## Types of Client-Side Storage
### **1. Cookies** (Not Recommended)

![2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1594509716015/VPKCWTbOj.png)
*Source: https://www.webideasole.com/wp-content/uploads/2019/02/javascript-cookies-01-splessons.png*

You probably have heard of cookies. They are the most classic type of client-side storage and have been used by sites since the early days of the web.

Cookies are **sent from the server** to the client and then **stored on the client**. The stored cookie can then be retrieved and sent back to the server whenever the client makes a request to the server again. Typically, cookies are used to manage account sessions, store user information and track user data. 

However, because cookies are the oldest forms of client-side storage, they have a few **security issues and storage limitations**, which make them an unsuitable option to store client-side data.

> For more information on the security issues of cookies, read [here](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#Security).

### CRUD Example
```
//Create
document.cookie = "name=victoria";

//Read
console.log( document.cookie );

//Update
document.cookie = "name=victoria lo";

//Delete - Just set an expiry date that has passed
document.cookie = "name=victoria lo ; expires = Thu, 01 Jan 2010 00:00:00 GMT"
```

### **2. Web Storage API**
The Web Storage API is an API which stores **key-value pairs** of data in the client. This simple and intuitive syntax allows easy storage and retrieval of **strings or stringified JSON data**.

There are 2 types of web storage in this API: **Local Storage** and **Session Storage**.

### Local Storage vs Session Storage
Some distinct differences between the 2 types of web storage to note.

|              | LocalStorage| SessionStorage
|:------- |:---------------|:--------------
| Max Size    |10-15MB    | 5MB
| Data can be accessed from   | Anywhere on browser (Same domain)   | Window/Tab it is created on
|Data is deleted when      | removeItem()           | When browser is closed

### CRUD Example of Local Storage
```
// Create
const user = { first: 'Victoria', last: 'AAA' }
//store as a stringified JSON
localStorage.setItem('user', JSON.stringify(user));

// Read
console.log(JSON.parse(localStorage.getItem('user')))
//output will be a JSON: {first: "Victoria", last: "lo"}

// Update
const update = { first: 'Victoria', last: 'Lo'  }
localStorage.setItem('user', JSON.stringify(update));

// Delete
localStorage.removeItem('user');
```
### CRUD Example of Session Storage
Same syntax as Local Storage but replace ```localStorage``` with ```sessionStorage```.

### **3. IndexedDB API**
A complete database system suitable to store more complex data than Local Storage in the client. Unlike the Web Storage API, it allows more structured data to be organized and stored such as customer records, detailed to-do lists, etc.

It uses **object stores**, which are essentially table-like structures, to contain key-value pairs.

![4.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1594513580751/2aGlTduh5.png)
*Source: https://javascript.info/article/indexeddb/indexeddb-structure.svg*

### CRUD Example
First, we have to make a request to open the database:
```
let openRequest = indexedDB.open('users', 1);
// users is the database name and 1 is the version
```
Then, we can add some methods below to perform operations:
```
openRequest.onupgradeneeded = function() {
  // triggers if the client had no database
  // ...perform initialization...
};

openRequest.onerror = function() {
  console.error("Error", openRequest.error);
};

openRequest.onsuccess = function() {
  let db = openRequest.result;
  // continue to work with database using db object
};
```
*(Code from https://javascript.info/indexeddb)*

Now, let's create an object store inside the ```onupgradeneeded``` method:
```
let db = openRequest.result;
 // if there's no "users" store initialized, we create one
if (!db.objectStoreNames.contains('users')) {
       let objectStore = db.createObjectStore('users', { keyPath: 'id', autoIncrement:true });
}
```
To add data into the object store, IndexedDB API uses **transactions**. We can start a transaction to add/put data into our 'users' object store with:
```
// open a read/write transaction
let transaction = db.transaction("users", "readwrite"); 

// get the object store we want to operate on
let userStore = transaction.objectStore("users");

// add the data into the store
userStore.add({
    	first: 'Victoria',
    	last: 'Lo'
    });

// finish the transaction
transaction.oncomplete = function() {
  console.log("Transaction is complete");
};
```
To read or delete data, simply follow the same transaction steps previously shown but this time, instead of add, we use:
```
// Read
userStore.get('Victoria');

// Delete
userStore.delete('Victoria');
```

## And that's the gist!
Thank you for reading this basic introduction to client-side storage in JavaScript. These examples only serve as a quick overview of how these various types of storage work. I encourage you to read for more details at:
- https://javascript.info/indexeddb
- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage

Still, the best way to learn is by doing, so I also encourage you to **try making a mini project** that uses client-side storage. I hope this article has been helpful. If it is, please like and share it with your community! 

And please, **do not hesitate to ask any questions** or concerns in the comments below. Thanks and cheers!