Overview
Addons are dynamically-linked shared objects written in C++ that provide an interface between JavaScript and native libraries. They can be loaded as ordinary Node.js modules usingrequire().
Node-API (formerly N-API) is the recommended approach for building addons, providing ABI stability across Node.js versions.
Building Addons
There are three options for implementing addons:Node-API
Recommended approach with ABI stability
NAN
Native Abstractions for Node.js
Direct V8
Direct V8, libuv, and Node.js APIs
Key Components
When building addons without Node-API, you’ll work with:V8 JavaScript Engine
V8 JavaScript Engine
The C++ library providing JavaScript implementation. Access through
v8.h header file.libuv Event Loop
libuv Event Loop
Provides event loop, worker threads, and asynchronous behaviors. Cross-platform abstraction for system tasks.
Node.js Internal Libraries
Node.js Internal Libraries
C++ APIs including
node::ObjectWrap class.Hello World Example
A simple addon equivalent tomodule.exports.hello = () => 'world':
hello.cc
All Node.js addons must export an initialization function following the pattern above. There is no semicolon after
NODE_MODULE as it’s not a function.Node-API for Version Stability
Why Node-API?
Node-API is independent from the underlying JavaScript runtime (V8) and provides ABI stability across Node.js versions.ABI Stability
Modules compiled for one major version can run on later versions without recompilation
Node-API Properties
Using node-addon-api (C++ Wrapper)
The official C++ binding provides a cleaner interface:Context-Aware Addons
For environments requiring multiple addon instances (e.g., Electron):Using NODE_MODULE_INIT
Building with node-gyp
Create abinding.gyp configuration file:
binding.gyp
Best Practices
Use Node-API
Unless you need direct V8 access, always use Node-API for stability
Error Handling
Always check return status codes and handle errors appropriately
Memory Management
Be careful with object lifetimes and use proper cleanup hooks
Thread Safety
Avoid blocking the event loop - offload work to worker threads
Related Resources
Embedding Node.js
Embed Node.js in C++ applications
V8 Integration
Deep dive into V8 engine integration
Node.js Internals
Explore Node.js C++ core architecture
Node-API Docs
Official Node-API documentation