Sub topic 11
The Same Algorithm Behind postMessage and IndexedDB
This chapter assumes you already know how structuredClone behaves, including which types it supports, why it throws DataCloneError, and how the transfer option detaches buffers. It also assumes you can run code in Node.js 15+ or a browser console. The IndexedDB example needs a browser.
structuredClone was not a new invention. Browsers had been running the structured clone algorithm for years inside other APIs. The global function, added in 2021–2022, gave developers direct access to an algorithm the platform already used. Before that, people deep-copied values by sending them through a MessageChannel and reading them back.
Where the Algorithm Runs
When you hand a value to one of these APIs, the platform serializes it into an internal format. Later it deserializes that format into a new value, sometimes in a different realm (a separate global environment such as a worker).
| API | When the copy is made | Transfer list allowed |
|---|---|---|
| `structuredClone(value)` | Immediately, same realm | Yes |
| `worker.postMessage`, `MessagePort.postMessage` | At the call, rebuilt in the receiver | Yes |
| `window.postMessage` (iframes, popups) | At the call, rebuilt in the target window | Yes |
| `BroadcastChannel.postMessage` | At the call, rebuilt in each listener | No |
| IndexedDB `put` / `add` | At the call, rebuilt on each read | No |
| `history.pushState(state, ...)` | At the call, rebuilt for `history.state` | No |
All of these follow the same rules you have already learned. The rows marked "No" for transfer use the storage form of the algorithm. That form also rejects values that only make sense inside one process, such as SharedArrayBuffer.
Messages Are Copies
A MessageChannel gives you two linked ports. It is available as a global in both Node.js and browsers, so you can try messaging without creating a worker file.
const { port1, port2 } = new MessageChannel();
const payload = { sent: new Date(0), ids: new Set([1, 2]) };
port2.onmessage = (event) => {
const data = event.data;
console.log(data === payload); // false
console.log(data.sent instanceof Date); // true
console.log([...data.ids]); // [1, 2]
port1.close();
};
port1.postMessage(payload);
payload.ids.add(3); // happens after serialization, so the receiver never sees 3
try {
port1.postMessage({ handler: () => {} });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}Notice two things in this example. The mutation after postMessage has no effect, because the snapshot was taken during the call. The function also fails synchronously at the sender, so you catch it where you send it and not in the receiver.
Transfer works the same way it does in structuredClone. You pass the transfer list as the second argument: worker.postMessage(buffer, [buffer]). This is the main reason the option exists. It lets you send a large image or audio buffer to a worker without copying its memory.
IndexedDB Stores Clones
IndexedDB stores the serialized form of each record. Reading a record deserializes a fresh copy, so Date, Map, Set, typed arrays and Blob values come back with their real types. JSON-based storage such as localStorage cannot do that.
const request = indexedDB.open('clone-demo', 1);
request.onupgradeneeded = () => {
request.result.createObjectStore('items', { keyPath: 'id' });
};
request.onsuccess = () => {
const db = request.result;
const tx = db.transaction('items', 'readwrite');
const store = tx.objectStore('items');
const record = { id: 1, created: new Date(0), tags: new Set(['a']) };
store.put(record);
record.tags.add('b'); // after put: not stored
try {
store.put({ id: 2, onSave: () => {} });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}
tx.oncomplete = () => {
const read = db.transaction('items').objectStore('items').get(1);
read.onsuccess = () => {
console.log(read.result.created instanceof Date); // true
console.log([...read.result.tags]); // ['a']
db.close();
};
};
};The losses from the earlier chapters apply here too. A stored class instance comes back as a plain object. If your app keeps User instances in IndexedDB, you have to rebuild them after reading, for example with Object.assign(new User(), record) or a factory function.
Exercise
A page calls worker.postMessage(state) and then immediately sets state.count = 0. The worker logs event.data.count and sees the old value, 5. Why, and what would happen if state also contained a method?
Show answer
postMessage serializes state synchronously during the call, so the worker receives a snapshot taken before count was changed. If state contained a function, postMessage would throw a DataCloneError at the sender during that call, and no message would be sent.
Exercise
Why can you pass a transfer list to worker.postMessage but not to IndexedDB's put?
Show answer
Transferring moves memory to another live realm and detaches the original. IndexedDB uses the storage form of the algorithm, which writes a durable serialized copy that may be read many times later. No receiver exists to take ownership of the memory, so transfer has no meaning there.