~2 min read • Updated Dec 26, 2025
1. Introduction
The C++ Embedder API allows developers to run JavaScript inside C++ applications. These APIs are defined in src/node.h and rely on concepts from the V8 embedder API.
2. Setting up Per-Process State
- Parse Node.js CLI arguments.
- Initialize V8 requirements such as a
v8::Platforminstance. node::InitializeOncePerProcesssets up Node.js globally.MultiIsolatePlatform::Create()creates a V8 platform that supports Worker threads.
int main(int argc, char** argv) {
argv = uv_setup_args(argc, argv);
std::vector args(argv, argv + argc);
auto result = node::InitializeOncePerProcess(args, {...});
if (result->early_return() != 0) return result->exit_code();
auto platform = MultiIsolatePlatform::Create(4);
V8::InitializePlatform(platform.get());
V8::Initialize();
int ret = RunNodeInstance(platform.get(), result->args(), result->exec_args());
V8::Dispose();
V8::DisposePlatform();
node::TearDownOncePerProcess();
return ret;
}
3. Setting up Per-Instance State
- Each
node::Environmentis tied to onev8::Isolateand oneuv_loop_t. - An
ArrayBuffer::Allocatormust be provided (Node.js offers a default allocator). node::NewIsolate()creates and registers a new Isolate with Node.js hooks.
4. Running JavaScript Code
node::LoadEnvironment: Loads the Node.js environment and executes code.node::SpinEventLoop: Runs the event loop until completion.node::Stop: Explicitly stops the event loop.
MaybeLocalloadenv_ret = node::LoadEnvironment( env, "const publicRequire = require('node:module').createRequire(process.cwd() + '/');" "globalThis.require = publicRequire;" "require('node:vm').runInThisContext(process.argv[1]);"); if (loadenv_ret.IsEmpty()) return 1; exit_code = node::SpinEventLoop(env).FromMaybe(1); node::Stop(env);
Conclusion
The C++ Embedder API in Node.js is a powerful tool for executing JavaScript inside C++ applications. By managing per-process and per-instance state, and using APIs like LoadEnvironment and SpinEventLoop, developers can build hybrid applications that leverage both Node.js and C++ together.
Written & researched by Dr. Shahin Siami