Server Actions for AI Intermediate
Next.js Server Actions let you run AI operations on the server without creating separate API routes. Combined with generateText and streamText, they provide a clean, secure way to call AI models from your components.
Why Server Actions for AI?
Server Actions are ideal for AI operations because:
- Security — API keys stay on the server, never reaching the client
- Simplicity — No need to create separate API routes for each AI operation
- Type safety — Full TypeScript support with input validation
- Progressive enhancement — Forms work even without JavaScript
Basic Server Action with AI
TypeScript - app/actions.ts
'use server'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; export async function summarize(text: string) { const { text: summary } = await generateText({ model: openai('gpt-4o'), prompt: `Summarize this text in 2-3 sentences:\n\n${text}`, }); return summary; }
Using Server Actions in Components
TypeScript - app/summarizer/page.tsx
'use client'; import { useState } from 'react'; import { summarize } from '../actions'; export default function SummarizerPage() { const [summary, setSummary] = useState(''); const [loading, setLoading] = useState(false); async function handleSubmit(formData: FormData) { setLoading(true); const text = formData.get('text') as string; const result = await summarize(text); setSummary(result); setLoading(false); } return ( <form action={handleSubmit}> <textarea name="text" placeholder="Paste text to summarize..." /> <button type="submit" disabled={loading}> {loading ? 'Summarizing...' : 'Summarize'} </button> {summary && <div>{summary}</div>} </form> ); }
Streaming with Server Actions
For longer AI responses, you can stream results from Server Actions using the createStreamableValue utility:
TypeScript - app/actions.ts
'use server'; import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { createStreamableValue } from 'ai/rsc'; export async function generate(prompt: string) { const stream = createStreamableValue(''); (async () => { const { textStream } = await streamText({ model: openai('gpt-4o'), prompt, }); for await (const delta of textStream) { stream.update(delta); } stream.done(); })(); return { output: stream.value }; }
When to Use What: Use route handlers with
useChat for conversational chat interfaces. Use Server Actions with generateText for one-shot AI operations like summarization, translation, or classification.
Server Actions Mastered!
You can now run AI operations securely on the server. Next, learn to build advanced streaming UIs with generative components.
Next: Streaming UI →