Deploy your React AI app to Vercel with API routes. Replace the Express server with Vercel serverless functions and get a live URL.
Deploy your React AI app to Vercel with API routes. Replace the Express server with Vercel serverless functions and get a live URL.
Vercel runs API routes as serverless functions. Instead of an Express server, you create files in an api/ folder. Each file becomes an endpoint. Vercel handles deployment, scaling, and cold starts.
my-ai-app/ ├── api/ ← Vercel API routes │ ├── chat.js ← POST /api/chat │ └── upload.js ← POST /api/upload ├── src/ │ ├── App.jsx │ └── ... ├── public/ └── vite.config.js
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { messages, system } = req.body;
try {
const response = await client.messages.create({
model: 'claude-3-haiku-20240307',
max_tokens: 1024,
system: system || 'You are a helpful assistant.',
messages: messages,
});
res.json({ content: response.content[0].text });
} catch (err) {
res.status(500).json({ error: err.message });
}
}
export const config = { runtime: 'edge' }. The Edge Runtime supports streaming responses directly. Standard Node.js functions don't support SSE.{
"rewrites": [
{ "source": "/api/(.*)", "destination": "/api/$1" }
],
"buildCommand": "npm run build",
"outputDirectory": "dist"
}
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': 'http://localhost:3000' // proxy to Vercel dev server
}
}
});
# 1. Install Vercel CLI npm install -g vercel # 2. Login vercel login # 3. Link your project (run once from project root) vercel link # 4. Set environment variables vercel env add ANTHROPIC_API_KEY # 5. Deploy vercel --prod # You'll get a URL like: https://my-ai-app.vercel.app
Never commit API keys. Vercel stores them securely and injects them at runtime.
# Add via CLI vercel env add ANTHROPIC_API_KEY production # Or add via Vercel dashboard: # Project Settings → Environment Variables → Add # Verify locally vercel env pull .env.local # pulls production vars to a local .env.local file # Don't commit .env.local
.env.local and .env to .gitignore before your first commit. If you accidentally commit an API key, rotate it immediately.# Add a domain you own vercel domains add yourdomain.com # Or use a free .vercel.app subdomain # Your app is automatically at: project-name.vercel.app
Before moving on, confirm understanding of these key concepts: