Skip to main content
Prerequisites:
  • A Cloudflare account with Workers enabled
  • Node.js version 22 or higher
  • A Mastra project ready to deploy
  • wrangler CLI installed (optional peer dependency)
The Cloudflare deployer enables deployment of Mastra applications to Cloudflare Workers, running your AI applications on Cloudflare’s global edge network.

Installation

1

Install the Cloudflare deployer

Install the @mastra/deployer-cloudflare package and wrangler:
pnpm add @mastra/deployer-cloudflare wrangler
wrangler is an optional peer dependency, but recommended for local development and deployment.
2

Configure the deployer

Add the Cloudflare deployer to your Mastra configuration:
import { Mastra } from '@mastra/core/mastra';
import { CloudflareDeployer } from '@mastra/deployer-cloudflare';

const deployer = new CloudflareDeployer({
  name: 'my-mastra-app',
  compatibility_date: '2025-04-01',
  compatibility_flags: ['nodejs_compat'],
  // Optional: Configure bindings
  d1_databases: [
    {
      binding: 'DB',
      database_name: 'my-database',
      database_id: 'xxx-xxx-xxx',
    },
  ],
  kv_namespaces: [
    {
      binding: 'KV',
      id: 'xxx-xxx-xxx',
    },
  ],
});

const mastra = new Mastra({
  deployer,
  // ... other Mastra configuration
});
3

Build your project

Run your build command. The deployer will:
  • Bundle your application for Cloudflare Workers
  • Generate wrangler.jsonc configuration
  • Create a TypeScript stub to reduce bundle size
pnpm build
4

Deploy to Cloudflare

Deploy using Wrangler:
npx wrangler deploy
Or use the Cloudflare dashboard for GitOps deployments.

Configuration options

The CloudflareDeployer constructor accepts all standard wrangler.json configuration options. See the Wrangler configuration documentation for complete details.

Common options

name

  • Type: string
  • Required: Yes
  • Description: Name of your Worker
  • Example: name: 'my-ai-app'

compatibility_date

  • Type: string
  • Description: Cloudflare Workers compatibility date
  • Default: '2025-04-01'
  • Example: compatibility_date: '2025-04-01'

compatibility_flags

  • Type: string[]
  • Description: Enable runtime compatibility features
  • Default: ['nodejs_compat', 'nodejs_compat_populate_process_env']
  • Example: compatibility_flags: ['nodejs_compat']

vars

  • Type: Record<string, string>
  • Description: Environment variables (merged with .env files)
  • Example:
vars: {
  API_KEY: 'your-key',
  ENVIRONMENT: 'production',
}

d1_databases

  • Type: Array<{ binding: string; database_name: string; database_id: string }>
  • Description: Cloudflare D1 database bindings
  • Example:
d1_databases: [
  {
    binding: 'DB',
    database_name: 'production-db',
    database_id: 'xxx-xxx-xxx',
  },
]

kv_namespaces

  • Type: Array<{ binding: string; id: string }>
  • Description: Cloudflare KV namespace bindings
  • Example:
kv_namespaces: [
  {
    binding: 'CACHE',
    id: 'xxx-xxx-xxx',
  },
]

routes

  • Type: Array<{ pattern: string; zone_name?: string; custom_domain?: boolean }>
  • Description: Custom domain routing
  • Example:
routes: [
  {
    pattern: 'api.example.com/*',
    zone_name: 'example.com',
    custom_domain: true,
  },
]
Deprecated fields: projectName, d1Databases, kvNamespaces, and workerNamespace are deprecated. Use the standard wrangler.json property names instead.

How it works

The Cloudflare deployer:
  1. Wraps your Mastra instance to work with Cloudflare’s request/response model:
export default {
  fetch: async (request, env, context) => {
    const { mastra } = await import('#mastra');
    const { tools } = await import('#tools');
    const { createHonoServer, getToolExports } = await import('#server');
    const _mastra = mastra();

    const app = await createHonoServer(_mastra, { 
      tools: getToolExports(tools) 
    });
    return app.fetch(request, env, context);
  }
}
  1. Creates a TypeScript stub to prevent bundling the full TypeScript library (~10MB)
  2. Generates wrangler.jsonc with your configuration and proper paths
  3. Polyfills Node.js APIs for compatibility
  4. Handles PostgreSQL stores if using @mastra/pg

Storage compatibility

The Cloudflare deployer does not support @mastra/libsql. Use @mastra/cloudflare-d1 instead.
Compatible storage options:
  • @mastra/cloudflare-d1 - Cloudflare D1 (recommended)
  • @mastra/pg - PostgreSQL (with connection pooling)
  • @mastra/mongodb - MongoDB
  • @mastra/dynamodb - AWS DynamoDB
The deployer automatically checks for incompatible dependencies during the build process.

Environment variables

Environment variables are handled through:
  1. Local .env files - Automatically loaded and merged
  2. vars in configuration - Passed to the deployer constructor
  3. Wrangler secrets - For sensitive data:
npx wrangler secret put DATABASE_URL
  1. Cloudflare Dashboard - Via the Workers settings UI
Variables from .env files and the vars option are merged together, with vars taking precedence.

Using Cloudflare bindings

D1 Database

import { Mastra } from '@mastra/core/mastra';
import { CloudflareD1Store } from '@mastra/cloudflare-d1';
import { CloudflareDeployer } from '@mastra/deployer-cloudflare';

const deployer = new CloudflareDeployer({
  name: 'my-app',
  d1_databases: [
    {
      binding: 'DB',
      database_name: 'my-db',
      database_id: 'your-db-id',
    },
  ],
});

// Access in your Mastra app via context
const storage = new CloudflareD1Store({
  binding: 'DB',
});

const mastra = new Mastra({
  deployer,
  storage,
});

KV Namespace

const deployer = new CloudflareDeployer({
  name: 'my-app',
  kv_namespaces: [
    {
      binding: 'CACHE',
      id: 'your-kv-id',
    },
  ],
});

// Access in your handler via env.CACHE

Project structure

After building, your project will have:
your-project/
├── wrangler.jsonc              # Auto-generated Wrangler config
├── .mastra/
│   └── output/
│       └── index.mjs           # Bundled Worker
│       └── typescript-stub.mjs # TypeScript stub
├── src/
│   └── mastra/
│       └── index.ts            # Your Mastra config
└── package.json

Troubleshooting

This is handled automatically. The deployer creates a TypeScript stub to keep bundle sizes small while maintaining compatibility.
Ensure all imports use the correct module specifiers. Cloudflare Workers require explicit file extensions for ESM imports.
The deployer automatically detects @mastra/libsql and throws an error. Switch to @mastra/cloudflare-d1 for Cloudflare Workers.
Make sure you have the nodejs_compat_populate_process_env compatibility flag enabled (it’s enabled by default).

Next steps

Cloudflare D1 Storage

Use Cloudflare D1 for storage

Server & API

Learn about Mastra’s server capabilities

Observability

Set up logging and tracing

Wrangler Docs

Official Wrangler documentation

Build docs developers (and LLMs) love