/** * Next.js Pages Router - Complete Chat Example * * Complete production-ready chat interface for Next.js Pages Router. * * Features: * - v5 useChat with manual input management * - Auto-scroll to bottom * - Loading states & error handling * - Stop generation button * - Responsive design * * Directory structure: * pages/ * ├── chat.tsx (this file) * └── api/ * └── chat.ts (see nextjs-api-route.ts) * * Usage: * 1. Copy to pages/chat.tsx * 2. Create API route at pages/api/chat.ts (see nextjs-api-route.ts) * 3. Navigate to /chat */ import { useChat } from 'ai/react'; import { useState, FormEvent, useRef, useEffect } from 'react'; import Head from 'next/head'; export default function ChatPage() { const { messages, sendMessage, isLoading, error, stop } = useChat({ api: '/api/chat', }); const [input, setInput] = useState(''); const messagesEndRef = useRef(null); // Auto-scroll to bottom useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (!input.trim() || isLoading) return; sendMessage({ content: input }); setInput(''); }; return ( <> AI Chat
{/* Header */}

AI Chat

Powered by AI SDK v5 (Pages Router)

{/* Messages */}
{messages.length === 0 ? ( // Empty state
💬

Start a conversation

Type a message below to begin

) : ( // Messages list
{messages.map((message) => (
{message.content}
))} {isLoading && (
)}
)}
{/* Error */} {error && (
Error: {error.message}
)} {/* Input */}
setInput(e.target.value)} placeholder="Type a message..." disabled={isLoading} className="flex-1 p-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100" /> {isLoading ? ( ) : ( )}
); }