Sub topic 9
Where structuredClone Is Available
Earlier chapters showed what structuredClone copies and what it drops. Before you rely on it in real code, check one more thing: whether the runtime that runs your code provides it. This chapter covers which browsers and server runtimes have it, why some environments still lack it, how to detect it safely, and what to use when it is missing.
This chapter assumes you know how to run code in Node.js or a browser console, you are comfortable with try/catch, and you have read the earlier chapters on what structuredClone does.
structuredClone Comes From the Host, Not the Language
structuredClone is not part of ECMAScript, the specification that defines the JavaScript language itself. The WHATWG HTML Standard defines it, the same document that defines setTimeout, postMessage and window. A host is the environment that embeds a JavaScript engine and adds its own globals. Browsers, Node.js, Deno and Bun are all hosts.
This has two practical effects:
- A JavaScript engine alone does not give you
structuredClone. Each host must expose it, so availability depends on the host and its version, not on the ECMAScript version you target. - Tools that think only in ECMAScript terms do not cover it. Setting TypeScript's
targettoES2022, or telling a transpiler which ES version to emit, does not addstructuredCloneand does not declare its type.
The structured clone algorithm itself is older than the function. Browsers used it internally for years to power postMessage and IndexedDB. The global structuredClone() function, which makes that algorithm directly callable, arrived in 2021 and 2022.
Browser and Runtime Support
The table lists the first version of each major environment that exposes structuredClone as a global.
| Environment | First version with `structuredClone` | Released |
|---|---|---|
| Firefox | 94 | November 2021 |
| Chrome | 98 | February 2022 |
| Edge (Chromium) | 98 | February 2022 |
| Safari (macOS and iOS) | 15.4 | March 2022 |
| Node.js | 17.0.0 (first LTS line: 18) | October 2021 |
| Deno | 1.14 | September 2021 |
| Bun | available in 1.0 and later | 2023 |
| Cloudflare Workers | supported | n/a |
Safari 15.4 was the last of the major browsers to ship it. Web tooling uses the label "Baseline Widely available" for features that have worked in all major browsers for at least 30 months, and structuredClone reached that status in 2024. In a browser, it is also available inside Web Workers and Service Workers, not only on window.
Environments That Commonly Lack It
Most production failures come from environments that are not obviously "old browsers".
Legacy Node.js
Node.js 16 and earlier have no global structuredClone. Those versions are past end-of-life, but they still turn up in long-lived CI images, Lambda functions pinned to an old runtime, and Docker base images nobody has rebuilt. Run node --version in the same environment that runs your code, not on your laptop.
Test environments that simulate a browser
Test runners such as Jest can run tests inside a simulated DOM provided by jsdom. That environment builds its own global object, and older versions of jsdom did not define structuredClone on it, even when the Node.js process underneath had one. A test can then fail with ReferenceError: structuredClone is not defined while the same code works in a real browser and in plain Node.js.
Common fixes:
- Upgrade the test environment to a version that exposes it.
- Load a polyfill in a setup file (covered below).
- Use the Node environment instead of jsdom for tests that do not need the DOM.
Other embedded engines
Hosts that embed an engine without implementing web APIs may not provide it. Examples include some mobile app runtimes, scripting hosts inside desktop applications, and minimal engines used in IoT or plugin systems. Check that host's documentation and don't assume.
Type checking without runtime support
TypeScript declares structuredClone in its DOM library and in @types/node for Node.js 17 and later. A Node project whose lib setting omits DOM and that uses old Node type definitions gets Cannot find name 'structuredClone' at compile time. The opposite case is more dangerous. Including DOM makes the type checker accept the call even when the code will run on Node.js 16, where it then fails at runtime. Types describe what you declared, not what the runtime has.
Detecting structuredClone Safely
Feature detection means checking for a capability at runtime instead of guessing from version numbers. The standard check uses typeof:
function deepCopy(value) {
if (typeof structuredClone === 'function') {
return structuredClone(value);
}
throw new Error('structuredClone is not available in this runtime');
}
console.log(deepCopy({ when: new Date(0) }).when instanceof Date); // true where supportedUse typeof because it is the only operator that does not throw on an undeclared identifier. The obvious alternative breaks on exactly the runtimes you are trying to detect:
// Wrong: throws ReferenceError where structuredClone was never declared
// if (structuredClone) { ... }
// Safe: typeof returns 'undefined' for undeclared identifiers
console.log(typeof structuredClone);
// Also safe: reading a missing property returns undefined
console.log(typeof globalThis.structuredClone);globalThis refers to the global object in every modern host, whether that is window, self in a worker, or Node's global. Reading a property from it gives undefined instead of throwing. globalThis is itself newer than ES2020, so very old engines may not have it either.
Do the check once and keep the result. You don't need to test on every call:
const hasStructuredClone = typeof globalThis.structuredClone === 'function';
export function deepCopy(value) {
if (!hasStructuredClone) {
throw new Error('structuredClone is not available in this runtime');
}
return globalThis.structuredClone(value);
}Fallbacks When It Is Missing
Node.js: the v8 module
Node.js has shipped the node:v8 module with serialize and deserialize since version 8. They use V8's value serializer, the same machinery that underlies structured cloning, so a round-trip through them keeps Date, Map, Set, typed arrays and circular references.
// Save as copy.mjs and run with: node copy.mjs
import v8 from 'node:v8';
function deepCopy(value) {
if (typeof globalThis.structuredClone === 'function') {
return globalThis.structuredClone(value);
}
return v8.deserialize(v8.serialize(value));
}
const original = { when: new Date(0), ids: new Set([1, 2]) };
original.self = original;
const copy = deepCopy(original);
console.log(copy.when instanceof Date); // true
console.log(copy.ids.has(2)); // true
console.log(copy.self === copy); // trueThe fallback is close to structuredClone but not identical:
- When it meets a value it can't serialize, such as a function, it throws a plain
Errorrather than aDOMExceptionnamedDataCloneError. Code that checkserr.name === 'DataCloneError'will not match. - It has no
transferoption. - It goes through a
Buffer, so it allocates the whole serialized form in memory before decoding it.
Polyfills for browsers and test setups
A polyfill is code that adds a missing standard API so that later code can use it as if it were native. Two widely used options:
- core-js installs a global
structuredClonewhen one is missing. Import it once, early in your entry point or test setup file. - @ungap/structured-clone exports a function you call directly, and it does not touch the global object.
// Option 1: install the global if missing (npm install core-js)
import 'core-js/actual/structured-clone';
const a = structuredClone({ when: new Date(0) });
console.log(a.when instanceof Date); // true// Option 2: use an explicit function (npm install @ungap/structured-clone)
import structuredClone from '@ungap/structured-clone';
const b = structuredClone({ ids: new Set([1, 2]) });
console.log(b.ids.has(1)); // truePolyfills run in ordinary JavaScript. They cannot reach host internals, so they can't truly detach an ArrayBuffer for transfer, and they may not support every platform type a browser supports natively. They cover the common cases: plain objects, arrays, Date, RegExp, Map, Set, typed arrays and cycles. When using one, test the exact data shapes you clone.
Bundlers and transpilers
A transpiler such as Babel rewrites syntax, but it doesn't add missing globals unless you ask it to. With @babel/preset-env set to inject core-js polyfills based on usage and your browser targets, the build can include the structuredClone polyfill automatically. Without that setting, nothing is added. If old browsers are among your targets, check the built output or test in one of them. Don't assume the build handled it.
Checking Availability in Practice
A short checklist for a project:
- List every place your code runs: browsers, server runtimes, workers, test runners, CI images and serverless functions.
- Compare each one against the support table. For servers, read the version from the deployed environment.
- Run a one-line probe where you are unsure, for example
node -e "console.log(typeof structuredClone)". - If any target lacks it, choose one behavior and apply it everywhere: a polyfill, the
v8fallback on Node.js, or a clear error. - Make your TypeScript
liband@types/nodesettings match the runtimes you actually deploy to.
Exercise
A colleague writes const clone = structuredClone ? structuredClone : (v) => JSON.parse(JSON.stringify(v)); to support old runtimes. Name two problems with this line.
Show answer
First, reading the bare identifier structuredClone throws a ReferenceError in runtimes where it was never declared, so the check fails in exactly the environments it is meant to support. Use typeof structuredClone === 'function' or typeof globalThis.structuredClone === 'function' instead. Second, the JSON fallback silently changes results: Dates become strings, undefined properties disappear, NaN becomes null, Maps and Sets become empty objects, and circular references throw. The same call would return differently shaped data on different runtimes.
Exercise
Your code works in Chrome and in node app.js on Node.js 20, but a Jest test using the jsdom environment fails with "structuredClone is not defined". Why can this happen, and what are two ways to fix it?
Show answer
structuredClone is a host API. The jsdom test environment builds its own simulated browser global object, and older jsdom versions did not define structuredClone on it, even though the Node.js process underneath has one. Fixes: upgrade the test environment to a version that exposes it, load a polyfill such as core-js/actual/structured-clone in a Jest setup file, or run tests that do not need the DOM in the Node test environment.
Exercise
You add the fallback v8.deserialize(v8.serialize(value)) for Node.js 16. An existing handler catches clone failures with if (err.name === 'DataCloneError'). What changes on Node.js 16 when someone passes an object containing a function?
Show answer
On Node.js 16 the v8 fallback throws an ordinary Error, not a DOMException named DataCloneError, so the name check does not match and the error escapes the handler. Either check for both cases, for example by catching any error from the clone call, or wrap the fallback so it rethrows a consistent error type.
Exercise
A TypeScript Node.js project has "lib": ["ES2022", "DOM"] and deploys to Node.js 16. It compiles cleanly. Will calls to structuredClone work in production?
Show answer
No. Including the DOM library only tells the type checker that a global structuredClone exists. It adds nothing at runtime. Node.js 16 has no global structuredClone, so calls throw a ReferenceError. Upgrade to Node.js 18 or later, or add a runtime check with a fallback.