mastra-ai/mastra · error

require(${specifier}) is not available in Cloudflare Workers

Error message

require(${specifier}) is not available in Cloudflare Workers

What it means

This error is thrown by a module stub that the Cloudflare deployer writes during `writeFiles` (called via `prepare`) into the deploy bundle. Wrangler runs Workers with an undefined `import.meta.url`, so Node's `createRequire(import.meta.url)` interop helper cannot work; the stub replaces `module.createRequire` with a function that throws this explicit message whenever bundled code calls `require(...)`. It exists to turn a cryptic runtime crash into a clear diagnostic: Node's `require` is unavailable in the Cloudflare Workers runtime.

Source

Thrown at deployers/cloudflare/src/index.ts:175

    // Write readable-stream stub — redirects to native node:stream available via nodejs_compat.
    // readable-stream is a userland copy of Node.js streams used by packages like elevenlabs.
    // Bundling it for Workers pulls in Node.js polyfills (abort-controller, process/, string_decoder/)
    // that are unnecessary and fail to resolve. The native node:stream is API-compatible.
    const readableStreamStubPath = 'readable-stream-stub.mjs';
    const readableStreamStub = `// Redirect readable-stream to native node:stream (available via nodejs_compat)
import stream from 'node:stream';
export const { Readable, Writable, Duplex, Transform, PassThrough, Stream, pipeline, finished } = stream;
export default stream;
`;
    await writeFile(join(outputDirectory, this.outputDir, readableStreamStubPath), readableStreamStub);

    // Write module stub — Wrangler runs Workers with an undefined import.meta.url,
    // so eager createRequire(import.meta.url) interop helpers must not call Node's implementation.
    const moduleStubPath = 'module-stub.mjs';
    const moduleStub = `// Stub for module.createRequire in Cloudflare Workers
export function createRequire() {
  const req = specifier => {
    throw new Error(\`require(\${specifier}) is not available in Cloudflare Workers\`);
  };
  req.resolve = specifier => specifier;
  return req;
}
export default { createRequire };
`;
    await writeFile(join(outputDirectory, this.outputDir, moduleStubPath), moduleStub);

    const wranglerConfig: Unstable_RawConfig = {
      name: 'mastra',
      compatibility_date: '2025-04-01',
      compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],
      observability: {
        logs: {
          enabled: true,
        },
      },
      ...userConfig,

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Find the `require(...)` / `createRequire(import.meta.url)` call in the stack trace and replace it with a static ESM `import`.
  2. Configure your bundler to resolve the ESM/browser build of the offending dependency (mainFields/alias/`conditions: ['worker','browser']`).
  3. Mark the module external and provide a Workers-compatible shim, or enable `nodejs_compat` compat flags if only limited Node APIs are needed.
  4. Run `wrangler dev` before deploying to catch the stub throw locally.

Example fix

// before
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');
// after
import pkg from './package.json' with { type: 'json' };
Defensive patterns

Strategy: fallback

Validate before calling

// Detect Node require/createRequire usage before deploying to Workers
import { readFileSync } from 'node:fs';
const src = readFileSync(entryFile, 'utf8');
if (/createRequire\s*\(/.test(src) || /(^|[^.\w])require\s*\(\s*['"]/.test(src)) {
  throw new Error('Entry uses require()/createRequire() which is unavailable in Cloudflare Workers; migrate to ESM imports.');
}

Type guard

function isNodeInteropUsage(code: string): boolean {
  return /createRequire|\brequire\s*\(/.test(code);
}

Try / catch

try {
  await deployer.prepare(...);
} catch (err) {
  if (err instanceof Error && err.message.includes('is not available in Cloudflare Workers')) {
    console.error('CJS interop detected: replace require()/createRequire with ESM imports or add nodejs_compat.', err.message);
  } else throw err;
}

Prevention

When it happens

Trigger: Deployed Worker code (or a bundled dependency) eagerly calls `require('...')` or `const require = createRequire(import.meta.url); require(...)` at module evaluation time, hitting the module-stub.mjs stub inside the Workers runtime.

Common situations: Importing an npm package with CJS interop shims that detect `import.meta.url`; publishing CJS-only dependencies into a Worker bundle; running Node-written code on Workers; bundler resolving the CJS entry instead of the ESM build.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/16ce346471cc7d57. Report an issue: GitHub.