Client-Side Storage in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

Hello and welcome to the 2nd article of the #2Articles1Week challenge series! I'm very excited to partake in this challenge. If you haven't heard about the #2Articles1Week challenge, learn more about it here.

2a1w.png

Firstly, thank you to everyone who read my 1st article of challenge: Why Every Developer Should Start Blogging. It was unbelievable how much people liked and read that article. I didn't expect it at all so thank you very much. I hope my articles are (and will be) helpful to anyone who is doing this challenge or interested in writing/development!

Today, we will be discussing about Client-Side Storage.

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.

1.png Source: upload.wikimedia.org/wikipedia/commons/a/a4..

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

2.png Source: webideasole.com/wp-content/uploads/2019/02/..

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.

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.

LocalStorageSessionStorage
Max Size10-15MB5MB
Data can be accessed fromAnywhere on browser (Same domain)Window/Tab it is created on
Data is deleted whenremoveItem()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 Source: javascript.info/article/indexeddb/indexeddb..

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 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:

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 I'll see you in the next #2Articles1Week article! Cheers!

Osinachi Chukwujama 's photo

Thank you for this post, Victoria

You said something about localStorage being accessible anywhere on the browser.

Can you give more insights on this?

Show +1 replies
Osinachi Chukwujama 's photo

Victoria Lo I think I get it now.

You mean for the same web address, the localstorage is shared across multiple tabs

I previously thought you meant the data in localstorage from one web address can be accessed by another

Victoria Lo's photo

Osinachi Chukwujama Yes it's per domain and port (like same origin policy).

Bolaji Ayodeji's photo

This was worth my time, gave it a share also. Thank you for sharing :)

Ben's photo

Thank you. Great article. I love the "CRUD Examples" format. I hope you don't mind if I borrow that some of my posts.

Victoria Lo's photo

No problem! Feel free to use it!

Mohammed Jabali's photo

Thank you. Your article is very helpful.

I noticed this issue:

let openRequest = indexedDB.open('database', 1);
// users is the database name and 1 is the version

There is no "users" in your code.

Victoria Lo's photo

Thanks for pointing that out! I have corrected it :)