An Overview of Client-Side Storage

Storing data directly within the browser has a lot of benefits, the main one being quick and network-independent access to a "database". There are currently four active methods (plus one deprecated), for storing data on the client side -

  1. Cookies
  2. Local Storage
  3. Session Storage
  4. IndexedDB
  5. WebSQL (deprecated)

Cookies

Cookies are the classic way of storing simple string data within a document. Typically, cookies are sent from the server to the client, which can then store it, and send it back to the server on subsequent requests. This can be used for things like managing account sessions and tracking user information.

Additionally, cookies can be used for storing data purely on the client-side. Because of this, they have also been used for storing general data, such as user preferences.

Basic CRUD with Cookies

We can create, read, update, and delete cookies using the following syntax -

// Create
document.cookie = "user_name=Ire Aderinokun";  
document.cookie = "user_age=25;max-age=31536000;secure";

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

// Update
document.cookie = "user_age=24;max-age=31536000;secure"; 

// Delete
document.cookie = "user_name=Ire Aderinokun;expires=Thu, 01 Jan 1970 00:00:01 GMT";  

Advantages of Cookies

  • They can be used for communication with the server
  • We can set when we want the cookie to expire automatically, instead of having to manually delete

Disadvantages of Cookies

  • They add to the page load of the document
  • They can only store a small amount of data
  • They can only store Strings
  • Potential security issues
  • It is not the recommended method for client-side storage anymore since the introduction of the Web Storage API (Local and Session Storage)

Support

Cookies have basic support in all major browsers.

Local Storage

Local Storage is one type of the Web Storage API, which is an API for storing key-value pairs of data within the browser. It arose as a solution to the issues with Cookies, by offering a more intuitive and secure API for storing simple data within the browser.

Although technically we can only store strings in Local Storage, this can be worked around by storing stringified JSON. This allows us to store a bit more complex data in Local Storage than we can with Cookies.

Basic CRUD with Local Storage

We can create, read, update, and delete data to Local Storage using the following syntax -

// Create
const user = { name: 'Ire Aderinokun', age: 25 }  
localStorage.setItem('user', JSON.stringify(user));

// Read (Single)
console.log( JSON.parse(localStorage.getItem('user')) ) 

// Update
const updatedUser = { name: 'Ire Aderinokun', age: 24 }  
localStorage.setItem('user', JSON.stringify(updatedUser));

// Delete
localStorage.removeItem('user');  

Advantages of Local Storage

  • Offers a more simple intuitive interface to storing data (than Cookies)
  • More secure for client-side storage (than Cookies)
  • Allows for the storage of more data (than Cookies)

Disadvantages of Local Storage

  • Only allows the storage of Strings

Support

Data on support for the namevalue-storage feature across the major browsers from caniuse.com.

Session Storage

Session Storage is the second type of the Web Storage API. It is exactly the same as Local Storage, except that the data is only stored for the browser tab session. Once the user closes that browser tab, the data is cleared.

Basic CRUD with Session Storage

We can create, read, update, and delete data to Session Storage using the following syntax -

// Create
const user = { name: 'Ire Aderinokun', age: 25 }  
sessionStorage.setItem('user', JSON.stringify(user));

// Read (Single)
console.log( JSON.parse(sessionStorage.getItem('user')) ) 

// Update
const updatedUser = { name: 'Ire Aderinokun', age: 24 }  
sessionStorage.setItem('user', JSON.stringify(updatedUser));

// Delete
sessionStorage.removeItem('user');  

Advantages, Disadvantages, and Support for Session Storage

Same as for Local Storage.

IndexedDB

IndexedDB is a much more complex and well-rounded solution for storing data in the browser. It is a "low-level API for client-side storage of significant amounts of structured data" (Mozilla). It is a JavaScript-based, object-oriented, database that allows us to easily store and retrieve data that has been indexed with a key.

In my article on Building a Progressive Web Application, I went over in more detail how you can use IndexedDB to create an offline-first application.

Basic CRUD with IndexedDB


Note: In all my examples, I uses Jake Archibald’s IndexedDB Promised library which offers a Promise-ified version of the IndexedDB methods.

Using IndexedDB is more complicated than the other browser storage methods. Before we can create/read/update/delete any data, we need to first open up the database, creating any stores (which are like tables in a database) we need.

function OpenIDB() {  
    return idb.open('SampleDB', 1, function(upgradeDb) {
        const users = upgradeDb.createObjectStore('users', {
            keyPath: 'name'
        });
    });
}

To create (or update) data within a store, we need to go through the following steps -

// 1. Open up the database
OpenIDB().then((db) => {  
    const dbStore = 'users';

    // 2. Open a new read/write transaction with the store within the database
    const transaction = db.transaction(dbStore, 'readwrite');
    const store = transaction.objectStore(dbStore);

    // 3. Add the data to the store
    store.put({
        name: 'Ire Aderinokun',
        age: 25
    });

    // 4. Complete the transaction
    return transaction.complete;
});

To retrieve data, we need to go through the following -

// 1. Open up the database
OpenIDB().then((db) => {  
    const dbStore = 'users';

    // 2. Open a new read-only transaction with the store within the database
    const transaction = db.transaction(dbStore);
    const store = transaction.objectStore(dbStore);

    // 3. Return the data
    return store.get('Ire Aderinokun');
}).then((item) => {
    console.log(item);
})

Finally, to delete data, we need to do the following -

// 1. Open up the database
OpenIDB().then((db) => {  
    const dbStore = 'users';

    // 2. Open a new read/write transaction with the store within the database
    const transaction = db.transaction(dbStore, 'readwrite');
    const store = transaction.objectStore(dbStore);

    // 3. Delete the data corresponding to the passed key
    store.delete('Ire Aderinokun');

    // 4. Complete the transaction
    return transaction.complete;
})

If you're interested in learning more about how to use IndexedDB, you can read my article showing how I used it in a Progressive Web Application.

Advantages of IndexedDB

  • Can handle more complex, structured, data
  • Can have multiple "databases" and "tables" within each "database"
  • More allowance for storage
  • More control over how we interact with it

Disadvantages of IndexedDB

  • More complex to use than the Web Storage API

Support

Data on support for the indexeddb feature across the major browsers from caniuse.com.

WebSQL

WebSQL is an API for a relational database on the client, similar to SQLite. Since 2010, the W3C Web Applications Working Group has ceased working on the specification. It is no longer a part of HTML specification, and should not be used.

A Comparison

Feature Cookies Local Storage Session Storage IndexedDB
Storage Limit ~4KB ~5MB ~5MB Up to half of hard drive
Persistent Data? Yes Yes No Yes
Data Value Type String String String Any structured data
Indexable? No No No Yes
blog comments powered by Disqus