Understanding Client-Side Storage: Cookies vs. IndexedDB with Practical Examples
Published in
3 min readJul 28, 2024
Cookies and IndexedDB are both mechanisms for storing data on the client side, but they have different characteristics and use cases.
Cookies
Characteristics:
- Size Limit: Typically, cookies are limited to about 4KB in size.
- Automatic Data Sending: Cookies are automatically sent with every HTTP request to the domain that set them.
- Expiration: Cookies can be set to expire at a specific time or can be session-based (deleted when the browser closes).
- Scope: Cookies are scoped by domain and path, allowing some control over which pages can access them.
- Security: Cookies can be flagged as Secure (only sent over HTTPS) and HttpOnly (not accessible via JavaScript).
Use Cases:
- Session Management: Storing session tokens or user authentication data.
- Personalization: Saving user preferences or settings for a website.
- Tracking: Keeping track of user behavior across visits (often used by analytics and ad tracking services).
Example:
// Setting a cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 12:00:00 UTC; path=/";
// Reading a cookie
let cookies = document.cookie.split("; ");
for (let cookie of cookies) {
let [name, value] = cookie.split("=");
console.log(`${name}: ${value}`);
}
// Deleting a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
IndexedDB
Characteristics:
- Size Limit: IndexedDB has a much larger storage capacity compared to cookies (up to hundreds of megabytes or more, depending on the browser).
- Structured Data: IndexedDB allows you to store complex data structures, including objects and files.
- Asynchronous: IndexedDB operations are asynchronous, which helps avoid blocking the main thread.
- Transactions: IndexedDB uses transactions for reading and writing data, ensuring data integrity.
- Indexed: Data can be indexed for fast retrieval, supporting advanced querying capabilities.
Use Cases:
- Large Data Storage: Storing large amounts of structured data, such as user-generated content or offline web application data.
- Offline Applications: Supporting offline functionality by storing data locally when the network is unavailable.
- Complex Queries: Running complex queries on stored data for fast retrieval and manipulation.
Example:
// Opening (or creating) an IndexedDB database
let request = indexedDB.open("myDatabase", 1);
request.onupgradeneeded = function(event) {
let db = event.target.result;
let objectStore = db.createObjectStore("users", { keyPath: "id" });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};
request.onsuccess = function(event) {
let db = event.target.result;
// Adding data
let transaction = db.transaction(["users"], "readwrite");
let objectStore = transaction.objectStore("users");
let user = { id: 1, name: "John Doe", email: "john@example.com" };
objectStore.add(user);
// Reading data
transaction = db.transaction(["users"]);
objectStore = transaction.objectStore("users");
let getRequest = objectStore.get(1);
getRequest.onsuccess = function(event) {
console.log(event.target.result);
};
// Deleting data
transaction = db.transaction(["users"], "readwrite");
objectStore = transaction.objectStore("users");
objectStore.delete(1);
};
Comparison:
- Size: Cookies are suitable for small amounts of data (<4KB), while IndexedDB can handle much larger datasets.
- Data Structure: Cookies store simple key-value pairs, whereas IndexedDB can store and index complex objects.
- Persistence: Cookies can be set to expire; IndexedDB data persists until explicitly deleted.
- Use Case: Use cookies for lightweight, short-term data (e.g., session tokens, user preferences). Use IndexedDB for larger, structured, long-term data (e.g., offline application data, complex user data).
Conclusion:
Choose cookies for simple, small-scale data storage with automatic transmission to the server, and choose IndexedDB for handling larger, more complex data structures with advanced querying and offline capabilities.