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

Get Started

To enable both built-in runtime APIs and polyfills for your Worker or Pages project, add the nodejs_compat compatibility flag to your wrangler.toml, and set your compatibility date to September 23rd, 2024 or later.

wrangler.toml
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

When you enable the nodejs_compat compatability flag and set your compatibility date to 2024-09-23 or later, 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:

[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 compatability 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" ]