Skip to content

Storage Adapters

The Course
•
17 min study

Storage is a dependency, not a guarantee

The capstone intentionally keeps its saved books in memory. Rerunning or reloading starts fresh. To add persistence, inject a storage object with getItem and setItem rather than calling localStorage throughout the model. This creates one place to choose failure behavior.

On a normal origin, localStorage stores strings synchronously. Reads or writes may throw because of browser policy, quota, or unavailable storage. Parsed saved text may be invalid JSON or an obsolete schema. Validate restored data before putting it into state. An inaccessible store is different from a missing key, even if both lead to an empty initial list; communicate when saving is unavailable.

The isolated webpage labs do not have same-origin storage privileges. Use the controlled adapter below to practice. The downloadable HTTP-served project is a suitable place to add an actual localStorage adapter. Do not weaken the lab sandbox to make storage work.

Decide whether a failed write should undo the user's in-memory action. For a reading queue, keeping the action and showing "not saved across reloads" is reasonable. For a payment workflow it would be an entirely different contract. A fallback must be visible; silent persistence failure creates false confidence.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
function writeSaved(storage, books) {
  try {
    storage.setItem("reading-queue:v1", JSON.stringify(books));
    return true;
  } catch {
    return false;
  }
}

const memory = new Map();
const storage = {
  setItem(key, text) {
    memory.set(key, text);
  }
};

console.log(writeSaved(storage, [{ id: "js", title: "Notes" }]));
console.log(JSON.parse(memory.get("reading-queue:v1"))[0].id);
console.log(
  writeSaved(
    {
      setItem() {
        throw new Error("Blocked");
      }
    },
    []
  )
);
Check your prediction
Text
true
js
false

The Map is a test adapter, not persistence across program runs. A false result should drive visible feedback at the UI boundary.

Distinguish missing storage from malformed storage

A storage adapter crosses two boundaries: the storage operation can fail, and retrieved text can fail parsing or validation. A missing key is a normal empty state, while malformed text is a recovery decision. Neither should crash unrelated interaction unless the application's policy explicitly requires it.

Version the storage key when its shape changes. Validate parsed records before exposing them as trusted application data. A JSON array alone is not enough evidence that it contains valid saved books.

Distinguish missing storage from malformed storage: trace JavaScript
function read(storage) {
  const text = storage.getItem("queue:v1");

  if (text === null) {
    return [];
  }

  const value = JSON.parse(text);

  if (!Array.isArray(value)) {
    throw new Error("Expected list");
  }

  return value;
}

console.log(
  read({
    getItem() {
      return null;
    }
  }).length
);
console.log(
  read({
    getItem() {
      return "[]";
    }
  }).length
);
Check your prediction
Text
0
0

Both cases produce an empty array here, but they arrived through different paths. A later migration policy may need to distinguish absent data from existing serialized data.

Distinguish missing storage from malformed storage: contrast JavaScript
function write(storage, value) {
  try {
    storage.setItem("queue:v1", JSON.stringify(value));
    return true;
  } catch {
    return false;
  }
}

const storage = {
  setItem() {
    throw new Error("Quota exceeded");
  }
};

console.log(write(storage, [{ id: "a" }]));
Check your prediction
Text
false

A storage write can fail even when serialization succeeds. The boolean gives the caller a recovery choice. It should not be converted into a claim that persistence succeeded.

Try the rule on new inputs

Test missing key, valid empty list, malformed JSON, wrong-shaped JSON and blocked writes. Decide which cases recover to empty and which show a warning. Keep the currently displayed saved state intact when a write fails.

Build it yourself

Exercise

Load saved books and say what went wrong

Write loadSaved(storage) for the key "saved-books". It always returns { books, problem } and never throws. problem is null when all is well, including a first visit with nothing saved (getItem returns null). Otherwise books is empty and problem explains which stage failed: "storage unavailable" when getItem throws, "saved data is not JSON" when parsing fails, and "saved data rejected: " plus the decoder's message when the records are invalid. Use the supplied decodeBooks. The five test stores should print:

Text
valid: 1 book(s), ok
empty: 0 book(s), ok
blocked: 0 book(s), storage unavailable
corrupt: 0 book(s), saved data is not JSON
old schema: 0 book(s), saved data rejected: Each book needs an id and title
Your working space JavaScript
function decodeBooks(value) {
  if (!Array.isArray(value)) {
    throw new Error("Expected a list of books");
  }
  return value.map(item => {
    if (
      item === null ||
      typeof item !== "object" ||
      typeof item.id !== "string" ||
      typeof item.title !== "string" ||
      item.title.trim() === ""
    ) {
      throw new Error("Each book needs an id and title");
    }
    return { id: item.id, title: item.title.trim() };
  });
}

function loadSaved(storage) {
  // Return { books, problem }: problem is null when nothing is wrong.
  return { books: [], problem: null };
}

const stores = {
  valid: { getItem: () => '[{"id":"js","title":" Notes "}]' },
  empty: { getItem: () => null },
  blocked: {
    getItem() {
      throw new Error("SecurityError");
    }
  },
  corrupt: { getItem: () => "[{oops" },
  "old schema": { getItem: () => '[{"id":"js","name":"Notes"}]' }
};

for (const [name, storage] of Object.entries(stores)) {
  const { books, problem } = loadSaved(storage);
  console.log(`${name}: ${books.length} book(s), ${problem ?? "ok"}`);
}
Hint 1: the idea

There are three operations that can fail (read, parse, decode) plus one normal "nothing here" case. Giving each operation its own try lets the catch know exactly which stage failed, so the message can say so.

Hint 2: a first step

Start with the read: put only storage.getItem("saved-books") inside a try, and return the "storage unavailable" result from its catch. Then handle null before parsing. Run it: "blocked" and "empty" are now right, and "corrupt" stops the program with a SyntaxError, which is your next stage.

Show one solution
JavaScript
function decodeBooks(value) {
  if (!Array.isArray(value)) {
    throw new Error("Expected a list of books");
  }
  return value.map(item => {
    if (
      item === null ||
      typeof item !== "object" ||
      typeof item.id !== "string" ||
      typeof item.title !== "string" ||
      item.title.trim() === ""
    ) {
      throw new Error("Each book needs an id and title");
    }
    return { id: item.id, title: item.title.trim() };
  });
}

function loadSaved(storage) {
  let text;
  try {
    text = storage.getItem("saved-books");
  } catch {
    return { books: [], problem: "storage unavailable" };
  }

  if (text === null) {
    return { books: [], problem: null }; // first visit: nothing saved yet
  }

  let value;
  try {
    value = JSON.parse(text);
  } catch {
    return { books: [], problem: "saved data is not JSON" };
  }

  try {
    return { books: decodeBooks(value), problem: null };
  } catch (error) {
    return { books: [], problem: `saved data rejected: ${error.message}` };
  }
}

const stores = {
  valid: { getItem: () => '[{"id":"js","title":" Notes "}]' },
  empty: { getItem: () => null },
  blocked: {
    getItem() {
      throw new Error("SecurityError");
    }
  },
  corrupt: { getItem: () => "[{oops" },
  "old schema": { getItem: () => '[{"id":"js","name":"Notes"}]' }
};

for (const [name, storage] of Object.entries(stores)) {
  const { books, problem } = loadSaved(storage);
  console.log(`${name}: ${books.length} book(s), ${problem ?? "ok"}`);
}
Text
valid: 1 book(s), ok
empty: 0 book(s), ok
blocked: 0 book(s), storage unavailable
corrupt: 0 book(s), saved data is not JSON
old schema: 0 book(s), saved data rejected: Each book needs an id and title

Each try wraps one operation, so a catch can name its stage without inspecting error types. text and value are declared with let outside the try blocks so the next stage can use them. A missing key is checked with === null before parsing, because JSON.parse(null) would quietly return null and the decoder would then report a normal first visit as rejected data. "old schema" is valid JSON whose records use name instead of title; only the decoder can catch that, which is why parsing successfully is not the same as loading successfully. A single try around all three steps would turn every case into the same vague message.

Explain before moving on

What does a versioned key help you change later? Why is a Map double not proof that localStorage is available?

Was this article helpful?

Your response is saved on this device.