Sub topic 11
The Same Algorithm Behind postMessage and IndexedDB
structuredClone was not new when browsers added it. The structured clone algorithm had already been part of the web platform for years. Every time you send a message to a worker, store a record in IndexedDB, or push state onto the browser history, the platform runs this algorithm. structuredClone gave you a direct, synchronous way to call it.
This chapter assumes you have read the earlier chapters on supported types, DataCloneError, lost metadata and the transfer option. It also assumes you know the basics of Web Workers or Node.js worker_threads and can read callback-style asynchronous code. What you learned about structuredClone carries over to all of these APIs. This chapter shows where it applies and which details differ.
One Algorithm, Two Halves
The specification splits structured cloning into two steps:
- Serialize: walk the value graph and turn it into an internal, engine-independent record. This step throws
DataCloneErroron functions, DOM nodes and other unsupported values. - Deserialize: build fresh objects from that record, possibly in a different realm. A realm is a separate JavaScript global environment, such as a worker, an iframe or a later page load reading from disk.
structuredClone(value) runs both steps immediately, one after the other, in the same realm. The other APIs split the steps across time or space. postMessage serializes in the sender and deserializes in the receiver. IndexedDB serializes when you write and deserializes each time you read.
Two practical consequences follow from this split:
- Errors are synchronous at the sender.
postMessageandput()throw at the call site. You do not get a rejected promise or an error event. Wrap the call itself intry/catch. - The snapshot is taken at call time. Anything you change after the call returns is not part of the message or the stored record.
Messaging: Workers, Windows and Channels
A worker round trip in the browser
The example below runs in a browser console on an ordinary web page. Some pages block Blob-URL workers through their Content Security Policy, so open about:blank if it fails. The worker reports what it received.
const workerSource = `
self.onmessage = (event) => {
const data = event.data;
self.postMessage({
isDate: data.when instanceof Date,
idCount: data.ids.size,
bytes: data.buffer.byteLength
});
};
`;
const url = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));
const worker = new Worker(url);
worker.onmessage = (event) => {
console.log(event.data); // { isDate: true, idCount: 3, bytes: 16 }
worker.terminate();
URL.revokeObjectURL(url);
};
const payload = {
when: new Date(),
ids: new Set([1, 2, 3]),
buffer: new ArrayBuffer(16)
};
worker.postMessage(payload, [payload.buffer]);
payload.ids.add(4); // too late: the worker still sees 3 ids
console.log(payload.buffer.byteLength); // 0, the buffer was transferredThe Date and Set arrive with their types intact. The Set edit made after postMessage never reaches the worker. The second argument is the transfer list, which works the same way as structuredClone's { transfer } option. Worker.postMessage accepts both forms: an array, or { transfer: [...] }.
Errors happen at the sender
const { port1, port2 } = new MessageChannel();
try {
port1.postMessage({ handler() {} });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}
port1.close();
port2.close();This runs in browsers and in Node.js 15 and later, where MessageChannel is a global. Nothing was queued, so the receiving port never sees a partial message.
The old deep-copy trick
Before structuredClone existed, developers deep-copied values by sending them through a MessageChannel to themselves. It still works, which shows that both paths run the same algorithm:
function cloneViaChannel(value) {
return new Promise((resolve) => {
const { port1, port2 } = new MessageChannel();
port2.onmessage = (event) => {
resolve(event.data);
port1.close();
port2.close();
};
port1.postMessage(value);
});
}
const node = { name: 'root', when: new Date(0) };
node.self = node;
cloneViaChannel(node).then((copy) => {
console.log(copy.self === copy); // true
console.log(copy === node); // false
console.log(copy.when instanceof Date); // true
});The circular reference survives and the Date stays a Date, just as with structuredClone. The trick is asynchronous and allocates a channel for every copy. Replace it with structuredClone wherever you find it.
Node.js worker_threads
Node's worker_threads messaging uses the HTML structured clone algorithm, with a few Node-specific additions such as transferring MessagePort and FileHandle objects.
const { Worker } = require('node:worker_threads');
const worker = new Worker(`
const { parentPort } = require('node:worker_threads');
parentPort.once('message', (msg) => {
parentPort.postMessage({
type: msg.when.constructor.name,
keys: [...msg.meta.keys()]
});
});
`, { eval: true });
worker.once('message', (reply) => {
console.log(reply); // { type: 'Date', keys: [ 'a' ] }
worker.terminate();
});
worker.postMessage({ when: new Date(0), meta: new Map([['a', 1]]) });Node also provides v8.serialize() and v8.deserialize(), which expose V8's serializer as a Buffer. That serializer is closely related to structured clone but not identical, and its output format can change between V8 versions. Use it for short-lived data such as an in-process cache, not for long-term storage.
IndexedDB: Cloning to Disk
IndexedDB stores structured clones. When you call put() or add(), the value is serialized right away, during the call, and not when the transaction commits. Each get() deserializes a new copy.
Run this in a browser console:
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 item = { id: 1, when: new Date(0), tags: new Set(['a']) };
store.put(item);
item.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 = () => {
const stored = read.result;
console.log(stored.when instanceof Date); // true
console.log([...stored.tags]); // ['a']
console.log(stored === item); // false
db.close();
};
};
};The failed put() throws synchronously and creates no request. Because the code catches the error, the transaction continues and commits record 1. If you let the exception escape, the rest of your transaction code never runs.
Everything from the earlier chapter on lost metadata applies, and it lasts longer here because the data is persisted:
- A class instance comes back as a plain object. Store plain data, and rebuild instances when you read, for example with
Point.fromRecord(stored). - Getters are read once at
put()time and stored as plain values. - Symbol-keyed properties are dropped without any error.
Other Places the Algorithm Appears
| API | When it serializes | Transfer list | Where errors surface |
|---|---|---|---|
| `structuredClone(value, { transfer })` | Immediately, then deserializes | Yes | Thrown by the call |
| `Worker.postMessage` / `self.postMessage` | At the call | Yes | Thrown at the sender; `messageerror` at the receiver |
| `window.postMessage(msg, origin, transfer)` | At the call | Yes | Thrown at the sender; `messageerror` at the receiver |
| `MessagePort.postMessage` | At the call | Yes | Thrown at the sender; `messageerror` at the receiver |
| `BroadcastChannel.postMessage` | At the call | No | Thrown at the sender |
| IndexedDB `put()` / `add()` | At the call | No | Thrown by `put()` / `add()` |
| `history.pushState(state, ...)` / `replaceState` | At the call | No | Thrown by the call |
| Node `worker_threads` `postMessage(value, transferList)` | At the call | Yes | Thrown at the sender |
history.pushState is easy to forget. If you put a class instance into history state, history.state later returns a plain object. Browsers also limit the serialized size of history state; Firefox, for example, caps it at 16 MiB. Keep history state small and plain.
Performance and Design Notes
- Serialization cost scales with size. A message containing a 50 MB object graph is walked and copied in full on the sending thread, which can block the UI. If most of the payload is binary, put it in an
ArrayBufferand transfer it instead. - Transfer is only for messaging. IndexedDB,
BroadcastChannelandhistoryhave no transfer list. They always copy. - Send data, not behaviour. Because functions throw
DataCloneError, worker protocols usually send a plain command object such as{ type: 'resize', width, height }. The receiver decides which code to run. - Identity does not cross the boundary. Shared references are preserved within a single message. Two separate messages that contain the same object arrive as two unrelated copies.
Exercises
Exercise
You call worker.postMessage(state) and then immediately run state.count++. The worker logs event.data.count. Does it see the old or the new value, and why?
Show answer
It sees the old value. postMessage serializes the value synchronously during the call, so the record is complete before the increment runs. The worker deserializes that earlier snapshot.
Exercise
A store.put(record) call in an IndexedDB transaction throws DataCloneError because record contains a callback. Will the transaction's other writes still commit, and how should you fix the data?
Show answer
The throw happens synchronously and creates no request, so the transaction is not aborted by the failed put itself. If you catch the error, the other writes still commit. If the exception escapes your handler, any later writes in that code are skipped. Fix the data by removing the function before storing, for example by destructuring it out with const { callback, ...data } = record, and then reattach the behaviour when you read the record.
Exercise
You store new Point(3, 4) in IndexedDB and in history.pushState. What does each one return when read back, and what is a reliable way to get a Point instance again?
Show answer
Both return a plain object { x: 3, y: 4 } that is not a Point, has no getters and has lost its prototype. Store plain data on purpose, and rebuild the instance on read with a factory such as new Point(stored.x, stored.y) or a static Point.fromRecord(stored).
Exercise
Code in a library deep-copies values with a helper that posts them through a MessageChannel and resolves a promise. What should you replace it with, and what changes for its callers?
Show answer
Replace it with structuredClone(value). The cloning rules and results are the same, but the call is synchronous, so callers no longer need to await it. Callers that relied on it returning a promise must be updated, or the helper can wrap the result in Promise.resolve during the migration.