Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 133 ยท The Runtime

The vm Module: Running Code in Separate Contexts

Learn how node:vm compiles and runs JavaScript in separate contexts, how globals, timeouts and errors behave, why vm is not a security sandbox, and what to use instead for untrusted code.

Every JavaScript program runs inside a realm: a set of built-in objects (Object, Array, Error, Promise) and a global object. Normally you only ever see one. The built-in node:vm module lets you create additional realms inside the same process, called contexts, and run code in them with a global object you choose. The result looks like a mini-program with its own global scope.

That is useful for things that really want a separate global scope: a REPL, a test runner that gives each file a clean environment, a template or configuration language that evaluates small expressions, a plug-in system that hands scripts a limited API. It is also dangerously easy to misuse, because vm looks like a sandbox and is not one. The most important part of this lesson is the last example, which shows how code escapes. Read the whole lesson before using vm on anything you did not write.

Running code: the basics

The simplest call is vm.runInNewContext(code, sandbox): create a new context whose global object is sandbox, run the code, and return the value of its last expression. A compiled vm.Script can be run many times in different contexts, so you pay the parsing cost once.

Node.js runInNewContext, Script and what the code can see

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A few details worth remembering. State persists in a context across calls, as the total and counter lines show. var and function declarations become properties of the global object (the sandbox), while let, const and class are kept in the context's hidden script scope. The context's built-ins are its own copies: the Array inside is not the Array outside.

Errors, line numbers and timeouts

Code from a string needs good error reporting, so vm accepts a filename (and lineOffset) that shows up in stack traces. And because user code can loop forever, runInContext and Script#runIn* accept a timeout in milliseconds.

Node.js Filenames in errors, timeouts and the instanceof trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the first trap: an error thrown inside a context is not instanceof the host's Error classes. That surprises code that checks error instanceof TypeError; compare error.name instead, or just rely on the message. Timeouts are the second lesson: timeout only measures the synchronous evaluation. If you give the code setTimeout or let promises run, the work continues after the call returns and no timeout applies. microtaskMode: 'afterEvaluate' makes promise callbacks run inside the evaluation so they count against the timeout, but you still must not hand the code timers.

Why vm is not a security sandbox

The Node.js documentation states it plainly: the vm module is not a security mechanism. Do not use it to run untrusted code. The reason is that contexts share a process, a heap and an event loop with the host. The boundary is made of object references, and any host object that reaches the inside leaks the host's realm along with it.

The classic escape is three words long: from any object that came from the host, climb to its constructor, then to constructor again, which is the host's Function. Calling that with source text builds a function in the host's scope, where process exists.

Node.js Escaping the vm sandbox through one host object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The attacker's code printed the host's Node version and process id, and could just as easily have called process.exit(), read files with process.binding, or required modules. Hardening tricks exist (null-prototype objects, passing only primitives, freezing prototypes), and each one has been bypassed in the past. You are in an arms race you do not want to be in.

What to use for untrusted code

Choose the isolation boundary to match the risk:

  • Trusted code in a different scope (your own plug-ins, a config file you control, a REPL): vm is fine, with a timeout.
  • Code from your users that must not crash you: a worker thread with resourceLimits isolates the heap and lets you terminate it. It does not stop the code from using require, so it is not a security boundary either.
  • Hostile code: a separate process with a restricted OS user, or better a container/VM or a service built for it. A purpose-built engine such as isolated-vm (separate V8 isolates, no shared references), a WebAssembly runtime (see WebAssembly in Node.js) or a hosted sandbox is the right answer. This website itself runs learners' code in a container with no network, which is the same principle.
  • Expressions only? Often you do not need a language at all. Parse a safe subset yourself (a small expression evaluator), or use a purpose-made library, instead of eval in any form. The same warning applies to eval, new Function and template engines that compile templates with them, so never put user text into a template source (see Template Engines: EJS).

Other things in the module

  • vm.compileFunction(code, params, options) compiles a function body and is faster and cleaner than wrapping code in new Function.
  • vm.measureMemory() reports how much memory contexts use, a rare diagnostics tool; see V8 and Memory.
  • new vm.Script(code, { cachedData }) reuses V8's compiled bytecode cache between runs, which is what some tools use to speed up start-up.
  • vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER and vm.SourceTextModule run ES modules in contexts. They are experimental and sit behind the --experimental-vm-modules flag.
  • vm.runInThisContext(code) runs code in the current realm, with access to globals but not to the local scope; the module system uses a version of it to run your files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does vm.runInNewContext('x + 1', { x: 4 }) return?

    The properties of the sandbox object are the global variables of the new context, so x is 4 and the last expression evaluates to 5.
  2. 2. Why is error instanceof TypeError false for an error thrown by code inside a vm context?

    Each context has its own set of built-ins. Compare error.name, or check the message, instead of instanceof.
  3. 3. Which statement about the timeout option is correct?

    timeout measures the time of the synchronous run. Work scheduled with timers continues afterwards unless you avoid exposing timers.
  4. 4. Why can code escape a vm context when you pass in a host object?

    api.constructor.constructor is the host's Function constructor. Calling it with code produces a function that runs in the host realm, where process and require are reachable.

Summary

  • node:vm runs JavaScript in separate contexts with their own globals; runInNewContext, createContext + runInContext, Script and compileFunction are the main tools.
  • The sandbox object's properties are the context's globals; var and functions land on it, let, const and class do not; contexts keep state between runs.
  • Errors from a context fail instanceof against host classes; give code a filename so stack traces are useful.
  • timeout covers synchronous evaluation only; microtaskMode: 'afterEvaluate' brings promise callbacks into it.
  • vm is not a security boundary: any host object leaks Function and with it process. For untrusted code use processes, containers, isolated isolates or Wasm.

Next: WebAssembly in Node.js.