Skip to main content

Fastify with AI SDK

Learn how to integrate the AI SDK into Fastify applications for high-performance AI endpoints.

Why Fastify?

Fastify is an excellent choice for AI applications:
  • Fast: Low overhead framework optimized for speed
  • Schema-based: Built-in JSON schema validation
  • Plugin System: Extensible architecture
  • TypeScript: First-class TypeScript support
  • Logging: Built-in structured logging

Prerequisites

  • Node.js 18+
  • Basic knowledge of Fastify
  • Vercel AI Gateway API key

Quick Start

Create a new project:
Install dependencies:
Configure TypeScript:
Set environment variables:

Basic Streaming

Stream AI responses with Fastify:
Run the server:
Test with curl:

UI Message Stream

Stream messages compatible with useChat:

Text-Only Stream

Stream plain text responses:

Custom Data Streaming

Send custom data with AI responses:

Tool Calling

Implement AI tools with Fastify:

Structured Output

Generate structured JSON with schema validation:

Schema Validation

Use Fastify’s built-in schema validation:

Plugins

Rate Limiting Plugin

Authentication Plugin

Use plugins:

Error Handling

Global error handler:

Production Setup

Project Structure

Routes as Plugins

Build Scripts

Deployment

Docker

Environment Variables

Performance Tips

  1. Enable HTTP/2: For better streaming performance
  2. Use Async/Await: Properly handle promises
  3. Connection Pooling: Reuse database connections
  4. Caching: Cache frequent responses
  5. Compression: Use for non-streaming routes

Best Practices

  1. Use Plugins: Modular architecture
  2. Schema Validation: Validate all inputs
  3. Logging: Use Fastify’s built-in logger
  4. Error Handling: Centralized error handling
  5. TypeScript: Full type safety
  6. Testing: Write tests for routes

Example Repository

View the complete example: github.com/vercel/ai/examples/fastify

Resources