Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Messaging and Storage

Storage Patterns - onChanged, Quotas, Migrations

React to storage changes with storage.onChanged, keep every extension page in sync, avoid read-modify-write races, check quotas and migrate stored data between versions of your extension.

Saving data is the easy part. The hard parts come later: the popup must update when the options page changes a setting, two writes at once must not lose data, and version 2 of your extension must understand the data that version 1 saved. This lesson covers the patterns that solve those problems.

Reacting with storage.onChanged

chrome.storage.onChanged fires in every extension context (worker, popup, options page, content scripts) whenever any of them writes. That makes storage the simplest shared state bus: write in one place, react everywhere.

JavaScript
// real extension code
chrome.storage.onChanged.addListener((changes, areaName) => {
  if (areaName !== "sync") return;
  if (changes.theme) {
    applyTheme(changes.theme.newValue);   // oldValue is also available
  }
});

changes is an object keyed by the changed storage key, each with oldValue and newValue. A removed key has no newValue. The event does not fire for the context's own write only: it fires everywhere, including the writer, so keep handlers idempotent.

onChanged keeps two views in sync

Avoiding read-modify-write races

A classic bug: two parts read the same list, each adds an item, each writes back, and one item is lost.

JavaScript
// risky when two contexts run it at once
const { items = [] } = await chrome.storage.local.get("items");
items.push(newItem);
await chrome.storage.local.set({ items });

There is no transaction API, so reduce the risk:

  • Route all writes through one place (the service worker) and send it messages (see One-time messages).
  • Store each item under its own key (item:123) instead of one big array, so writes never overlap.
  • If you must update one shared value, serialise the writes with a small promise queue.
A promise queue serialises writes

Checking quotas

Each area has limits. You can ask how much you use:

JavaScript
const bytes = await chrome.storage.local.getBytesInUse(null);
console.log(`Using ${bytes} bytes`);
console.log(chrome.storage.sync.QUOTA_BYTES_PER_ITEM); // 8192

Writes that exceed a quota reject with an error, and chrome.runtime.lastError carries the message in callback style. Catch it and tell the user instead of failing silently:

JavaScript
try {
  await chrome.storage.sync.set({ bigNote });
} catch (e) {
  console.warn("Could not sync:", e.message);
  await chrome.storage.local.set({ bigNote }); // fall back to local
}

Large data (history, cached pages) belongs in local. For hundreds of thousands of records, use IndexedDB from the worker or an offscreen document; it is not limited to 10 MB. Add "unlimitedStorage" to permissions if you really need more local space.

Migrating data between versions

Your next release may rename a key or change a shape. Users will have old data, so version your data and migrate when the extension updates. Run migrations in runtime.onInstalled.

JavaScript
// service-worker.js (real extension code)
const SCHEMA = 2;

chrome.runtime.onInstalled.addListener(async ({ reason }) => {
  if (reason !== "update" && reason !== "install") return;
  const { schema = 1 } = await chrome.storage.local.get("schema");
  if (schema < 2) {
    const { notes = [] } = await chrome.storage.local.get("notes");
    // v1 stored strings, v2 stores objects
    const upgraded = notes.map((n) => typeof n === "string" ? { text: n, created: 0 } : n);
    await chrome.storage.local.set({ notes: upgraded });
  }
  await chrome.storage.local.set({ schema: SCHEMA });
});
A schema migration, step by step

Keep every migration small and ordered; never edit an old one after release. Defaults on read (get({ key: default })) cover new optional keys without a migration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which contexts does chrome.storage.onChanged fire after one page writes?

    All contexts of the extension receive the event, which makes storage a simple shared state channel.
  2. 2. Two contexts add items to the same stored array at the same moment. What can go wrong?

    Read-modify-write is not atomic. Funnel writes through one place, use one key per item or queue the writes.
  3. 3. Where is the best place to run a data migration for a new version?

    onInstalled fires once after the extension is installed or updated, before most other code needs the new data shape.
  4. 4. What should you do when sync.set rejects because of a quota?

    Quota errors are normal at the limits. Catch them and degrade gracefully.

Summary

  • storage.onChanged tells every extension context about writes: use it to keep views in sync.
  • Avoid read-modify-write races with one key per item, a single writer or a promise queue.
  • Check usage with getBytesInUse and handle quota errors.
  • Keep a schema number and migrate in runtime.onInstalled.

Next: The Permissions Model