JavaScript EvalError Explained With Causes and Fixes
EvalError is a legacy error class that engines no longer throw for eval mistakes. See where it still appears, how eval errors look and safer alternatives.

EvalError has a name that promises an error from eval(), and the promise has not been true for a long time. The class is still in the language, because removing it would break code that references it, but no built-in operation throws it for a mistake inside evaluated code. A syntax error in a string passed to eval() is a SyntaxError, a missing variable is a ReferenceError, and so on. What EvalError does appear for today is a different situation: a runtime that has been told not to turn strings into code at all. This post explains the history in one paragraph, shows what errors from eval() really look like, then demonstrates the case where EvalError is real, which is code generation from strings being disabled, the way a strict Content Security Policy does in a browser. It covers how to detect that case, how direct and indirect eval() differ, and the alternatives to evaluating strings. The examples assume Node.js 24, and the messages are V8's.
What it is and what it is not
const error = new EvalError("custom message");
console.log(error instanceof EvalError, error instanceof Error);
console.log(error.name, "-", error.message);
console.log(Object.getPrototypeOf(EvalError) === Error);
console.log(String(error));
console.log(typeof EvalError);true true
EvalError - custom message
true
EvalError: custom message
functionThe last line prints function, because the class exists as a constructor. It is an ordinary error type with no extra fields: it behaves like Error with a different name. In the first edition of the language, eval() was specified to throw it in some misuse cases, such as calling it through an alias, and engines never did so consistently. The current specification keeps the class for compatibility and states that it is not used by the language. You will not see it from eval() itself.
What errors from eval really look like
const sources = ["1 +", "missingName + 1", "null.field", "(() => { throw new RangeError('own'); })()"];
for (const source of sources) {
try {
eval(source);
} catch (e) {
console.log(e.constructor.name, "-", e.message);
}
}SyntaxError - Unexpected end of input
ReferenceError - missingName is not defined
TypeError - Cannot read properties of null (reading 'field')
RangeError - ownEach failure is the error class that describes it. The text does not parse, so it is a SyntaxError. The code runs and fails, so the error is whatever the failing operation throws, as it would if the same code were in a file. None is an EvalError, so a handler written as catch (e) { if (e instanceof EvalError) ... } for these cases never runs. The correct handler for code of unknown shape catches Error and reports the type and message.
Where EvalError is real: code generation disabled
An engine can be configured to refuse to compile strings. V8 reports that refusal as an EvalError. Node.js exposes the option through vm contexts, and browsers reach it through Content Security Policy.
import vm from "node:vm";
const open = vm.createContext({});
const closed = vm.createContext({}, { codeGeneration: { strings: false, wasm: false } });
const code = `
const results = [];
for (const run of [() => eval("1 + 1"), () => new Function("return 2")(), () => (0, eval)("3")]) {
try {
results.push(run());
} catch (e) {
results.push(e.name + ": " + e.message);
}
}
results;
`;
console.log(vm.runInContext(code, open));
console.log(vm.runInContext(code, closed));[ 2, 2, 3 ]
[
'EvalError: Code generation from strings disallowed for this context',
'EvalError: Code generation from strings disallowed for this context',
'EvalError: Code generation from strings disallowed for this context'
]In the open context all three ways of building code from a string work. In the closed context, each of them throws an EvalError with the same message, because the restriction applies to eval(), to the Function constructor, and to indirect eval. The message wording is V8's. A browser with a strict Content Security Policy reports its own text, which names the policy, Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script. The shape is the same: name is EvalError, and the point is that the environment refused, not that your code was wrong.
Detecting whether evaluation is allowed
Libraries that compile templates or schemas with new Function() need a way to fall back when it is blocked.
const probe = `
(() => {
try {
return new Function("return 1")() === 1;
} catch (e) {
return e instanceof EvalError ? false : "other error";
}
})();
`;
console.log(vm.runInContext(probe, open));
console.log(vm.runInContext(probe, closed));true
falseThe probe tries the simplest possible compilation and treats an EvalError as "not allowed". It returns a different value for any other error, so a bug in the probe is not mistaken for a policy. A real library runs this once at load time, stores the result, and then chooses between a compiled fast path and an interpreted slow path. That is how template engines and validators keep working on pages with a strict policy, at some cost in speed. The check also works unchanged in browsers, where the EvalError comes from the policy and not from a vm context.
Direct and indirect eval
The two forms differ in which variables the string can see.
const local = "module value";
console.log(eval("local"));
try {
console.log((0, eval)("local"));
} catch (e) {
console.log(e.name, "-", e.message);
}
globalThis.shared = "global value";
console.log((0, eval)("shared"));module value
ReferenceError - local is not defined
global valueA direct call, written as eval(...), runs in the scope where it is written and can read local variables. An indirect call, such as (0, eval)(...), runs in the global scope, so it cannot see the module's own variables, which is why the second line fails. The distinction matters for security policies and for minifiers, which cannot rename variables that a direct eval might read. It is another reason code that uses eval() tends to be slow and hard to optimize.
Why evaluating strings is a last resort
Anything you pass to eval() runs with the full power of your program. If any part of the string comes from a user, a request or a file you do not control, the program does what the author of that text wants. There is no safe subset to which you can restrict it with a filter.
const operations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
};
function calculate(name, a, b) {
const operation = Object.hasOwn(operations, name) ? operations[name] : null;
if (operation === null) throw new RangeError(`unknown operation: ${name}`);
return operation(Number(a), Number(b));
}
console.log(calculate("add", "2", 3));
console.log(calculate("multiply", 4, 5));
try {
calculate("constructor", 1, 2);
} catch (e) {
console.log(e.name, "-", e.message);
}5
20
RangeError - unknown operation: constructorA dispatch table does the job that eval("2 + 3") would do, for the operations you chose to allow. The Object.hasOwn() check matters: without it, the name constructor would find Object.prototype.constructor through inheritance and call it. The inputs are converted with Number(), so a string cannot smuggle in anything but a number. This is longer than eval(), and every line of it is a decision you made on purpose.
Alternatives for common jobs
| You want to | Use instead of eval |
|---|---|
| Read data | JSON.parse() |
| Call a function by name | A lookup table of allowed functions |
| Read a property by a dynamic name | Bracket access: object[name] |
| Evaluate arithmetic from a user | A small parser, or a library built for expressions |
| Build a function from a template | A template function written as code, or a compile step at build time |
| Run untrusted code | A separate process or an isolate with no secrets, not eval() or vm |
| Load a module by name | Dynamic import() from an allow-list |
The vm module in Node.js is not a security boundary: its documentation says so, and code in a context can reach the host in several ways. Treat it as a convenience for running trusted code in a separate global scope, and not as a sandbox.
A mistake we hit: a handler that waits for the wrong error
function safeEval(source) {
try {
return { ok: true, value: eval(source) };
} catch (e) {
if (e instanceof EvalError) {
return { ok: false, reason: "blocked" };
}
throw e;
}
}
console.log(safeEval("2 * 3"));
try {
safeEval("2 *");
} catch (e) {
console.log("escaped the handler:", e.name);
}{ ok: true, value: 6 }
escaped the handler: SyntaxErrorThe author assumed that anything wrong with a string passed to eval() is an EvalError, so the handler rethrows everything else. The syntax error went right through it and crashed the caller. We wrote this in a tool that evaluated user formulas and tested it only with valid formulas. The fix is to decide what the function promises: either it returns a result object for all failures, catch (e) { return { ok: false, reason: e.name } }, or it documents that it throws, and lets the caller handle SyntaxError. The EvalError branch is useful only for the blocked case, and belongs next to the probe above.
Choosing between the responses
| You see | Do this |
|---|---|
An EvalError in a browser | Check the Content Security Policy; remove the eval or new Function call |
An EvalError in a vm context | The context disallows string compilation; run the code in an allowed context or remove it |
A SyntaxError from eval() | The string is not valid code; fix the string |
| A library fails under a strict policy | Use a build-time compiled version, or a library with an interpreter fallback |
| You want to evaluate user input | Parse it, never execute it |
Practical rules we follow
Do not use eval() or new Function() in application code. Where a dependency uses them, check that it has a policy-friendly mode before adopting it. Catch Error broadly around evaluated text, and report e.name, since the class tells you which kind of failure it was. Keep any probe for EvalError at startup, and not in a hot path. And never evaluate anything that crossed a trust boundary.
Where EvalError stops being the right diagnosis
It tells you the environment refused to compile text. It does not tell you what was wrong with the text, and for mistakes inside the text, the other error classes apply. It is rare in Node.js and appears mostly through vm options and the --disallow-code-generation-from-strings flag. And in browsers it is the sign of a policy that the page owner set on purpose, so the fix is to change your code, not to loosen the policy. The reference is in the MDN EvalError page and the ECMAScript specification.


