<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ firebase genkit - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ firebase genkit - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:33:35 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/firebase-genkit/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Deploy Genkit Apps on Cloudflare Workers ]]>
                </title>
                <description>
                    <![CDATA[ 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  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/deploy-genkit-apps-on-cloudflare-workers/</link>
                <guid isPermaLink="false">6b119ff79e7a3c1966d84f64</guid>
                
                    <category>
                        <![CDATA[ firebase genkit ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cloudflare ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Orim Dominic Adah ]]>
                </dc:creator>
                <pubDate>Thu, 03 Dec 2026 16:59:35 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/21a033d6-82eb-4db5-9a72-29429eee09fd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>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.</p>
<p>Genkit has support for many model providers through an <code>ai.generate()</code> API, which means you can swap Gemini for OpenAI or Claude without rewriting your application.</p>
<p>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.</p>
<p>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.</p>
<p>Genkit applications break on Workers out of the box, so in this tutorial you'll understand why and also learn how to fix it.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-why-genkit-breaks-on-cloudflare-workers">Why Genkit Breaks on Cloudflare Workers</a><ul>
<li><a href="#heading-restrictions-on-eval-and-new-function">Restrictions onevalandnew Function()</a></li>
<li><a href="#heading-the-error-from-genkits-reflection-server-express-module">The Error from Genkit's Reflection Server Express Module</a></li>
</ul>
</li>
<li><a href="#heading-how-to-set-up-the-starter-repository">How to Set Up the Starter Repository</a></li>
<li><a href="#heading-how-to-build-the-explainer-flow">How to Build the Explainer Flow</a><ul>
<li><a href="#heading-swap-in-a-different-provider">Swap in a Different Provider</a></li>
<li><a href="#heading-configure-the-genkit-runtime">Configure the Genkit Runtime</a></li>
<li><a href="#heading-stop-the-express-crash">Stop the Express Crash</a></li>
<li><a href="#heading-add-the-http-endpoint">Add the HTTP Endpoint</a></li>
</ul>
</li>
<li><a href="#heading-how-to-test-the-worker-locally">How to Test the Worker Locally</a></li>
<li><a href="#heading-how-to-run-the-app-with-the-genkit-dev-ui">How to Run the App with the Genkit Dev UI</a></li>
<li><a href="#heading-how-to-deploy-to-cloudflare-workers">How to Deploy to Cloudflare Workers</a></li>
<li><a href="#heading-how-to-set-up-groq-as-a-fallback-provider">How to Set Up Groq as a Fallback Provider</a></li>
<li><a href="#heading-troubleshooting-common-errors">Troubleshooting Common Errors</a></li>
<li><a href="#heading-streaming-responses-with-genkit-on-cloudflare-workers">Streaming Responses with Genkit on Cloudflare Workers</a></li>
<li><a href="#heading-limitations-of-genkit-on-cloudflare-workers">Limitations of Genkit on Cloudflare Workers</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
<li><a href="#heading-references">References</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you need:</p>
<ul>
<li>Working knowledge of TypeScript</li>
<li>Basic knowledge of Genkit (flows and <code>ai.generate()</code>)</li>
<li>A Cloudflare account</li>
<li>A Gemini API key (a Groq key is optional, for the fallback section)</li>
<li><code>pnpm</code> installed</li>
<li><code>curl</code> or Postman for testing</li>
</ul>
<h2 id="heading-why-genkit-breaks-on-cloudflare-workers">Why Genkit Breaks on Cloudflare Workers</h2>
<p>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.</p>
<p>The browser is an example of a runtime environment (with <code>fetch</code> and the DOM APIs), while Node.js is another (with <code>fs</code> and <code>net</code> APIs). Bun and Deno are still others.</p>
<p>Cloudflare Workers uses its own runtime (workerd) built on V8, the same engine that powers Chrome tabs. It gives you <code>fetch</code>, <code>crypto</code>, and timers, but it's not Node.js. Building a JavaScript application on Workers that assumes a full Node.js environment can fail.</p>
<p>Genkit relies on two capabilities that the Workers runtime deliberately restricts.</p>
<h3 id="heading-restrictions-on-eval-and-new-function">Restrictions on <code>eval</code> and <code>new Function()</code></h3>
<p>Workers forbids generating code from strings. Both <code>eval()</code> and <code>new Function()</code> throw this error in workerd, Cloudflare's runtime:</p>
<pre><code class="language-text">EvalError: Code generation from strings disallowed for this context
</code></pre>
<p>Genkit uses <code>new Function()</code> in two places:</p>
<ul>
<li><strong>When its schema validator compiles validation code from JSON schemas</strong>: You turn that off with <code>jsonSchemaMode: "interpret"</code>, which makes Genkit validate schema by only going through it instead of compiling it. This mode needs the <code>@cfworker/json-schema</code> package.</li>
<li><strong>When it handles prompts</strong>: If you pass a <strong>string</strong> as the <code>system</code> or <code>prompt</code> value to <code>ai.generate()</code>, Genkit routes it through its dotprompt library. Dotprompt compiles Handlebars templates with <code>new Function()</code>. 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:</li>
</ul>
<pre><code class="language-ts">// 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.' }] });
</code></pre>
<p>You'll use the parts form everywhere in this tutorial.</p>
<h3 id="heading-the-error-from-genkits-reflection-server-express-module">The Error from Genkit's Reflection Server Express Module</h3>
<img src="https://cdn.hashnode.com/uploads/covers/66e28b713f978a0e2cd2b763/397ec06d-5e35-439d-88d1-c003eee82176.png" alt="Error path for Genkit reflection server on Cloudflare Workers" style="display: block;" width="600" height="400" loading="lazy">

<p>When your Worker imports the <code>genkit</code> module, the module executes <code>setGenkitRuntimeConfig()</code> to set up Genkit's global runtime behaviour. The import chain pulls in Genkit's reflection server code, and that file does <code>require("express")</code> at module load.</p>
<p>Express pulls in <code>body-parser</code>, then <code>raw-body</code>, then <code>iconv-lite</code>, which calls <code>require('stream')</code> in a way workerd (Cloudflare's server runtime) rejects:</p>
<pre><code class="language-text">Uncaught TypeError: require_streams(...) is not a function
  at iconv-lite/lib/index.js ← raw-body ← body-parser ← express
</code></pre>
<p>This shuts down your worker before a request arrives. <a href="https://genkit.dev/docs/js/deployment/any-platform/#environments-that-restrict-eval">Genkit's documented fix</a> for restricted environments is <code>sandboxedRuntime: true</code>, but that flag only prevents the reflection server (Genkit's internal server that exposes your app for the Dev UI) from <em>starting</em>. It doesn't stop express from <em>loading</em>, and a crash then happens at load time.</p>
<p>The solution is to tell wrangler to replace <code>express</code> 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.</p>
<p>In general, there are three fixes to be made:</p>
<ul>
<li>interpret-mode schemas</li>
<li>message-part prompts</li>
<li>an Express stub</li>
</ul>
<p>Everything else in this tutorial is regular application code.</p>
<h2 id="heading-how-to-set-up-the-starter-repository">How to Set Up the Starter Repository</h2>
<p>Clone the starter repository and install dependencies:</p>
<pre><code class="language-bash">git clone https://github.com/orimdominic/genkit-apps-on-cloudflare-workers
cd genkit-apps-on-cloudflare-workers
pnpm install
</code></pre>
<p>The repository is a barebones application built from Cloudflare's Workers template. It uses <a href="https://hono.dev/docs/">Hono</a>, a lightweight web framework with an Express-like router and middleware API. You declare routes like <code>app.post('/ping', ...)</code>, add middleware between the request and the handler, and then return a response.</p>
<p>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.</p>
<p>To test the application, start it:</p>
<pre><code class="language-bash">pnpm dev				
</code></pre>
<p>In a second terminal or in Postman, make a request to the <code>POST /ping</code> endpoint:</p>
<pre><code class="language-bash">curl -X POST http://localhost:8787/ping
</code></pre>
<p>Expected output:</p>
<pre><code class="language-text">pong
</code></pre>
<p><code>pnpm dev</code> runs <code>wrangler dev</code>, which starts a local Workers runtime on port 8787. You can stop it anytime using <code>CTRL + C</code> or <code>CMD + C</code>.</p>
<h2 id="heading-how-to-build-the-explainer-flow">How to Build the Explainer Flow</h2>
<p>Install <code>genkit</code> and <code>@genkit-ai/google-genai</code> as dependencies of the project. In a terminal, run:</p>
<pre><code class="language-bash">pnpm install genkit@latest @genkit-ai/google-genai
</code></pre>
<p>Create a <code>.dev.vars</code> file in the root directory of the project and set <code>GEMINI_API_KEY</code> to your Gemini API key:</p>
<pre><code class="language-txt">GEMINI_API_KEY=your-key-here
</code></pre>
<p>Create <code>src/flows/explainer.ts</code>:</p>
<pre><code class="language-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 }) =&gt; {
		// 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 };
	},
);
</code></pre>
<p>There are a few decisions here that you should understand:</p>
<ul>
<li>The <code>z</code> you import comes from <code>genkit</code> itself. It re-exports zod, so you don't need a separate <code>zod</code> dependency. You declare <code>explainerInputSchema</code> once and export it. The flow uses it as its input schema and the HTTP layer will use the same object for validation.</li>
<li>The <code>system</code> and <code>prompt</code> values are arrays of objects, so that dotprompt never compiles them with <code>Function()</code> which is blocked on Workers. This is the difference between a Worker that responds and a Worker that throws <code>EvalError</code>.</li>
</ul>
<h3 id="heading-swap-in-a-different-provider">Swap in a Different Provider</h3>
<p>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:</p>
<table>
<thead>
<tr>
<th>Provider</th>
<th>Plugin</th>
<th>Model Reference</th>
<th>API key env variable</th>
</tr>
</thead>
<tbody><tr>
<td>Gemini</td>
<td><code>googleAI()</code> from <code>@genkit-ai/google-genai</code></td>
<td><code>googleAI.model("gemini-3.5-flash")</code></td>
<td><code>GEMINI_API_KEY</code></td>
</tr>
<tr>
<td>OpenAI</td>
<td><code>openAI()</code> from <code>@genkit-ai/compat-oai/openai</code></td>
<td><code>"openai/gpt-4o"</code></td>
<td><code>OPENAI_API_KEY</code></td>
</tr>
<tr>
<td>Groq</td>
<td><code>openAICompatible({ name, baseURL })</code> from <code>@genkit-ai/compat-oai</code></td>
<td><code>"groq/openai/gpt-os-12b"</code></td>
<td><code>GROQ_API_KEY</code></td>
</tr>
</tbody></table>
<p>For OpenAI:</p>
<pre><code class="language-bash">pnpm install @genkit-ai/compat-oai/openai			# install the Genkit OpenAI plugin
</code></pre>
<pre><code class="language-ts">import { openAI } from '@genkit-ai/compat-oai/openai';

export const ai = genkit({
	plugins: [openAI()],
	model: 'openai/gpt-4o',
});
</code></pre>
<p><code>openAI()</code> reads <code>OPENAI_API_KEY</code> from the environment automatically. The <a href="#how-to-set-up-groq-as-a-fallback-provider">Groq section</a> below shows how to set up Groq in full.</p>
<p>This tutorial puts environment variables in <code>.dev.vars</code> for local development and in Wrangler secrets for production.</p>
<h3 id="heading-configure-the-genkit-runtime">Configure the Genkit Runtime</h3>
<p>Create <code>src/genkit-runtime.ts</code>:</p>
<pre><code class="language-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,
});
</code></pre>
<p><code>WebSocketPair</code> only exists in the Workers runtime, so <code>src/genkit-runtime.ts</code> 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.</p>
<p>There are two things to note about <code>src/genkit-runtime.ts</code>:</p>
<ul>
<li>It must be the first import in your entry points, before <code>genkit</code> is used.</li>
<li>On startup you'll see this warning:</li>
</ul>
<pre><code class="language-text">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`
</code></pre>
<p>Install the <code>pnpm add @cfworker/json-schema</code> package and ignore the warning. Genkit prints this warning every time you use interpret mode, even when the package is already installed.</p>
<h3 id="heading-stop-the-express-crash">Stop the Express Crash</h3>
<p>Add the alias to <code>wrangler.jsonc</code>:</p>
<pre><code class="language-json">{
  "$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"
  }
}
</code></pre>
<p>Create the Express stub in <code>src/stubs/express.js</code>. It exists only to satisfy the import that Genkit's reflection server performs at module load:</p>
<pre><code class="language-js">function express() {
	const app = () =&gt; app;
	app.use = () =&gt; app;
	app.get = () =&gt; app;
	app.post = () =&gt; app;
	app.put = () =&gt; app;
	app.delete = () =&gt; app;
	app.listen = () =&gt; app;
	app.set = () =&gt; app;
	app.engine = () =&gt; app;
	app.locals = {};
	return app;
}

// Mirrors the express APIs referenced by genkit's reflection server.
const passthrough = () =&gt; (_req, _res, next) =&gt; next?.();

express.json = passthrough;
express.urlencoded = passthrough;
express.raw = passthrough;
express.text = passthrough;
express.static = passthrough;
express.Router = express;

export default express;
</code></pre>
<p>Why a stub is safe: On Workers, <code>sandboxedRuntime: true</code> stops the reflection server from ever starting, so Express is loaded but never called. The stub only needs to survive module load. The <code>alias</code> entry applies only to wrangler's bundle. When you run the app in Node later, Node loads the real Express module from <code>node_modules</code> and nothing is stubbed there.</p>
<h3 id="heading-add-the-http-endpoint">Add the HTTP Endpoint</h3>
<p>Update <code>src/app.ts</code>:</p>
<pre><code class="language-ts">import { Hono } from 'hono';
import { validator } from 'hono/validator';
import { explainerFlow, explainerInputSchema } from './flows/explainer';

const app = new Hono();

app.post('/ping', (c) =&gt; {
	return c.text('pong');
});

const validateTopic = validator('json', (value, c) =&gt; {
	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) =&gt; {
	const { topic } = c.req.valid('json');
	const { explanation } = await explainerFlow({ topic });
	return c.json({ explanation });
});

export default app;
</code></pre>
<p><code>validateTopic</code> is a middleware that ensures that <code>topic</code> sent in the payload has a valid value. Inside the handler, <code>c.req.valid('json')</code> hands you an object that's already typed as <code>{ topic: string }</code>.</p>
<p>Point the Worker entry at this app. Replace the contents of <code>src/index.ts</code>:</p>
<pre><code class="language-ts">import './genkit-runtime';
import app from './app';

export default app;
</code></pre>
<p>The bare <code>import './genkit-runtime'</code> line runs the configuration before anything else touches Genkit, to set it up for Workers.</p>
<h2 id="heading-how-to-test-the-worker-locally">How to Test the Worker Locally</h2>
<p>With <code>pnpm dev</code> still running, send a request using curl or Postman.</p>
<pre><code class="language-bash">curl -X POST http://localhost:8787/explain \
  -H 'Content-Type: application/json' \
  -d '{"topic":"microservices"}'
</code></pre>
<p>Expected output (abbreviated):</p>
<pre><code class="language-json">{"explanation":"Welcome! As a junior engineer, you're going to hear the word \"Microservices\" thrown around constantly..."}
</code></pre>
<p>If it fails with <code>FAILED_PRECONDITION: ... set the GEMINI_API_KEY</code>, 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 <code>.dev.vars</code> file at the project root:</p>
<pre><code class="language-text">GEMINI_API_KEY=your-key-here
</code></pre>
<p><code>.dev.vars</code> is local-only and gitignored. Wrangler reads it once at startup. If you add or change a key while <code>pnpm dev</code> is running, restart the dev server.</p>
<h2 id="heading-how-to-run-the-app-with-the-genkit-dev-ui">How to Run the App with the Genkit Dev UI</h2>
<img src="https://cdn.hashnode.com/uploads/covers/66e28b713f978a0e2cd2b763/0844b694-39e3-49b0-ad8c-26cb42b27fe0.png" alt="The Genkit Dev UI" style="display: block;" width="600" height="400" loading="lazy">

<p>The <a href="https://genkit.dev/docs/js/devtools/">Genkit Developer UI</a> 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?</p>
<p>The UI is a browser page, but it talks to a <strong>reflection server</strong>: 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.</p>
<p>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).</p>
<p>Create <code>src/dev.ts</code> (entry point for the reflection server):</p>
<pre><code class="language-ts">import './genkit-runtime';
import { serve } from '@hono/node-server';
import app from './app';

serve({ fetch: app.fetch, port: 3781 }, (info) =&gt; {
	console.log(`Hono server listening on http://localhost:${info.port}`);
});
</code></pre>
<p>This serves the same <code>app</code>: the same routes, validation, and flow from Node on port 3781, using <code>@hono/node-server</code>. So there are two runtimes each with its own entry point: <code>src/index.ts</code> is the Worker entry point, <code>src/dev.ts</code> is the Node.js entry point, and everything else is shared.</p>
<p>Add the script to <code>package.json</code>:</p>
<pre><code class="language-json">"genkit:dev": "genkit start -- tsx --env-file=.dev.vars --watch src/dev.ts"
</code></pre>
<p>Run it with your key in the environment. This is the simplest way, since you already have <code>.dev.vars</code>:</p>
<pre><code class="language-bash">pnpm run genkit:dev
</code></pre>
<p>Expected output:</p>
<pre><code class="language-text">Genkit Developer UI: http://localhost:4000
Hono server listening on http://localhost:3781
</code></pre>
<p>Open <a href="http://localhost:4000">http://localhost:4000</a>. You should see <code>explainerFlow</code> in the flows list. Run it with <code>{"topic":"recursion"}</code> and you get an explanation back. This is the same response your Worker returns, served this time by Node.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66e28b713f978a0e2cd2b763/9bb22518-a4b3-4e7a-81a9-f4872bcd0d1b.png" alt="Genkit Dev UI after running the flow (explaining recursion)" style="display: block;" width="600" height="400" loading="lazy">

<p>If the flows list is empty, the reflection server probably shut itself down because <code>GEMINI_API_KEY</code> wasn't in the environment when <code>genkit:dev</code> started.</p>
<h2 id="heading-how-to-deploy-to-cloudflare-workers">How to Deploy to Cloudflare Workers</h2>
<p>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:</p>
<pre><code class="language-bash">pnpm run deploy
</code></pre>
<p>Note that the first time you run any <code>wrangler</code> command, it asks you to authenticate. It:</p>
<ul>
<li>prints a URL</li>
<li>opens your browser</li>
<li>asks you to log in to Cloudflare and authorize Wrangler</li>
</ul>
<p>Authorization returns a token and the CLI picks up the token automatically.</p>
<p>In the deployment process, Wrangler bundles your Worker, uploads it, and prints your live URL thereafter:</p>
<pre><code class="language-text">https://deploy-genkit-apps-on-cloudflare-workers.&lt;your-account&gt;.workers.dev
</code></pre>
<p>Secrets are encrypted and injected as environment variables at runtime. Give your deployed Worker the API key as a secret:</p>
<pre><code class="language-bash">pnpm dlx wrangler secret put GEMINI_API_KEY
</code></pre>
<p>Wrangler prompts you to <code>Enter the secret value:</code> and pastes what you type.</p>
<p>Test the deployed endpoint with curl or Postman:</p>
<pre><code class="language-bash">curl -X POST https://deploy-genkit-apps-on-cloudflare-workers.&lt;your-account&gt;.workers.dev/explain \
  -H 'Content-Type: application/json' \
  -d '{"topic":"microservices"}'
</code></pre>
<p>You receive the JSON explanation as a response. Your Genkit app is now running on Cloudflare's edge!</p>
<p>One note on configuration: this project needs no <code>compatibility_flags</code> configuration in <code>wrangler.json</code>. With a <code>compatibility_date</code> of 2026-11-13, Cloudflare enables <code>nodejs_compat</code> by default, which is what puts environment variables like <code>GEMINI_API_KEY</code> on <code>process.env</code> inside the Worker.</p>
<h2 id="heading-how-to-set-up-groq-as-a-fallback-provider">How to Set Up Groq as a Fallback Provider</h2>
<p>If you prefer to use Groq instead, get your Groq API key from the <a href="https://console.groq.com">Groq console</a>. Install <code>@genkit-ai/compat-oai</code> as a dependency in the project:</p>
<pre><code class="language-bash">pnpm add @genkit-ai/compat-oai
</code></pre>
<p>Add your key to <code>.dev.vars</code> and restart <code>pnpm dev</code>, because wrangler only reads that file at startup:</p>
<pre><code class="language-text">GROQ_API_KEY=your-groq-key
</code></pre>
<p>Swap the plugin and model in <code>src/flows/explainer.ts</code>:</p>
<pre><code class="language-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',
});
</code></pre>
<p>This is the only change required. <code>ai.generate()</code> is provider-agnostic, which is one of Genkit's selling points. The model reference is namespaced as <code>groq/&lt;model&gt;</code>, using the <code>name</code> you gave the plugin.</p>
<p>Test it locally with the same <code>curl</code> command as before. Expected output (abbreviated, wording may vary because AI is non-deterministic):</p>
<pre><code class="language-json">{"explanation":"## What's a \"Microservice\"?\n\nThink of a big software system as a city..."}
</code></pre>
<p>For production, set the secret the same way: <code>pnpm dlx wrangler secret put GROQ_API_KEY</code>.</p>
<h2 id="heading-troubleshooting-common-errors">Troubleshooting Common Errors</h2>
<p>Here are some tips to help you solve common issues you might encounter:</p>
<table>
<thead>
<tr>
<th>Error message</th>
<th>Cause</th>
<th>Fix</th>
</tr>
</thead>
<tbody><tr>
<td><code>TypeError: require_streams(...) is not a function</code> at startup</td>
<td>Genkit's import chain loads express inside workerd</td>
<td>Add the <code>express</code> alias in <code>wrangler.jsonc</code></td>
</tr>
<tr>
<td><code>EvalError: Code generation from strings disallowed</code></td>
<td>A string <code>system</code>/<code>prompt</code> went through dotprompt</td>
<td>Pass prompts as parts: <code>system: [{ text }]</code></td>
</tr>
<tr>
<td><code>FAILED_PRECONDITION: ... set the GEMINI_API_KEY</code></td>
<td>Key missing from the Worker's environment</td>
<td>Add it to <code>.dev.vars</code>, restart <code>pnpm dev</code></td>
</tr>
<tr>
<td>Dev UI loads but shows no flows</td>
<td>Reflection server stopped: key missing when <code>genkit:dev</code> started</td>
<td>Export the key, restart <code>pnpm run genkit:dev</code></td>
</tr>
<tr>
<td><code>503 ... experiencing high demand</code></td>
<td>Provider capacity, not your code</td>
<td>Retry, or switch to the Groq setup above</td>
</tr>
<tr>
<td><code>@cfworker/json-schema</code> warning at startup</td>
<td>Unconditional reminder from <code>setGenkitRuntimeConfig</code></td>
<td>Install the package. The warning is harmless.</td>
</tr>
</tbody></table>
<h2 id="heading-streaming-responses-with-genkit-on-cloudflare-workers">Streaming Responses with Genkit on Cloudflare Workers</h2>
<p>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 <a href="https://genkit.dev/docs/js/deployment/any-platform/#streaming-flow-calls">its deployment guide</a>.</p>
<h2 id="heading-limitations-of-genkit-on-cloudflare-workers">Limitations of Genkit on Cloudflare Workers</h2>
<p>Here are a few limitations worth knowing when deploying Genkit on Workers:</p>
<ul>
<li>The Dev UI and reflection server run in Node only. On Workers, <code>sandboxedRuntime</code> disables them by design. This means that you can't access the Dev UI of your app in production.</li>
<li>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.</li>
<li>Dotprompt string templates are unavailable on Workers. Prompts must be passed as message parts.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>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:</p>
<ul>
<li>interpret-mode schema validation</li>
<li>message-part prompts that bypass dotprompt's <code>new Function()</code> and</li>
<li>the Express stub that keeps Genkit's import chain from crashing <code>workerd</code></li>
</ul>
<p>You also learned how to scale through the hurdles.</p>
<p>Go ahead and build with Genkit and deploy it on Cloudflare.</p>
<p>To see the finished version of the project, check the <code>article/deploy-genkit-on-cloudflare</code> branch of the project non GitHub. If you have any questions, or just want to say hi, reach out to <a href="https://linkedin.com/in/orimdominicadah">Orim Dominic on LinkedIn</a>.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a href="https://genkit.dev/docs/js/deployment/any-platform/#environments-that-restrict-eval">Genkit deployment guide: restricted <code>eval</code> environments</a></li>
<li><a href="https://genkit.dev/docs/js/devtools/">Genkit Developer tools (Developer UI and CLI)</a></li>
<li><a href="https://developers.cloudflare.com/workers/runtime-apis/web-standards/">Cloudflare Workers: <code>eval()</code> and <code>new Function</code> are not allowed</a></li>
<li><a href="https://www.npmjs.com/package/@genkit-ai/compat-oai"><code>@genkit-ai/compat-oai</code> (OpenAI-compatible providers)</a></li>
<li><a href="https://console.groq.com/docs/quickstart">Groq API quickstart</a></li>
<li><a href="https://hono.dev/docs/">Hono</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
