Web Chat UI
A streaming chat interface built with Next.js, Tailwind CSS, and the Vercel AI SDK.
Wired up the frontend to the OpenAI API using the Vercel AI SDK v6 streaming pipeline.
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: openai('gpt-4o-mini'),
system: systemPrompt || 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
});
return result.toUIMessageStreamResponse();Key concepts:
- UI messages vs Model messages — The frontend uses
UIMessage(has.parts,.id, metadata). The model API expects a flatModelMessageformat ({ role, content }).convertToModelMessagesbridges the two. Managing this gap between app format and model format is a recurring pattern in AI engineering. toUIMessageStreamResponse()— Returns a structured stream with text deltas, step boundaries, finish reason, and token usage. This is what powers theuseChathook's state on the client. Different from a plain text stream — it carries metadata the UI needs.
const { messages, sendMessage, status, stop, error, regenerate } = useChat({
transport: new DefaultChatTransport({ api: '/api/chat' }),
});One hook manages the entire chat lifecycle:
| Property | What it does |
|---|---|
messages |
Full conversation history, updated token-by-token as the stream arrives |
status |
'ready' / 'submitted' / 'streaming' / 'error' — maps to the LLM request lifecycle |
stop |
Aborts the stream mid-generation (saves tokens + improves UX) |
regenerate |
Retries the last assistant message |
Why this matters for AI engineering: LLMs are stateless — the full conversation history is re-sent on every request. The useChat hook handles this automatically. Understanding that statefulness lives in the client, not the model, is foundational.
Refactored into a clean component tree with the 'use client' boundary pushed as far down as possible.
app/
├── page.tsx ← Server Component, renders <Chat />
├── api/chat/route.ts ← Streaming API route
└── components/
├── Chat.tsx ← 'use client' — owns useChat state, passes props down
├── MessageList.tsx ← Pure display: maps messages, thinking indicator, error state
├── MessageBubble.tsx ← Single message: role badge + bubble styling
├── MarkdownContent.tsx ← Renders assistant message text as Markdown
└── ChatInput.tsx ← 'use client' — owns textarea state, auto-grow, submit logic
Key decisions:
page.tsxstays a server component — no JavaScript shipped for the outer shell'use client'boundary is atChat.tsx, not at the page levelMessageListandMessageBubbleare pure display components with no hooks — stateless and easy to extendChatInputhas its own'use client'since it owns local input state independently of the chat
- Auto-grow moved from an
onInputDOM event handler to auseEffectwatchinginputstate — height stays in sync with React's state, including auto-reset on send - Send/Stop text labels replaced with SVG icon buttons; textarea is no longer disabled during streaming so the user can type ahead
- Minor UX tweaks: taller max height, smooth height transition
OpenAI returns plain text that uses Markdown syntax (e.g. **bold**, fenced code blocks, tables). Previously these rendered as raw characters. Now assistant messages are parsed and displayed as formatted Markdown.
- OpenAI sends a plain text string — no styling metadata, just Markdown conventions baked into the text
MessageBubbleroutes assistant text parts throughMarkdownContentand renders user messages as plainwhitespace-pre-wraptext (users don't write Markdown)MarkdownContentusesreact-markdownwithremarkGfmto parse the string into HTML
| Library | Role |
|---|---|
react-markdown |
Parses CommonMark syntax and renders React elements |
remarkGfm |
Extends CommonMark with GFM: tables, strikethrough, task lists, autolinks |
@tailwindcss/typography |
prose base styles for headings, paragraphs, lists |
components prop |
Overrides <code> and <pre> with custom Tailwind styling for inline code and code blocks |
Introduced multi-conversation support. Users can create, switch between, and delete conversations, all persisted to localStorage.
app/
├── page.tsx ← now renders <ChatApp /> instead of <Chat />
└── components/
├── ChatApp.tsx ← 'use client' — owns all conversation state, persists to localStorage
├── Sidebar.tsx ← conversation list, new/delete actions, responsive (mobile overlay)
├── Chat.tsx ← now accepts initialMessages + onMessagesChange props
└── MessageList.tsx ← added auto-scroll (smart: only scrolls if user is near bottom)
ChatAppas the state owner — all conversation data lives here.Chatis now a controlled component that receives its messages as a prop and calls back when they change.localStoragepersistence — conversations are loaded on mount and saved whenever state changes. Ahydratedflag prevents a SSR/client mismatch on first render.- Auto-title — a conversation titled "New chat" is automatically renamed to the first 40 characters of the user's first message (
deriveTitleinapp/lib/conversations.ts). - Callback timing —
Chatpersists on two events: when the user sends a message (viauseEffectwatching message length) and when the assistant finishes responding (viaonFinish+queueMicrotask). Refs are used so the callbacks always capture the latest state without becoming stale closures. key={activeConversation.id}— switching conversations unmounts and remounts<Chat>entirely, giving each conversation a freshuseChatinstance seeded with its saved messages.
# Add your OpenAI key
echo "OPENAI_API_KEY=sk-..." > .env.local
npm install
npm run devOpen http://localhost:3000.