Web Storage APIs

Web Storage APIs

In this blog, we explore the Web Storage API provided by modern web browsers. This API allows websites to store data directly within the user's browser. There are three main types of Web Storage APIs:

  1. Local Storage: Enables data storage across browser sessions, persisting even after the browser is closed.

  2. Session Storage: Similar to Local Storage but limited to the duration of the browser session.

  3. IndexedDB: A more complex solution that allows the storage of significant amounts of structured data and supports transactions.


What is Local Storage?

Local Storage is widely supported by modern web browsers and allows websites to store data in key-value pairs persistently. This persistence means that the data will remain stored across browser sessions and even if the user restarts their computer.

Using Local Storage

localStorage.setItem('myKey', 'myValue');  // Add or update data under 'myKey'
const retrievedValue = localStorage.getItem('myKey');  // Retrieve data for 'myKey', returns null if not found
localStorage.removeItem('myKey');  // Remove data associated with 'myKey'
localStorage.clear();  // Clear all data stored by the website in Local Storage

This code snippet concisely shows all the main operations (adding, retrieving, removing, and clearing data) associated with Local Storage. Each line is annotated with a comment to explain what it does. Note that localStorage.clear() clears data only for your domain and does not impact other domains.

Handling Complex Data Types in Local Storage

Local Storage only supports storing data as strings, which necessitates serialization of complex data types like arrays or objects before storing them. Here’s how to handle this using JSON:

// Convert the data to a JSON string and store it
let nums = [1, 2, 3];  // Example array
localStorage.setItem('nums', JSON.stringify(nums));  // Serializing array to string

// Retrieve the stored string and parse it back to original data type
let retrievedNums = JSON.parse(localStorage.getItem('nums'));  // Parsing string back to array

In this code snippet, JSON.stringify(nums) converts the array nums into a JSON string format for storage, while JSON.parse(localStorage.getItem('nums')) retrieves and converts this string back to an array. This process allows the preservation of the original structure and type of data when using Local Storage, which inherently only stores strings.

Appropriate Uses for Local Storage

Local Storage is a useful feature in web browsers for storing non-sensitive data across sessions. Here are examples of what is safe and effective to store in Local Storage:

  1. User Preferences: Settings such as layout preferences, themes, or language settings can enhance the user experience without compromising security.

  2. Session State: Data like the history of user actions (e.g., product views, last page visited) can be stored to maintain state across sessions.

  3. Form Data: To improve user convenience, form entries can be saved so users don't lose their progress if they accidentally close the window.

  4. Shopping Cart Contents: It’s common to store items in the user’s shopping cart to persist even when they leave the site temporarily.

  5. Caching Data: Frequently accessed data such as images or files can be cached in Local Storage to reduce load times.

  6. Analytics and Ad Tracking: Storing analytics data and tracking information for advertisements can help in gathering insights without additional server requests.

What Not to Store in Local Storage

Due to its vulnerability to cross-site scripting (XSS) attacks, Local Storage should not be used to store sensitive data:

  • Sensitive Information: Never store passwords, personal identification details, financial data, or any other information that could compromise user security.

  • Email Addresses and Phone Numbers: Storing contact information can be risky and should be avoided to protect user privacy.

Limitations of Local Storage

  1. While Local Storage is highly useful, it has certain limitations, primarily regarding its capacity. Most browsers restrict Local Storage to about five megabytes per domain. This limitation is crucial to remember as it is not intended for large data storage needs.

Here are exciting projects that you can dive into to learn more about local-storage


What is Session Storage?

Session storage provides a mechanism for storing data within the user's browser on the client side, similar to local storage. However, there are distinct differences in how data is managed with session storage:

Key Characteristics of Session Storage:

  • Temporary Storage: Data stored in session storage remains available throughout the browser session. This means that data persists over page reloads but not when opening a new tab or window.

  • Isolation Across Tabs and Windows: Each tab or window has its own isolated session storage. Unlike local storage, where data is shared across all instances of a domain, session storage does not share data between tabs or windows.

  • Session-Based Utility: Ideal for storing data that should only persist during an active browser session. This is useful in scenarios like maintaining state in single-page applications without needing the data to persist beyond the session.

  • API Compatibility: The session storage API mirrors that of local storage, providing methods such as setItem, getItem, removeItem, and clear, making it easy to adopt and implement.

Use Cases for Session Storage:

  • State Management in Single-Page Applications: Maintain user state during navigation without permanent storage.

  • Performance Enhancements: Use session storage to cache data fetched during the session, reducing the need to reload data on every page refresh.

  • Transient Data Storage: Store data that should not persist beyond the session, such as sensitive information that doesn’t require long-term storage but should be readily available as long as the session continues.

Capacity and Limitations:

  • Storage Capacity: Similar to local storage, most modern browsers support approximately five megabytes of data for session storage.

  • Data Persistence: Data in session storage is maintained through page refreshes but not through new sessions or tabs.

Session Storage Project Link - Form Data Storage using Session Storage


What is IndexedDB?

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This allows you to build applications that work seamlessly both online and offline, taking advantage of complex data models and rich query capabilities.

Basic Usage Pattern of IndexedDB

The fundamental pattern encouraged by IndexedDB involves a few key steps:

  1. Open a database: The open method on indexedDB is used to open a database asynchronously, which does not block the browser's UI thread.

  2. Create an object store: If the database is being created for the first time or if a new version number is provided, the onupgradeneeded event is triggered where you can create object stores which hold the data.

  3. Start a transaction and make a request: Transactions are used to read from and write to the database. You can start a transaction on an object store and make requests to add, retrieve, or modify the stored data.

  4. Handle responses: Listen to the events on the request to handle the results of your database requests.

Here's the code with comments explaining each step:

const openRequest = indexedDB.open("myDatabase", 1); // Open a database. 

// Event handler for creating or upgrading the database. Called when accessing a new database or a new version of the database.
openRequest.onupgradeneeded = event => { 
  const db = event.target.result;
  const store = db.createObjectStore("myStore", { keyPath: 'id' }); // Create an object store in the database.
};

// Event handler for when the database is successfully opened.
openRequest.onsuccess = event => {
  const db = event.target.result;
  const transaction = db.transaction("myStore", "readwrite"); // Start a transaction on the "myStore" object store with readwrite access.
  const store = transaction.objectStore("myStore");
  store.add({ id: 1, value: "value" }); // Add data to the store. The object must include the keyPath property.
};

In summary, IndexedDB is a powerful tool for web applications requiring significant, structured client-side storage with the ability to perform complex queries. However, for simpler storage needs or applications that rely heavily on immediate consistency and server-side processing, other storage solutions might be more suitable.