How to Deploy Genkit Apps on Cloudflare Workers

How to Deploy Genkit Apps on Cloudflare Workers


Genkit is an open-source framework built by Google for building AI-powered applications. It provides structured output, tool calling, RAG (Retrieval-Augmented Generation), streaming, and generative UI capabilities. The framework also includes tooling for tracing and evaluation of your AI application, plus a developer UI for testing and observability.


Genkit supports many model providers through a single ai.generate() API, which means you can swap Gemini for OpenAI or Claude without rewriting your application.


Cloudflare Workers is a serverless platform that runs your code close to your users. Workers execute your JavaScript in V8 isolates—lightweight sandboxes that start in milliseconds—eliminating the cold start problems common in traditional serverless environments. With Cloudflare's continued investment in edge computing through 2026, Workers now support even more Node.js APIs and have expanded compatibility flags, making it an increasingly viable target for AI workloads.


In this tutorial, you'll build an AI application called Explainer. You send it a software engineering topic, and it explains the topic as if you were a junior engineer.


Genkit applications break on Workers out of the box, so in this tutorial you'll understand why and also learn how to fix it.


What We'll Cover


  • Prerequisites
  • Why Genkit Breaks on Cloudflare Workers
  • Restrictions on eval and new Function()
  • The Error from Genkit's Reflection Server Express Module
  • How to Set Up the Starter Repository
  • How to Build the Explainer Flow
  • Swap in a Different Provider
  • Configure the Genkit Runtime
  • Stop the Reflection Server from Loading
  • Deploying to Cloudflare Workers
  • Testing Your Deployment

Prerequisites


Before you begin, make sure you have:


  • Node.js 20 or later installed
  • A Cloudflare account (the free tier is sufficient)
  • An API key for at least one model provider (Google AI Studio, OpenAI, or Anthropic)
  • Basic familiarity with TypeScript and serverless concepts
  • The Wrangler CLI installed (npm install -g wrangler)

Why Genkit Breaks on Cloudflare Workers


Restrictions on `eval` and `new Function()`


Cloudflare Workers run in V8 isolates with a strict security model that prohibits dynamic code evaluation. Unlike Node.js, Workers disallow eval() and new Function() because these can introduce security vulnerabilities and prevent the runtime from optimizing and caching code effectively. This restriction is part of the Workers runtime's design to ensure fast, secure execution at the edge.


Many npm packages—including some that Genkit depends on—rely on dynamic evaluation for features like schema validation, dependency injection, or plugin loading. When Genkit initializes, these dependencies can trigger runtime errors on Workers.


The Error from Genkit's Reflection Server Express Module


Out of the box, Genkit starts a reflection server (used by the Genkit Developer UI) that depends on Express. Express and its middleware stack use dynamic require() calls and eval-based patterns that are incompatible with the Workers runtime. When you attempt to bundle or deploy a Genkit app, you'll typically see an error like:


Error: Dynamic require of "express" is not supported

or


TypeError: eval is not a function

These errors occur because the reflection server attempts to load at module initialization time. The fix is to prevent the reflection server from loading in the Workers environment and to configure Genkit to run in a mode that avoids dynamic evaluation.


How to Set Up the Starter Repository


Clone the starter repository, which includes a basic Cloudflare Workers project with TypeScript and Genkit dependencies pre-installed:


git clone https://github.com/your-org/genkit-workers-starter.git
cd genkit-workers-starter
npm install

The project structure looks like this:


genkit-workers-starter/
├── src/
│   └── index.ts
├── wrangler.toml
├── package.json
└── tsconfig.json

Your wrangler.toml should include the following configuration to enable Node.js compatibility (which Genkit requires for certain polyfills):


name = "genkit-explainer"
main = "src/index.ts"
compatibility_date = "2026-01-01"
compatibility_flags = ["nodejs_compat"]

[vars]
# Model provider keys should be set as secrets, not vars

Add your model provider API key as a secret:


wrangler secret put GOOGLE_AI_API_KEY

How to Build the Explainer Flow


Create a new file src/explainer.ts that defines the Genkit flow:


import { genkit, z } from 'genkit';
import { googleAI } from '@genkit-ai/googleai';

export const ai = genkit({
  plugins: [googleAI()],
  model: 'googleai/gemini-2.5-flash',
});

export const explainerFlow = ai.defineFlow(
  {
    name: 'explainerFlow',
    inputSchema: z.object({ topic: z.string() }),
    outputSchema: z.object({ explanation: z.string() }),
  },
  async ({ topic }) => {
    const { text } = await ai.generate({
      prompt: `Explain the following software engineering topic as if I were a junior engineer: ${topic}`,
    });
    return { explanation: text };
  }
);

Swap in a Different Provider


To use OpenAI or Anthropic instead, replace the plugin import and model identifier:


import { openAI } from '@genkit-ai/openai';

export const ai = genkit({
  plugins: [openAI()],
  model: 'openai/gpt-4o',
});

Remember to set the corresponding API key as a secret (wrangler secret put OPENAIAPIKEY).


Configure the Genkit Runtime


Create src/index.ts to wire up the Worker and configure Genkit for the Workers environment:


import { explainerFlow } from './explainer';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/explain' && request.method === 'POST') {
      try {
        const body = await request.json() as { topic: string };
        const result = await explainerFlow({ topic: body.topic });
        return Response.json(result);
      } catch (error) {
        return Response.json({ error: (error as Error).message }, { status: 500 });
      }
    }

    return new Response('Not Found', { status: 404 });
  },
};

interface Env {
  GOOGLE_AI_API_KEY: string;
}

Stop the Reflection Server from Loading


The reflection server is what breaks on Workers. To prevent it from loading, set the environment variable GENKIT_ENV to production (or any value other than dev) before importing Genkit. In Workers, you can do this at the top of your entry file:


globalThis.process = globalThis.process || {};
(globalThis.process as any).env = {
  ...((globalThis.process as any).env || {}),
  GENKIT_ENV: 'production',
};

// Now import Genkit modules
import { explainerFlow } from './explainer';

Alternatively, add an alias in your wrangler.toml to stub out the reflection server module:


[alias]
"@genkit-ai/express" = "./src/stubs/express-stub.ts"

And create src/stubs/express-stub.ts:


export function startReflectionServer() {
  // No-op on Workers
}

This prevents the Express module from being bundled and loaded at runtime.


Deploying to Cloudflare Workers


With the reflection server disabled and Genkit configured for production mode, deploy your Worker:


wrangler deploy

Wrangler will bundle your application, run compatibility checks, and upload it to Cloudflare's edge network. If you encounter bundling errors related to dynamic require calls, add the following to your wrangler.toml to enable Node.js built-in module polyfills:


[build]
command = "npm run build"

[build.upload]
format = "modules"

And ensure your package.json includes a build script that uses esbuild with the --platform=node flag, which handles many CommonJS patterns:


{
  "scripts": {
    "build": "esbuild src/index.ts --bundle --format=esm --platform=node --outfile=dist/index.js"
  }
}

Testing Your Deployment


After deployment, test your Explainer with a curl request:


curl -X POST https://genkit-explainer.your-subdomain.workers.dev/explain \
  -H "Content-Type: application/json" \
  -d '{"topic": "What is a closure in JavaScript?"}'

You should receive a JSON response containing a junior-friendly explanation of JavaScript closures. If you get a 500 error, check the Worker logs with:


wrangler tail

This streams real-time logs from your deployed Worker, making it easy to diagnose issues related to Genkit initialization or model provider authentication.


Wrapping Up


Deploying Genkit on Cloudflare Workers requires working around the runtime's security restrictions on dynamic code evaluation and preventing the reflection server from loading. By setting GENKITENV=production and stubbing out the Express-based reflection server, you can run Genkit flows at the edge with millisecond cold starts and global distribution. As Cloudflare's nodejscompat flag continues to mature in 2026, the number of workarounds needed for AI frameworks like Genkit continues to shrink—but understanding these constraints will help you debug any framework that relies on Node.js-specific patterns when moving to the edge.

via FreeCodeCamp

Related