Client-side storage in JavaScript is a powerful tool for creating dynamic, interactive web pages that can store data on the user's computer. With client-side storage, JavaScript applications have the ability to store data locally within a browser rather than sending it back and forth between a server and the browser each time an action takes place. This allows websites to create more responsive experiences as they can quickly retrieve stored information without additional requests or refreshes.

There are several options for client-side storage in JavaScript, including:

  • Cookies — The browser saves a few small text files on the user's machine. Small pieces of data, such as user preferences or login details, can be stored in them. Example:
// Setting a cookie
document.cookie = "username=Sagar";

// Getting a cookie
const username = document.cookie.split("=")[1];
console.log(username); 
//Output -> "Sagar"
None
  • Local Storage — Allows you to save key-value pairs on the client's browser. The data is saved even after the browser is closed and can be used to store large amounts of information. Example:
// Setting a value in local storage
localStorage.setItem("username", "Sagar");

// Getting a value from local storage
const username = localStorage.getItem("username");
console.log(username); 
//Output -> "Sagar"
None
  • Session Storage Similar to Local Storage, but the data is deleted when the browser or the page is closed. Example:
// Setting a value in session storage
sessionStorage.setItem("username", "Sagar");

// Getting a value from sessionstorage
const username = sessionStorage.getItem("username");
console.log(username); 
//Output -> "Sagar"
None
  • IndexedDB — It is a low-level API for client-side storage of large amounts of structured data, such as files and blobs. This API makes use of indexes to allow for high-performance searches of this data. With the help of this, you can make your applications work both online and offline. Example:
//Open a database
const request = window.indexedDB.open("MyDatabase", 1);

// Create object store if it does not exist
request.onupgradeneeded = function(event) {

  // Save the IDBDatabase interface
  const db = event.target.result;

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("users", { keyPath: "id" });
};

/* 
If the onupgradeneeded event exits successfully, 
the onsuccess handler of the open database request will then be triggered.
*/

request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(["users"], "readwrite");
  const objectStore = transaction.objectStore("users");

  // Add data to object store
  objectStore.add({ id: 1, name: "Sagar", age: 30 });

  // Retrieve data from object store
  const request = objectStore.get(1);
  request.onsuccess = function(event) {
    console.log(event.target.result); 
    // { id: 1, name: "Sagar", age: 30 }
  };
};

// Handling error
request.onerror = (event) => {
  console.error(`Database error: ${event.target.error}`);
};
None
  • CacheStorage — You can use the browser's built-in cache storage. Cache storage allows you to cache files, such as images, scripts, and stylesheets, in the browser's cache so that they can be loaded faster on subsequent visits to the website. Example:
// Caching a file
caches.open('static-v1').then(cache => {
    return cache.addAll([
        '/styles/main.css',
        '/scripts/main.js',
        '/images/logo.png'
    ])
});

// Retrieving a cached file
caches.match('/images/logo.png').then(response => {
    if (response) {
        // Use the cached version
        return response;
    }
    // Otherwise, fetch the file
    return fetch('/images/logo.png');
});

The data can be viewed and altered by any JavaScript code active on the website, making client-side storage less secure than server-side storage. So, private data like passwords or other sensitive information shouldn't be kept on the client side.

Furthermore, depending on the user's device and browser, the storage capacity and feature support may change. Therefore, it is always advised to confirm that a feature is supported and that there is enough storage before utilizing it.

We appreciate you reading this article. If you enjoyed my writing but aren't a member of Medium, you can sign up for a Medium membership to have unlimited access to all content and support us as writers.