Skip to content

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:

  1. As built-in APIs provided by the Workers Runtime
  2. As polyfills that Wrangler adds to your Worker's code

You can view which APIs are supported using the Node.js compatibility matrix.

Get Started

To enable built-in Node.js APIs and add polyfills, you need to add the nodejs_compat compatibility flag to your wrangler configuration. This also enables nodejs_compat_v2 as long as your compatibility date is 2024-09-23 or later. Learn more about the Node.js compatibility flag and v2.

{
"compatibility_flags": [
"nodejs_compat"
],
"compatibility_date": "2024-09-23"
}

Built-in Node.js Runtime APIs

The following APIs from Node.js are provided directly by the Workers Runtime when either nodejs_compat or nodejs_compat_v2 are enabled:

Unless otherwise specified, implementations of Node.js APIs in Workers are intended to match the implementation in the Current release of Node.js.

Node.js API Polyfills

To enable built-in Node.js APIs and add polyfills, you need to add the nodejs_compat compatibility flag to your wrangler configuration. This also enables nodejs_compat_v2 as long as your compatibility date is 2024-09-23 or later. Learn more about the Node.js compatibility flag and v2.

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:

[unenv] <method name> is not implemented yet!

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 compatibility matrix.

If an API you wish to use is missing and you want to suggest that Workers support it, please add a post or comment in the Node.js APIs discussions category on GitHub.

Enable only AsyncLocalStorage

To enable only the Node.js AsyncLocalStorage API, use the nodejs_als compatibility flag.

{
"compatibility_flags": [
"nodejs_als"
]
}