#nextjs
#capstone
#ai
#vercel-ai-sdk
Day 29 β Capstone Project I: Planning & AI Chatbot
π§ Day 29 β Capstone Project I: Planning & AI Chatbot
Zero to Hero β Hands-on Next.js Tutorial
Congratulations! Youβve learned all the core concepts. Now, for the final 2 days, we will build a real-world, modern application.
The Project: An AI Chatbot (Clone of ChatGPT). The Stack: Next.js 14, Tailwind, Vercel AI SDK, OpenAI API.
π¦ 1. The Architecture
- Frontend: Client Components for the Chat UI (Input, Bubble, Scroll).
- Backend: A Route Handler (
/api/chat) to stream the AI response. - State: The
useChathook from Vercel AI SDK manages everything.
π© 2. Setup
npx create-next-app@latest ai-chat
npm install ai openai
Get your OpenAI Key and put it in .env.local.
π§ 3. The Backend (api/chat/route.ts)
This uses standard Response streams. Use the Edge runtime for speed!
import { OpenAIStream, StreamingTextResponse } from 'ai';
import OpenAI from 'openai';
// Optional, but recommended: run on the edge!
export const runtime = 'edge';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function POST(req: Request) {
const { messages } = await req.json();
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
stream: true,
messages,
});
const stream = OpenAIStream(response);
return new StreamingTextResponse(stream);
}
π₯ 4. The Frontend (page.tsx)
'use client';
import { useChat } from 'ai/react';
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
<div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
{messages.map(m => (
<div key={m.id} className="whitespace-pre-wrap">
{m.role === 'user' ? 'User: ' : 'AI: '}
{m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
value={input}
placeholder="Say something..."
onChange={handleInputChange}
/>
</form>
</div>
);
}
π§ͺ Challenge: Day 29
- Initialize the project.
- Get it running with your API Key.
- Send a message βHelloβ.
- Watch the text stream in character-by-character. (Thatβs the power of the AI SDK + Next.js Streaming!).
See you tomorrow for the Final Polish & Deployment! π