Genkit is an open-source framework built by Google you can use to build AI-powered applications. The framework gives you structured output and tool calling, RAG, streaming, and generative UI. It also gives you tools around your AI application for tracing and evaluation, plus a user interface to test and observe the application.

Genkit has support for many model providers through an 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 run your JavaScript app in V8 isolates. These are lightweight sandboxes that start in milliseconds, so you don't have any cold start problems like you would've had in cloud serverless environments.

In this tutorial, you'll build an AI application called Explainer. You'll send it a software engineering topic, and it'll explains the topic to you 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

To follow along with this tutorial, you need:

  • Working knowledge of TypeScript
  • Basic knowledge of Genkit (flows and ai.generate())
  • A Cloudflare account
  • A Gemini API key (a Groq key is optional, for the fallback section)
  • pnpm installed
  • curl or Postman for testing

Why Genkit Breaks on Cloudflare Workers

JavaScript doesn't run by itself. Think of JavaScript as a car. Can it move? Yes, but it needs a solid surface on which to move. Similarly, JavaScript needs an environment to run in, and that environment is a program that provides the APIs (or support) that your JavaScript code executes.

The browser is an example of a runtime environment (with fetch and the DOM APIs), while Node.js is another (with fs and net APIs). Bun and Deno are still others.

Cloudflare Workers uses its own runtime (workerd) built on V8, the same engine that powers Chrome tabs. It gives you fetch, crypto, and timers, but it's not Node.js. Building a JavaScript application on Workers that assumes a full Node.js environment can fail.

Genkit relies on two capabilities that the Workers runtime deliberately restricts.

Restrictions on eval and new Function()

Workers forbids generating code from strings. Both eval() and new Function() throw this error in workerd, Cloudflare's runtime:

EvalError: Code generation from strings disallowed for this context 

Genkit uses new Function() in two places:

  • When its schema validator compiles validation code from JSON schemas: You turn that off with jsonSchemaMode: "interpret", which makes Genkit validate schema by only going through it instead of compiling it. This mode needs the @cfworker/json-schema package.
  • When it handles prompts: If you pass a string as the system or prompt value to ai.generate(), Genkit routes it through its dotprompt library. Dotprompt compiles Handlebars templates with new Function(). On Workers, that throws even before your model is ever called. The fix is to pass your prompt explicitly, as an array of message parts instead:
// Crashes on Workers: string goes through dotprompt → new Function() await ai.generate({ system: 'You are a helpful teacher.' }); // Works: parts bypass dotprompt's template compiler await ai.generate({ system: [{ text: 'You are a helpful teacher.' }] }); 

You'll use the parts form everywhere in this tutorial.

The Error from Genkit's Reflection Server Express Module

Error path for Genkit reflection server on Cloudflare Workers

When your Worker imports the genkit module, the module executes setGenkitRuntimeConfig() to set up Genkit's global runtime behaviour. The import chain pulls in Genkit's reflection server code, and that file does require("express") at module load.

Express pulls in body-parser, then raw-body, then iconv-lite, which calls require('stream') in a way workerd (Cloudflare's server runtime) rejects:

Uncaught TypeError: require_streams(...) is not a function at iconv-lite/lib/index.js ← raw-body ← body-parser ← express 

This shuts down your worker before a request arrives. Genkit's documented fix for restricted environments is sandboxedRuntime: true, but that flag only prevents the reflection server (Genkit's internal server that exposes your app for the Dev UI) from starting. It doesn't stop express from loading, and a crash then happens at load time.

The solution is to tell wrangler to replace express with a tiny stub that never runs. This way, when any of Express's HTTP method's are invoked during the load, the Express stub methods are invoked instead.

In general, there are three fixes to be made:

  • interpret-mode schemas
  • message-part prompts
  • an Express stub

Everything else in this tutorial is regular application code.

How to Set Up the Starter Repository

Clone the starter repository and install dependencies:

git clone https://github.com/orimdominic/genkit-apps-on-cloudflare-workers cd genkit-apps-on-cloudflare-workers pnpm install 

The repository is a barebones application built from Cloudflare's Workers template. It uses Hono, a lightweight web framework with an Express-like router and middleware API. You declare routes like app.post('/ping', ...), add middleware between the request and the handler, and then return a response.

Hono runs on Cloudflare Workers, Node.js, Deno, and Bun, and it uses the same code with the same API on each. This portability is key because you'll serve the identical app from the Workers runtime in production and from Node during development.

To test the application, start it:

pnpm dev 

In a second terminal or in Postman, make a request to the POST /ping endpoint:

curl -X POST http://localhost:8787/ping 

Expected output:

pong 

pnpm dev runs wrangler dev, which starts a local Workers runtime on port 8787. You can stop it anytime using CTRL + C or CMD + C.

How to Build the Explainer Flow

Install genkit and @genkit-ai/google-genai as dependencies of the project. In a terminal, run:

pnpm install genkit@latest @genkit-ai/google-genai 

Create a .dev.vars file in the root directory of the project and set GEMINI_API_KEY to your Gemini API key:

GEMINI_API_KEY=your-key-here 

Create src/flows/explainer.ts:

import { googleAI } from '@genkit-ai/google-genai'; import { genkit, z } from 'genkit'; const systemPrompt = `You are an excellent teacher of software engineering concepts. Explain ${topic} to me like I'm a junior software engineer using analogies that I can relate to and understand.`; export const ai = genkit({ plugins: [googleAI()], model: googleAI.model('gemini-3.5-flash'), }); export const explainerInputSchema = z.object({ topic: z.string().min(3) }); export const explainerFlow = ai.defineFlow( { name: 'explainerFlow', inputSchema: explainerInputSchema, outputSchema: z.object({ explanation: z.string() }), }, async ({ topic }) => { // system and prompt are passed as message parts, not strings, so // dotprompt never compiles them with Function() (blocked on Workers). const { text } = await ai.generate({ system: [{ text: systemPrompt }],` prompt: [{ text: `Topic: ${topic}` }], }); return { explanation: text }; }, ); 

There are a few decisions here that you should understand:

  • The z you import comes from genkit itself. It re-exports zod, so you don't need a separate zod dependency. You declare explainerInputSchema once and export it. The flow uses it as its input schema and the HTTP layer will use the same object for validation.
  • The system and prompt values are arrays of objects, so that dotprompt never compiles them with Function() which is blocked on Workers. This is the difference between a Worker that responds and a Worker that throws EvalError.

Swap in a Different Provider

If you don't want to use Gemini, you can swap in a different model provider. Here's how the setup differs for OpenAI and Groq:

Provider Plugin Model Reference API key env variable
Gemini googleAI() from @genkit-ai/google-genai googleAI.model("gemini-3.5-flash") GEMINI_API_KEY
OpenAI openAI() from @genkit-ai/compat-oai/openai "openai/gpt-4o" OPENAI_API_KEY
Groq openAICompatible({ name, baseURL }) from @genkit-ai/compat-oai "groq/openai/gpt-os-12b" GROQ_API_KEY

For OpenAI:

pnpm install @genkit-ai/compat-oai/openai # install the Genkit OpenAI plugin 
import { openAI } from '@genkit-ai/compat-oai/openai'; export const ai = genkit({ plugins: [openAI()], model: 'openai/gpt-4o', }); 

openAI() reads OPENAI_API_KEY from the environment automatically. The Groq section below shows how to set up Groq in full.

This tutorial puts environment variables in .dev.vars for local development and in Wrangler secrets for production.

Configure the Genkit Runtime

Create src/genkit-runtime.ts:

import { setGenkitRuntimeConfig } from 'genkit'; // workerd forbids eval() and new Function(), which Genkit's schema validator // and dotprompt rely on, and it cannot host the reflection server the Dev UI // uses. const isWorkersRuntime = 'WebSocketPair' in globalThis; setGenkitRuntimeConfig({ jsonSchemaMode: 'interpret', sandboxedRuntime: isWorkersRuntime, }); 

WebSocketPair only exists in the Workers runtime, so src/genkit-runtime.ts behaves correctly in both environments. On Workers, Genkit interprets schemas and skips the reflection server. In Node, it keeps the default behavior for the reflection server.

There are two things to note about src/genkit-runtime.ts:

  • It must be the first import in your entry points, before genkit is used.
  • On startup you'll see this warning:
It looks like you're trying to disable schema code generation. Please ensure that the '@cfworker/json-schema' package is installed: `npm i --save @cfworker/json-schema` 

Install the pnpm add @cfworker/json-schema package and ignore the warning. Genkit prints this warning every time you use interpret mode, even when the package is already installed.

Stop the Express Crash

Add the alias to wrangler.jsonc:

{ "$schema": "node_modules/wrangler/config-schema.json", "name": "deploy-genkit-apps-on-cloudflare-workers", "main": "src/index.ts", "compatibility_date": "2026-11-13", "alias": { "express": "./src/stubs/express.js" } } 

Create the Express stub in src/stubs/express.js. It exists only to satisfy the import that Genkit's reflection server performs at module load:

function express() { const app = () => app; app.use = () => app; app.get = () => app; app.post = () => app; app.put = () => app; app.delete = () => app; app.listen = () => app; app.set = () => app; app.engine = () => app; app.locals = {}; return app; } // Mirrors the express APIs referenced by genkit's reflection server. const passthrough = () => (_req, _res, next) => next?.(); express.json = passthrough; express.urlencoded = passthrough; express.raw = passthrough; express.text = passthrough; express.static = passthrough; express.Router = express; export default express; 

Why a stub is safe: On Workers, sandboxedRuntime: true stops the reflection server from ever starting, so Express is loaded but never called. The stub only needs to survive module load. The alias entry applies only to wrangler's bundle. When you run the app in Node later, Node loads the real Express module from node_modules and nothing is stubbed there.

Add the HTTP Endpoint

Update src/app.ts:

import { Hono } from 'hono'; import { validator } from 'hono/validator'; import { explainerFlow, explainerInputSchema } from './flows/explainer'; const app = new Hono(); app.post('/ping', (c) => { return c.text('pong'); }); const validateTopic = validator('json', (value, c) => { const parsed = explainerInputSchema.safeParse(value); if (!parsed.success) { return c.json({ error: 'Send a JSON body like {"topic": "microservices"}' }, 400); } return parsed.data; }); app.post('/explain', validateTopic, async (c) => { const { topic } = c.req.valid('json'); const { explanation } = await explainerFlow({ topic }); return c.json({ explanation }); }); export default app; 

validateTopic is a middleware that ensures that topic sent in the payload has a valid value. Inside the handler, c.req.valid('json') hands you an object that's already typed as { topic: string }.

Point the Worker entry at this app. Replace the contents of src/index.ts:

import './genkit-runtime'; import app from './app'; export default app; 

The bare import './genkit-runtime' line runs the configuration before anything else touches Genkit, to set it up for Workers.

How to Test the Worker Locally

With pnpm dev still running, send a request using curl or Postman.

curl -X POST http://localhost:8787/explain \ -H 'Content-Type: application/json' \ -d '{"topic":"microservices"}' 

Expected output (abbreviated):

{"explanation":"Welcome! As a junior engineer, you're going to hear the word \"Microservices\" thrown around constantly..."} 

If it fails with FAILED_PRECONDITION: ... set the GEMINI_API_KEY, it means your Gemini API key isn't visible to the Worker. Restart the Worker by stopping the server and starting it again. Also ensure that you've set your Gemini API key in a .dev.vars file at the project root:

GEMINI_API_KEY=your-key-here 

.dev.vars is local-only and gitignored. Wrangler reads it once at startup. If you add or change a key while pnpm dev is running, restart the dev server.

How to Run the App with the Genkit Dev UI

The Genkit Dev UI

The Genkit Developer UI is a local web page that lists your flows, shows traces for every run, and lets you run flows from a UI instead of curl. It's one of Genkit's best features and it can't run on Cloudflare Workers. Why?

The UI is a browser page, but it talks to a reflection server: a HTTP server inside your process that exposes your registered Genkit components (flows, models, tools). Starting an HTTP server and hosting Express is a Node.js job. Workers can't do it.

So the architecture is this: your app runs in Node for development (where the reflection server lives), and runs in Workers when in production (where it doesn't).

Create src/dev.ts (entry point for the reflection server):

import './genkit-runtime'; import { serve } from '@hono/node-server'; import app from './app'; serve({ fetch: app.fetch, port: 3781 }, (info) => { console.log(`Hono server listening on http://localhost:${info.port}`); }); 

This serves the same app: the same routes, validation, and flow from Node on port 3781, using @hono/node-server. So there are two runtimes each with its own entry point: src/index.ts is the Worker entry point, src/dev.ts is the Node.js entry point, and everything else is shared.

Add the script to package.json:

"genkit:dev": "genkit start -- tsx --env-file=.dev.vars --watch src/dev.ts" 

Run it with your key in the environment. This is the simplest way, since you already have .dev.vars:

pnpm run genkit:dev 

Expected output:

Genkit Developer UI: http://localhost:4000 Hono server listening on http://localhost:3781 

Open http://localhost:4000. You should see explainerFlow in the flows list. Run it with {"topic":"recursion"} and you get an explanation back. This is the same response your Worker returns, served this time by Node.

Genkit Dev UI after running the flow (explaining recursion)

If the flows list is empty, the reflection server probably shut itself down because GEMINI_API_KEY wasn't in the environment when genkit:dev started.

How to Deploy to Cloudflare Workers

First, you need to deploy your worker, because the command for setting Worker secrets targets only workers that have been deployed. To deploy your worker:

pnpm run deploy 

Note that the first time you run any wrangler command, it asks you to authenticate. It:

  • prints a URL
  • opens your browser
  • asks you to log in to Cloudflare and authorize Wrangler

Authorization returns a token and the CLI picks up the token automatically.

In the deployment process, Wrangler bundles your Worker, uploads it, and prints your live URL thereafter:

https://deploy-genkit-apps-on-cloudflare-workers.<your-account>.workers.dev 

Secrets are encrypted and injected as environment variables at runtime. Give your deployed Worker the API key as a secret:

pnpm dlx wrangler secret put GEMINI_API_KEY 

Wrangler prompts you to Enter the secret value: and pastes what you type.

Test the deployed endpoint with curl or Postman:

curl -X POST https://deploy-genkit-apps-on-cloudflare-workers.<your-account>.workers.dev/explain \ -H 'Content-Type: application/json' \ -d '{"topic":"microservices"}' 

You receive the JSON explanation as a response. Your Genkit app is now running on Cloudflare's edge!

One note on configuration: this project needs no compatibility_flags configuration in wrangler.json. With a compatibility_date of 2026-11-13, Cloudflare enables nodejs_compat by default, which is what puts environment variables like GEMINI_API_KEY on process.env inside the Worker.

How to Set Up Groq as a Fallback Provider

If you prefer to use Groq instead, get your Groq API key from the Groq console. Install @genkit-ai/compat-oai as a dependency in the project:

pnpm add @genkit-ai/compat-oai 

Add your key to .dev.vars and restart pnpm dev, because wrangler only reads that file at startup:

GROQ_API_KEY=your-groq-key 

Swap the plugin and model in src/flows/explainer.ts:

import { openAICompatible } from '@genkit-ai/compat-oai'; import { genkit, z } from 'genkit'; export const ai = genkit({ plugins: [ openAICompatible({ name: 'groq', apiKey: process.env.GROQ_API_KEY, baseURL: 'https://api.groq.com/openai/v1', }), ], model: 'groq/openai/gpt-oss-120b', }); 

This is the only change required. ai.generate() is provider-agnostic, which is one of Genkit's selling points. The model reference is namespaced as groq/<model>, using the name you gave the plugin.

Test it locally with the same curl command as before. Expected output (abbreviated, wording may vary because AI is non-deterministic):

{"explanation":"## What's a \"Microservice\"?\n\nThink of a big software system as a city..."} 

For production, set the secret the same way: pnpm dlx wrangler secret put GROQ_API_KEY.

Troubleshooting Common Errors

Here are some tips to help you solve common issues you might encounter:

Error message Cause Fix
TypeError: require_streams(...) is not a function at startup Genkit's import chain loads express inside workerd Add the express alias in wrangler.jsonc
EvalError: Code generation from strings disallowed A string system/prompt went through dotprompt Pass prompts as parts: system: [{ text }]
FAILED_PRECONDITION: ... set the GEMINI_API_KEY Key missing from the Worker's environment Add it to .dev.vars, restart pnpm dev
Dev UI loads but shows no flows Reflection server stopped: key missing when genkit:dev started Export the key, restart pnpm run genkit:dev
503 ... experiencing high demand Provider capacity, not your code Retry, or switch to the Groq setup above
@cfworker/json-schema warning at startup Unconditional reminder from setGenkitRuntimeConfig Install the package. The warning is harmless.

Streaming Responses with Genkit on Cloudflare Workers

This tutorial covers non-streaming flow calls: one request returning one JSON response, a request-response cycle. If you want tokens streamed as they are generated, Genkit documents streaming flow calls separately in its deployment guide.

Limitations of Genkit on Cloudflare Workers

Here are a few limitations worth knowing when deploying Genkit on Workers:

  • The Dev UI and reflection server run in Node only. On Workers, sandboxedRuntime disables them by design. This means that you can't access the Dev UI of your app in production.
  • The Express stub means no Express-based Genkit feature will work inside your Worker. For a regular Genkit application, nothing you need does anyway. The stub only exists to let the import succeed.
  • Dotprompt string templates are unavailable on Workers. Prompts must be passed as message parts.

Conclusion

You built a Genkit flow, validated its input with a shared zod schema, and ran it in three places: the local Workers runtime, Node under the Dev UI, and a live Cloudflare Worker. Along the way, you learned about the hurdles you may experience when deploying Genkit applications on Cloudflare Workers:

  • interpret-mode schema validation
  • message-part prompts that bypass dotprompt's new Function() and
  • the Express stub that keeps Genkit's import chain from crashing workerd

You also learned how to scale through the hurdles.

Go ahead and build with Genkit and deploy it on Cloudflare.

To see the finished version of the project, check the article/deploy-genkit-on-cloudflare branch of the project non GitHub. If you have any questions, or just want to say hi, reach out to Orim Dominic on LinkedIn.

References