Skip to main content

Web Storage

Cookies:

A normal cookie is accessible from JavaScript and it is also included in every request to the associated domain. A cookie with the HttpOnly attribute is blocked from JavaScript and only is included in requests to the domain.

Then optionally, you add the Secure attribute as well to force the cookie to only be sent over HTTPS and not HTTP.

  • Small text files (usually < 4KB)
  • Sent with every HTTP request
  • Can be set to expire or persist
  • Accessible server-side and client-side
  • Used for session management, personalization

Local Storage:

  • Larger capacity (usually 5-10MB)
  • Data persists even after browser is closed
  • Accessible only client-side (JavaScript)
  • No automatic expiration
  • Good for storing non-sensitive user preferences

Session Storage:

  • Similar to Local Storage in capacity
  • Data cleared when browser tab is closed
  • Accessible only client-side (JavaScript)
  • Scope limited to a single browser tab
  • Useful for temporary data in a single session

IndexedDB:

  • Large capacity (generally unlimited)
  • Client-side database for structured data
  • Supports complex queries and indexing
  • Asynchronous API
  • Good for offline apps and large datasets

Key Differences:

Persistence: Cookies and Local Storage persist, Session Storage is temporary, IndexedDB can be configured.

Capacity: Cookies are smallest, Local/Session Storage larger, IndexedDB largest.

Complexity: Cookies and Storage are key-value pairs, IndexedDB is a full database.

Server Access: Only cookies are sent to the server automatically.

API: Cookies use document.cookie, Storage uses a simple get/set API, IndexedDB has a more complex API.

Local Storage

Local storage is a web storage mechanism that allows you to store data on the client's browser with no expiration date. The data persists even after the browser is closed and reopened. It's useful for storing large amounts of data that need to be available across sessions.

Example Usage:

// Storing data
localStorage.setItem("username", "shadab");

// Retrieving data
const username = localStorage.getItem("username");
console.log(username); // Outputs: shadab

// Removing data
localStorage.removeItem("username");

// Clearing all data
localStorage.clear();