# Node.js API compatibility - VM

The `vm` module in Node.js provides a way to execute JavaScript code within a virtual machine context. This allows developers to run code in a sandboxed environment, which can be useful for various applications, such as executing user-generated code, testing, or isolating code execution from the main application. This module is available in the Azion Runtime through Node.js compatibility, where a common use case is evaluating dynamic snippets or templates inside a function while keeping them separated from the surrounding scope.

The example below shows how to use the `vm` module in a function:

```javascript
/**
 * An example of using Node.js VM API in an Azion Function.
 * Support:
 * - Partially supported (Extended by library `vm-browserify`)
 * @module runtime-apis/nodejs/vm/main
 * @example
 * // Execute with Azion Bundler:
 * npx edge-functions build
 * npx edge-functions dev
 */
import vm from "node:vm";

// Set a global variable because bundler esbuild minify the code and rename the variable.
globalThis.contextVar = "initial value";

/**
 * An example of using the Node.js VM API in an Azion Function.
 * @param {*} event
 * @returns {Promise<Response>}
 */
const main = async (event) => {
  const vmResult = vm.runInThisContext(
    'globalThis.contextVar = "change by vm";'
  );
  console.log(
    `vmResult: '${vmResult}', globalThis.contextVar: '${globalThis.contextVar}'`
  );
  return new Response("Done!", { status: 200 });
};

export default main;w
```

## Related resources

- [Node.js `vm` documentation](https://nodejs.org/api/vm.html)