4 Ways to Save Data Locally Without Setting Up a Server

If you want to save data locally in an application without setting up a server, you can use client-side storage options provided by browsers.

There are four main options for client-side storage in JavaScript.

1. Cookies

Cookies are small pieces of data that can be stored on the user's device. They have a size limit (usually around 4 KB) and are sent with every HTTP request, which can impact performance.

// Function to set a cookie
const setCookie = (name, value, days) => {
  const expirationDate = new Date();
  expirationDate.setDate(expirationDate.getDate() + days);

  const cookieString = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`;
  document.cookie = cookieString;
};

// Function to get a cookie by name
const getCookie = (name) => {
  const cookies = document.cookie.split("; ");

  for (const cookie of cookies) {
    const [cookieName, cookieValue] = cookie.split("=");

    if (cookieName === name) {
      return cookieValue;
    }
  }

  return null;
};

// Example usage
setCookie("username", "john_doe", 7);

const username = getCookie("username");
console.log("Username:", username);

2. LocalStorage

LocalStorage allows you to store key-value pairs in the user's browser. The data will persist even if the user closes the browser or navigates away from the page.

// Save data to LocalStorage
localStorage.setItem("key", "value");

// Retrieve data from LocalStorage
const data = localStorage.getItem("key");

3. SessionStorage

SessionStorage is similar to LocalStorage, but the data is only available for the duration of the page session. Once the user closes the browser or tab, the data is cleared.

// Save data to SessionStorage
sessionStorage.setItem("key", "value");

// Retrieve data from SessionStorage
const data = sessionStorage.getItem("key");

4. IndexedDB

IndexedDB is a low-level API for storing large amounts of structured data. It's more powerful but also more complex than LocalStorage.

// Open or create an IndexedDB database named 'smallDB' with version 1
const request = indexedDB.open("smallDB", 1);

// Event handler triggered when a database upgrade is needed
request.onupgradeneeded = (event) => {
  // Get a reference to the database
  const db = event.target.result;

  // Create an object store named 'myStore' with 'id' as the key path
  const objectStore = db.createObjectStore("myStore", { keyPath: "id" });
};

// Event handler triggered when the database is successfully opened
request.onsuccess = (event) => {
  // Get a reference to the opened database
  const db = event.target.result;

  // Start a new transaction on the 'myStore' object store in read-write mode
  const transaction = db.transaction(["myStore"], "readwrite");

  // Get a reference to the 'myStore' object store within the transaction
  const objectStore = transaction.objectStore("myStore");

  // Add a new object with id: 1 and data: 'value' to the 'myStore' object store
  objectStore.add({ id: 1, data: "exampleValue" });

  // Log a message to indicate that the operation was successful
  console.log("Object added to myStore in smallDB");
};

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda