/** * Next.js App Router - Complete Chat Example * * Complete production-ready chat interface for Next.js App Router. * * Features: * - v5 useChat with manual input management * - Auto-scroll to bottom * - Loading states & error handling * - Stop generation button * - Responsive design * - Keyboard shortcuts (Enter to send, Cmd+K to clear) * * Directory structure: * app/ * ├── chat/ * │ └── page.tsx (this file) * └── api/ * └── chat/ * └── route.ts (see nextjs-api-route.ts) * * Usage: * 1. Copy to app/chat/page.tsx * 2. Create API route (see nextjs-api-route.ts) * 3. Navigate to /chat */ 'use client'; import { useChat } from 'ai/react'; import { useState, FormEvent, useRef, useEffect } from 'react'; export default function ChatPage() { const { messages, sendMessage, isLoading, error, stop, reload } = useChat({ api: '/api/chat', onError: (error) => { console.error('Chat error:', error); }, }); const [input, setInput] = useState(''); const messagesEndRef = useRef(null); const inputRef = useRef(null); // Auto-scroll to bottom when new messages arrive useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); // Focus input on mount useEffect(() => { inputRef.current?.focus(); }, []); const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (!input.trim() || isLoading) return; sendMessage({ content: input }); setInput(''); }; // Keyboard shortcuts const handleKeyDown = (e: React.KeyboardEvent) => { // Cmd+K or Ctrl+K to clear (focus input) if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); inputRef.current?.focus(); } }; return (
{/* Header */}

AI Assistant

{messages.length > 0 ? `${messages.length} message${messages.length === 1 ? '' : 's'}` : 'Start a conversation'}

{messages.length > 0 && !isLoading && ( )}
{/* Messages */}
{messages.length === 0 ? ( // Empty state
💬

Start a conversation

Ask me anything or try one of these:

{[ 'Explain quantum computing', 'Write a haiku about coding', 'Plan a trip to Tokyo', ].map((suggestion, idx) => ( ))}
) : ( // Messages list
{messages.map((message, idx) => (
{/* Role label (only for assistant on first message) */} {message.role === 'assistant' && idx === 1 && (
AI Assistant
)} {/* Message content */}
{message.content}
))} {/* Loading indicator */} {isLoading && (
Thinking...
)}
)}
{/* Error banner */} {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 ? ( ) : ( )}
Press Enter to send • Cmd+K to focus input
); }