Skip to main content

Express with AI SDK

Learn how to integrate the AI SDK into Express applications to create AI-powered HTTP endpoints.

Why Express?

Express is a minimal and flexible Node.js framework ideal for:
  • Building AI API endpoints
  • Creating microservices
  • Adding AI to existing Express apps
  • Simple deployment options

Prerequisites

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

Quick Start

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

Basic Text Streaming

Stream AI-generated text to clients:
Run the server:
Test with curl:

UI Message Stream

Stream messages in a format compatible with useChat:

Text-Only Stream

Stream plain text without message formatting:

Custom Data Streaming

Send custom data alongside AI responses:

Tool Calling

Implement tools for extended functionality:

Structured Output

Generate structured JSON responses:

Error Handling

Implement comprehensive error handling:

Middleware

Rate Limiting

Authentication

Production Setup

Project Structure

Example Routes Structure

Build and Run

Deployment

Docker

Railway/Render

Both platforms support Express apps with minimal configuration:
  1. Connect your GitHub repository
  2. Set environment variables
  3. Deploy

Best Practices

  1. Use Environment Variables: Never hardcode API keys
  2. Implement Rate Limiting: Protect against abuse
  3. Add CORS: Allow frontend requests
  4. Handle Errors: Provide meaningful error messages
  5. Log Requests: Monitor usage and debug issues
  6. Use TypeScript: Catch errors at compile time
  7. Validate Input: Sanitize user input

Troubleshooting

Streaming Not Working

Ensure you’re not using compression middleware before streaming:

Example Repository

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

Resources