Node.js compatibility
Most Workers import one or more packages of JavaScript or TypeScript code from NPM as dependencies in package.json
. Many of these packages rely on APIs from the Node.js runtime, and will not work unless these APIs are present.
To ensure compatibility with a wider set of NPM packages, and make it easier for you to run existing applications on Cloudflare Workers, the following subset of APIs from Node.js are available directly as Runtime APIs in your Cloudflare Worker:
These APIs are available directly in the Workers runtime, without the need to add polyfills to your own code via the previous node_compat
option in Wrangler.
Node.js APIs in Workers 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.
// Do this:
import { Buffer } from 'node:buffer';
// Do not do this:
import { Buffer } from 'buffer';
Enable Node.js with Workers
Add the nodejs_compat
compatibility flag to your wrangler.toml
:
wrangler.tomlcompatibility_flags = [ "nodejs_compat" ]
Enable Node.js with Pages Functions
Enable with Wrangler
To enable nodejs_compat
in local development, pass the --compatibility-flags
argument with the nodejs_compat
flag to wrangler pages dev
:
$ wrangler pages dev [<DIRECTORY>] --compatibility-flags="nodejs_compat" --experimental-local
For additional options, refer to the list of Pages-specific CLI commands.
Enable Node.js from the Cloudflare dashboard
To enable Node.js for your Pages Function from the Cloudflare dashboard:
- Log in to the Cloudflare dashboard and select your account.
- Select Pages and select your Pages project.
- Select Settings > Functions > Compatibility Flags.
- Add the
nodejs_compat
compatibility flag to your Preview and Production deployments.