Introduction
Building an AI chatbot from scratch used to mean: wire up OpenAI's API, manage message history manually, implement streaming with Server-Sent Events, and build the UI on top. It took days.
The Vercel AI SDK abstracts all of this into a handful of hooks and utilities. Here's how to build a working, streaming chatbot in Next.js in under an hour.
Step 1: Create a Next.js app and install dependencies
npx create-next-app@latest my-chatbot --typescript --tailwind --app
cd my-chatbot
npm install ai @ai-sdk/openaiAdd your OpenAI API key to .env.local:
OPENAI_API_KEY=sk-your-key-hereStep 2: Create the API route
Create app/api/chat/route.ts:
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai("gpt-4o"),
system: "You are a helpful assistant.",
messages,
});
return result.toDataStreamResponse();
}
That's the entire backend. The streamText function handles the OpenAI call and toDataStreamResponse() returns a streaming response the SDK's frontend hooks understand.
Step 3: Build the chat UI
Create app/page.tsx:
"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();
return (
{messages.map((message) => (
<div
key={message.id}
className={p-3 rounded-lg ${ message.role === "user" ? "bg-blue-100 ml-auto max-w-xs" : "bg-gray-100 mr-auto max-w-md" }}
>
{message.content}
))}
{isLoading && (
Thinking...
)}
<form onSubmit={handleSubmit} className="flex gap-2">
<input
value={input}
onChange={handleInputChange}
placeholder="Ask anything..."
className="flex-1 border rounded-lg px-4 py-2"
/>
<button
type="submit"
disabled={isLoading}
className="bg-black text-white px-4 py-2 rounded-lg disabled:opacity-50"
>
Send
</button>
</form>
</div>
);
}
Step 4: Run and deploy
npm run devOpen localhost:3000 — your chatbot is live. Message history is maintained automatically by useChat. Responses stream in token by token.
To deploy to Vercel:
npx vercel --prodAdd OPENAI_API_KEY to your Vercel environment variables and you're done.
What to add next
- Swap the model to
gpt-4o-minifor cheaper responses - Add a system prompt to give your bot a personality
- Persist chat history to a database with Prisma
- Add authentication with Clerk so users have private chats
Conclusion
The Vercel AI SDK turns what used to be a multi-day project into a one-hour build. The useChat hook handles everything — message state, streaming, loading states — so you can focus on making your chatbot actually useful.
