Skip to content
jshacks.dev
Fundamentals

What Is a Realm in JavaScript and Why instanceof Breaks

A realm has its own built-in objects, so an array from an iframe or vm context fails instanceof Array. See the checks that work across realms.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and TypeScript logos.

A function receives an array from another place, checks value instanceof Array and says no. The value is an array. It prints as one, it has every array method and Array.isArray() agrees. The explanation is that there is more than one Array in the program, and the value belongs to the other one. This happens in three everyday places: pages with iframes, programs that use worker threads or Node.js's vm module, and test runners that run each file in a fresh context. The unit that separates the copies is called a realm, and understanding it explains instanceof failures, a family of "works in my test, fails in the sandbox" bugs and the reason several checks in the language are written the way they are. This post defines a realm, reproduces the failure with node:vm, shows which checks survive the boundary and which do not, and covers how data crosses it. Output is from Node.js 24 as an ES module. The chain that instanceof walks is described in the post on the prototype chain, and the global object in the post on globalThis.

What a realm is

The specification defines a realm as a set of intrinsic objects, the built-in constructors and prototypes, along with a global environment. Each realm has its own Object, Array, Function, Error, Date, Map, Promise and so on. They are separate copies with the same names. Code running in a realm uses that realm's copies when it writes [] or new Error().

WhereNew realm created by
Browser tabThe page itself
<iframe>The frame's document
Web worker, service workerThe worker
Node.js worker threadThe worker
Node.js vm.createContext() and vm.runInNewContext()The context
Test runners that isolate files (Jest, Vitest in some modes)Each test file

Reproducing the failure

node:vm creates a new context in the same process, which makes the effect easy to see without a browser.

JavaScript
import vm from "node:vm";

const foreign = vm.runInNewContext("[1, 2, 3]");
const local = [1, 2, 3];

console.log(foreign instanceof Array, local instanceof Array);
console.log(Array.isArray(foreign), foreign.length, foreign.map((n) => n * 2));
console.log(foreign.constructor === Array, foreign.constructor.name);
console.log(Object.getPrototypeOf(foreign) === Array.prototype);
console.log(Object.prototype.toString.call(foreign));
console.log(JSON.stringify(foreign), [...foreign]);
Text
false true
true 3 [ 2, 4, 6 ]
false Array
false
[object Array]
[1,2,3] [ 1, 2, 3 ]

The foreign array behaves as an array in every way except instanceof Array, which asks whether the local Array.prototype is in its chain, and it is not, because the foreign array's prototype is that realm's own Array.prototype. The constructor is also a different function with the same name. Array.isArray() and Object.prototype.toString.call() do not use the chain: they inspect the object's internal class, and report the truth.

The same for other built-ins

Every built-in constructor has the same problem, and the effect is most visible for errors and dates, where instanceof is the common check.

JavaScript
import vm from "node:vm";
import { types } from "node:util";

const foreignError = vm.runInNewContext("new TypeError('from elsewhere')");
const foreignDate = vm.runInNewContext("new Date(0)");
const foreignMap = vm.runInNewContext("new Map([[1, 2]])");
const foreignRegExp = vm.runInNewContext("/ab+c/gi");
const foreignObject = vm.runInNewContext("({ a: 1 })");

console.log(foreignError instanceof Error, foreignError instanceof TypeError);
console.log(foreignDate instanceof Date, types.isDate(foreignDate));
console.log(foreignMap instanceof Map, types.isMap(foreignMap), foreignMap.get(1));
console.log(foreignRegExp instanceof RegExp, types.isRegExp(foreignRegExp));
console.log(foreignObject instanceof Object, Object.getPrototypeOf(foreignObject) === Object.prototype);
console.log(Object.prototype.toString.call(foreignError), foreignError.name, foreignError.message);
Text
false false
false true
false true 2
false true
false false
[object Error] TypeError from elsewhere

The foreign error is not an instance of the local Error or TypeError, and neither are the date, the map and the regular expression. Even a plain object fails instanceof Object, and its prototype is not the local Object.prototype. The checks that work are the type predicates in node:util, the tag from Object.prototype.toString.call() and ordinary property access, since the object itself works normally. A catch block that tests error instanceof TypeError will miss an error thrown by code in another realm, which is a real way to lose error handling in a plugin system or a sandbox.

What works across realms

Anything that reads an internal slot, a symbol or a plain property works. Anything that compares against a local constructor does not.

JavaScript
import vm from "node:vm";

const ctx = vm.createContext({});
const run = (code) => vm.runInContext(code, ctx);

const foreignSymbol = run("Symbol('id')");
const sharedSymbol = run("Symbol.for('app.session')");
const iterator = run("[10, 20][Symbol.iterator]()");

console.log(foreignSymbol === Symbol("id"), typeof foreignSymbol);
console.log(sharedSymbol === Symbol.for("app.session"));
console.log(run("Symbol.iterator") === Symbol.iterator);
console.log([...run("[7, 8]")], Array.from(run("new Set([1, 2])")));
console.log(Number.isInteger(run("42")), typeof run("'text'"), run("null"));
console.log(typeof run("typeof process"), run("typeof process"));
console.log(await run("Promise.resolve('later')"));
Text
false symbol
true
true
[ 7, 8 ] [ 1, 2 ]
true string null
string undefined
later

A symbol from Symbol() is unique in its realm and unequal everywhere else, but Symbol.for() goes through a registry shared by every realm in the agent, so it returns the same symbol, and well-known symbols such as Symbol.iterator are shared too. Iteration works across realms because it uses symbols and not constructors. Primitives have no realm, so numbers and strings behave identically. A new context does not have Node.js globals such as process, because a fresh realm starts with only the language's built-ins. And await works on a foreign promise, since it only needs a then method.

Checks that survive the boundary

For each built-in, the portable check avoids instanceof.

JavaScript
import vm from "node:vm";
import { types } from "node:util";

const samples = {
  array: vm.runInNewContext("[]"),
  error: vm.runInNewContext("new Error('x')"),
  date: vm.runInNewContext("new Date(0)"),
  regexp: vm.runInNewContext("/x/"),
  map: vm.runInNewContext("new Map()"),
  plain: vm.runInNewContext("({})"),
  func: vm.runInNewContext("(function () {})"),
};

const tag = (value) => Object.prototype.toString.call(value).slice(8, -1);

for (const [label, value] of Object.entries(samples)) {
  console.log(label.padEnd(7), tag(value).padEnd(9), typeof value);
}

console.log(Array.isArray(samples.array), types.isNativeError(samples.error), typeof samples.func === "function");
console.log(samples.plain instanceof Object, Object.getPrototypeOf(Object.getPrototypeOf(samples.plain)));
Text
array   Array     object
error   Error     object
date    Date      object
regexp  RegExp    object
map     Map       object
plain   Object    object
func    Function  function
true true true
false null

The tag from Object.prototype.toString.call() named each type correctly, and typeof reported "function" for the foreign function, since it checks internal callability. Array.isArray() is the array check, util.types.isNativeError() the Node.js check for errors, and a duck-typing test, "has a message and a stack", the portable one in browsers. A newer predicate, Error.isError(), was added in ES2026 for exactly this, and it is present in Node.js 24.1, so in code that targets a current runtime it is the simplest check, as covered in the post on ES2026. A plain object from another realm has its own Object.prototype at the end of its chain, which is itself an object whose prototype is null.

A pattern that is safe in shared code is to compare the tag and to prefer capability checks. For a class of your own, a brand check with a private field, #field in value, works across realms as long as the class itself was loaded once, as covered in the post on private class fields.

Data crossing a worker boundary

A worker thread is a separate realm, and values sent with postMessage are copied by the structured clone algorithm into the receiving realm. The receiver's instanceof works on what arrives.

JavaScript
import { Worker } from "node:worker_threads";

const source = `
  const { parentPort } = require("node:worker_threads");
  const array = [1, 2, 3];
  parentPort.postMessage({
    inWorker: array instanceof Array,
    list: array,
    when: new Date(0),
    tags: new Set(["a"]),
  });
`;

const worker = new Worker(source, { eval: true });

const message = await new Promise((resolve, reject) => {
  worker.once("message", resolve);
  worker.once("error", reject);
});

console.log(message.inWorker);
console.log(Array.isArray(message.list), message.list instanceof Array);
console.log(message.when instanceof Date, message.tags instanceof Set);
await worker.terminate();
Text
true
true true
true true

Inside the worker, instanceof Array is true for its own array. In the main thread, the message arrived as arrays, dates and sets of the main realm, so every instanceof check passes. This is the useful rule: data that crosses a boundary through messaging is rebuilt locally, and only objects that are shared by reference, as with vm or an iframe's contentWindow, keep their foreign prototypes. The post on structuredClone() describes the algorithm.

Where realms cause trouble

Three situations produce the bugs. Test frameworks that run code in a vm context, so that an error created in your code is not an instance of the test runner's Error, which breaks assertions like assert.throws(fn, TypeError) when a library passes the wrong realm's class. Plugin and sandbox systems, where code from a plugin returns arrays and errors that the host cannot recognize with instanceof. And browser pages that move nodes and arrays between frames, as in widget embeds.

The defense is to avoid instanceof on built-ins in code that may meet foreign values, and to use the predicates above. A library that must run in many environments often lists a helper isArray, isError, isDate and isPlainObject, built on the tag, and uses them everywhere.

Where this advice stops

A realm is not a security boundary by itself. Code in a vm context can reach the host through leaked objects, and the Node.js documentation says so plainly, so do not run untrusted code in one without a stronger isolation such as a separate process. And you will rarely meet a realm in an ordinary application: a single page, a single process, one set of built-ins. The knowledge pays off when something that should be an array says it is not.

Realms are defined in the specification under realms, and MDN's page on instanceof and the Node.js documentation for the vm module cover the behavior.

Taggedbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.