Index of every page on this site: llms.txt
All skills
genkit-ai avatar

/developing-genkit-js

@d12c988
by Genkitgenkit-ai/skills40 stars
13
Run it yourself

Provides guidance on developing AI-powered applications using Genkit in Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or tools in JavaScript/TypeScript, or when encountering Genkit errors, validation issues, type errors, or API problems. Don't use for Genkit in Python, Go, or Dart.

Use this Skill: https://skilld.dev/gh/genkit-ai/skills/developing-genkit-js

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesagents-deployment.md

≈1.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Deploying / Serving Agents over HTTP (Beta)

Beta / preview API. Uses expressHandler from @genkit-ai/express and the agent's beta companion actions. Read agents.md first.

An agent is served as an HTTP endpoint with expressHandler. Most agents also expose two companion actions:

  • agent.getSnapshotDataAction → POST /api/<name>/getSnapshot — read a snapshot's state. Needed for snapshot restore and background polling.
  • agent.abortAgentAction → POST /api/<name>/abort — cancel a background turn.

These paths match the remoteAgent client defaults (${url}/getSnapshot, ${url}/abort), so a client only needs the base url.


A reusable exposeAgent helper

When serving several agents, a small helper keeps registration consistent.

import { expressHandler } from '@genkit-ai/express';
import { Agent } from 'genkit/beta';
import express from 'express';

const app = express();
app.use(express.json());

// Register an agent at `/api/<name>`, optionally wiring up its companion
// `/getSnapshot` and `/abort` sub-actions.
function exposeAgent(
  name: string,
  agent: Agent,
  opts: { snapshot?: boolean; abort?: boolean } = {}
) {
  app.post(`/api/${name}`, expressHandler(agent));
  if (opts.snapshot) {
    app.post(
      `/api/${name}/getSnapshot`,
      expressHandler(agent.getSnapshotDataAction)
    );
  }
  if (opts.abort) {
    app.post(`/api/${name}/abort`, expressHandler(agent.abortAgentAction));
  }
}

// Plain conversational agent - no companions needed:
exposeAgent('weatherAgent', weatherAgent);

// Snapshot restore / branching - needs getSnapshot:
exposeAgent('branchingAgent', branchingAgent, { snapshot: true });

// Background agent - needs both getSnapshot (polling) and abort:
exposeAgent('backgroundAgent', backgroundAgent, { snapshot: true, abort: true });

app.listen(process.env.PORT ? parseInt(process.env.PORT) : 8080);

Which companions to enable:

Agent capability snapshot abort
Plain chat (client- or server-state) – –
Snapshot restore / branching ✓ –
Background / detach ✓ ✓

CORS for browser clients

A browser remoteAgent calling a different origin (e.g. a Vite dev server) needs CORS. Streaming requires the X-Genkit-Stream-Id header to be allowed on the request and exposed on the response.

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, Accept, X-Genkit-Stream-Id'
  );
  res.header('Access-Control-Expose-Headers', 'X-Genkit-Stream-Id');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  if (req.method === 'OPTIONS') {
    res.sendStatus(204);
    return;
  }
  next();
});

Serving a static web UI (optional)

To ship a single server that hosts both the API and a built SPA, serve the static bundle and add a non-/api fallback so client-side routing works on deep links / reloads.

import { existsSync } from 'node:fs';
import { join } from 'node:path';

const webDist = join(__dirname, '..', 'web', 'dist');
if (existsSync(webDist)) {
  app.use(express.static(webDist));
  // SPA fallback - send index.html for any non-API GET request.
  app.get(/^\/(?!api\/).*/, (_req, res) => {
    res.sendFile(join(webDist, 'index.html'));
  });
}

Registering agents/flows

Agents and flows must be imported so they register with Genkit. Side-effect imports work, but explicitly referencing them makes the available actions clear:

import { weatherAgent } from './weather-agent.js';
import { backgroundAgent } from './background-agent.js';

// Force-reference so the modules' top-level defineAgent/defineFlow run.
void [weatherAgent, backgroundAgent];

You can also expose plain flows the same way (e.g. helper endpoints):

app.post('/api/workspace/files', expressHandler(listWorkspaceFiles));

Other host frameworks

expressHandler is one of several adapters — an agent is just an action, so any of these works. Expose the companion actions (agent.getSnapshotDataAction, agent.abortAgentAction) at the matching sub-paths the same way when you need snapshot restore / background.

Next.js (@genkit-ai/next)

appRoute turns an agent into an App Router route handler. Put companions in their own route files.

// app/api/weatherAgent/route.ts
import { appRoute } from '@genkit-ai/next';
import { weatherAgent } from '@/lib/agents';

export const POST = appRoute(weatherAgent);

// app/api/weatherAgent/getSnapshot/route.ts
export const POST = appRoute(weatherAgent.getSnapshotDataAction);

Web Fetch (@genkit-ai/fetch)

Works with any Fetch-API runtime (Hono, Bun, Deno, Cloudflare Workers, Vercel/ Netlify Edge, etc.). fetchHandler(action) returns (request) => Promise<Response>; fetchHandlers(actions, prefix) path-routes multiple actions by name.

import { fetchHandler } from '@genkit-ai/fetch';
import { Hono } from 'hono';
import { weatherAgent } from './agents.js';

const app = new Hono();
app.all('/api/weatherAgent', (c) => fetchHandler(weatherAgent)(c.req.raw));
app.all('/api/weatherAgent/getSnapshot', (c) =>
  fetchHandler(weatherAgent.getSnapshotDataAction)(c.req.raw)
);

Fastify (@genkit-ai/fastify)

import Fastify from 'fastify';
import { fastifyHandler } from '@genkit-ai/fastify';
import { weatherAgent } from './agents.js';

const app = Fastify();
app.post('/api/weatherAgent', fastifyHandler(weatherAgent));
app.post(
  '/api/weatherAgent/getSnapshot',
  fastifyHandler(weatherAgent.getSnapshotDataAction)
);
await app.listen({ port: 8080 });

The @genkit-ai/vercel-ai plugin additionally offers a GenkitChatTransport for the Vercel AI SDK's useChat, which tracks the chatId → snapshotId mapping for you (no client SessionStore needed).

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts13d5 checks · Risk SAFE
  • Gen Agent Trust Hub14d

    The skill is a comprehensive development guide for the Genkit JS framework. It provides technical instructions, code examples, and troubleshooting steps. All referenced tools and packages are official or standard industry dependencies. No security risks were identified.

  • Socket13d

    No alerts

  • Snyk14d

    Risk: LOW · No issues

  • Runlayer8mo

    6 files scanned · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at d12c988. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 2 weeks ago
metadata
{
  "version": "1.0.0",
  "category": "AiAndMachineLearning"
}
  • TypeScript
  • genkit
  • nodejs
  • ai-agents
  • flows
  • llm
  • google-ai
  • openai
  • anthropic

README badge

README badge for genkit-ai/skills/developing-genkit-js

Develop AI-powered applications using Genkit in Node.js and TypeScript, including flows, tools, and multi-model integrations. Covers Genkit CLI setup, flow definition with schema validation, provider selection (Google AI, OpenAI, Anthropic, Ollama), and error troubleshooting for version 1.29.0 and later.

Generated from the current SKILL.md.

What Genkit CLI version does this skill require?
Minimum CLI version 1.29.0. Verify with `genkit --version` and upgrade with `npm install -g genkit-cli@^1.29.0` if needed.
Does this skill cover pre-1.0 Genkit or older versions?
No. Genkit went through a major breaking API change. This skill assumes v1.x (1.29.0+) and will not reliably handle pre-1.0 code or deprecated APIs.
What AI providers does this skill support?
Genkit is provider-agnostic and supports Google AI, OpenAI, Anthropic, Ollama, and others. The skill defaults to Google AI if no provider is specified.
How should I troubleshoot Genkit errors?
Always read the Common Errors reference first to identify known patterns and their fixes. Use `genkit docs:search` only if the error is not documented there.
Does this skill work with Next.js, Firebase, or Express?
Yes. The skill detects your framework via package.json and adapts the implementation to framework-specific patterns like @genkit-ai/next or @genkit-ai/firebase.

Generated from the current SKILL.md. These answers refresh after source changes.