Fastify

Integrate Better Agent with Fastify.

Integrate Better Agent with Fastify by creating your app and mounting its HTTP handler.

Create the app

Start with a normal Better Agent server module.

server.ts
import { betterAgent, defineAgent } from "@better-agent/core";
import { createOpenAI } from "@better-agent/providers/openai";

const openai = createOpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const assistant = defineAgent({
  name: "assistant",
  model: openai.text("gpt-5-mini"),
  instruction: "You are a concise assistant. Keep replies short and natural.",
});

const agentApp = betterAgent({
  agents: [assistant],
  baseURL: "/api",
  secret: "dev-secret",
});

export default agentApp;

Mount the handler

Use the Fastify adapter to bridge Fastify request and reply objects into Better Agent's standard handler.

src/index.ts
import Fastify from "fastify";
import { toFastifyHandler } from "@better-agent/adapters/fastify";
import agentApp from "./server";

const app = Fastify();

app.all("/api/*", toFastifyHandler(agentApp));

await app.listen({ port: 3000 });

Keep baseURL and the mounted route aligned. If the Better Agent app uses baseURL: "/api", mount it under /api.