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 APIs from the Node.js runtime ↗ are available directly as Workers runtime APIs, with no need to add polyfills to your own code:
- 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.
// Do this:import { Buffer } from "node:buffer";
// Do not do this:import { Buffer } from "buffer";
Unless otherwise specified, implementations of Node.js APIs in Workers are intended to match the implementation in the Current release of Node.js ↗.
Add the nodejs_compat
compatibility flag to your wrangler.toml
:
compatibility_flags = [ "nodejs_compat" ]
To enable nodejs_compat
in local development, pass the --compatibility-flags
argument with the nodejs_compat
flag to wrangler pages dev
:
npx wrangler pages dev [<DIRECTORY>] --compatibility-flags="nodejs_compat"
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
compatibility flag to your Preview and Production deployments.
To enable the Node.js AsyncLocalStorage
API only, use the nodejs_als
compatibility flag.
compatibility_flags = [ "nodejs_als" ]
- Write your Worker code in ES modules syntax for an optimized experience.