ERR_VM_MODULE_ALREADY_LINKED
Node.jsERRORCriticalModuleHIGH confidence

vm.Module.link() called on an already-linked module

Production Risk

Low — typically only affects sandboxing or test runner infrastructure.

What this means

Thrown when vm.Module.link() is called on a module instance that has already been successfully linked. A vm.Module can only progress through its lifecycle (unlinked → linking → linked → evaluated) in one direction; calling link() again after it has already been linked is not allowed.

Why it happens
  1. 1Calling mod.link() a second time on the same module instance
  2. 2Sharing a module instance across multiple evaluation cycles and re-linking it
  3. 3A logic error in an async linking loop that processes the same module twice
How to reproduce

Triggered when link() is invoked on a vm.Module whose status is already "linked" or "evaluated".

trigger — this will error
trigger — this will error
import vm from 'node:vm';
const mod = new vm.SourceTextModule('export const x = 1;');
await mod.link(() => {});
await mod.link(() => {}); // second call throws

expected output

Error [ERR_VM_MODULE_ALREADY_LINKED]: Module has already been linked

Fix 1

Check module status before linking

WHEN When you are unsure whether a module has already been linked

Check module status before linking
if (mod.status === 'unlinked') {
  await mod.link(linker);
}

Why this works

Guarding on mod.status prevents redundant link() calls.

Fix 2

Create a fresh vm.Module instance for each evaluation

WHEN When you need to re-evaluate the same source

Create a fresh vm.Module instance for each evaluation
async function runModule(src) {
  const mod = new vm.SourceTextModule(src);
  await mod.link(linker);
  await mod.evaluate();
  return mod.namespace;
}

Why this works

Creating a new instance resets the lifecycle, avoiding the already-linked error.

Code examples
Triggerjs
import vm from 'node:vm';
const mod = new vm.SourceTextModule('export const x = 1;');
await mod.link(() => {});
await mod.link(() => {}); // second call throws  // this triggers ERR_VM_MODULE_ALREADY_LINKED
Handle in try/catchjs
try {
  // operation that may throw ERR_VM_MODULE_ALREADY_LINKED
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_VM_MODULE_ALREADY_LINKED') {
    console.error('ERR_VM_MODULE_ALREADY_LINKED:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_vm_module_already_linked(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Reuse vm.Module instances across multiple evaluation runs

Module instances are stateful and cannot be re-linked once they advance past the "unlinked" state.

Same error in other languages
Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors