Node.js compatibility
When you write a Worker, you may need to import packages from npm ↗. Many npm packages rely on APIs from the Node.js runtime ↗, and will not work unless these Node.js APIs are available.
Cloudflare Workers provides a subset of Node.js APIs in two forms:
- As built-in APIs provided by the Workers Runtime
- As polyfills that Wrangler adds to your Worker’s code
You can view which APIs are supported using the Node.js compatability matrix ↗.
To enable both built-in runtime APIs and polyfills for your Worker, add the nodejs_compat_v2
compatibility flag to your wrangler.toml
:
To only enable built-in runtime APIs, add the nodejs_compat
compatibility flag to your wrangler.toml
:
The following APIs from Node.js are provided directly by the Workers Runtime. They are available when using nodejs_compat
or nodejs_compat_v2
:
- assert
- AsyncLocalStorage
- Buffer
- Crypto
- Diagnostics Channel
- EventEmitter
- path
- process
- Streams
- StringDecoder
- test
- util
Node.js APIs are available under the node:
prefix, and this prefix must be used when importing modules, both in your code and the npm packages you depend on.
Unless otherwise specified, implementations of Node.js APIs in Workers are intended to match the implementation in the Current release of Node.js ↗.
When using the nodejs_compat_v2
compatability flag, in addition to enabling Node.js APIs in the Workers Runtime, Wrangler will use unenv ↗ to automatically detect uses of Node.js APIs, and add polyfills where relevant.
Adding polyfills maximizes compatibility with existing npm packages, while recognizing that not all APIs from Node.js make sense in the context of serverless functions.
Where it is possible to provide a fully functional polyfill of the relevant Node.js API, unenv will do so.
In cases where this is not possible, such as the fs
↗, unenv adds a module with mocked methods.
Calling these mocked methods will either noop or will throw an error with a message like:
This allows you to import packages that use these Node.js modules, even if certain methods are not supported.
For a full list of APIs supported, including information on which are mocked, see the Node.js compatability matrix ↗.
Add the nodejs_compat
compatibility flag to your wrangler.toml
:
To enable nodejs_compat
in local development, pass the --compatibility-flags
argument with the nodejs_compat
flag to wrangler pages dev
:
For additional options, refer to the list of Pages-specific CLI commands.
To enable Node.js for your Pages Function from the Cloudflare dashboard:
- Log in to the Cloudflare dashboard ↗ and select your account.
- Select Workers & Pages and in Overview, select your Pages project.
- Select Settings > Functions > Compatibility Flags.
- Add the
nodejs_compat_v2
compatibility flag to your Preview and Production deployments.
To enable the Node.js AsyncLocalStorage
API only, use the nodejs_als
compatibility flag.
- Write your Worker code in ES modules syntax for an optimized experience.