An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix: resolve chatId duplication error in Next.js 16
Yoshiki Miurab56df4c1a2fd
diff --git a/app/page.tsx b/app/page.tsxindex b2ce0b5b..7314a0e3 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -1,14 +1,11 @@-import { generateId } from '@/lib/db/schema'-import { BetaBadge } from '@/components/beta-badge'import { ChangelogBanner } from '@/components/changelog-banner'import { Chat } from '@/components/chat'export default async function Page() {- const id = generateId()return (<>- <Chat id={id} />+ <Chat /><ChangelogBanner /><BetaBadge /></>diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex 87a7d948..c423811d 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -41,6 +41,8 @@ interface ChatPanelProps {scrollContainerRef: React.RefObject<HTMLDivElement>uploadedFiles: UploadedFile[]setUploadedFiles: React.Dispatch<React.SetStateAction<UploadedFile[]>>+ /** Callback to reset chatId when starting a new chat */+ onNewChat?: () => void}export function ChatPanel({@@ -57,7 +59,8 @@ export function ChatPanel({showScrollToBottomButton,uploadedFiles,setUploadedFiles,- scrollContainerRef+ scrollContainerRef,+ onNewChat}: ChatPanelProps) {const router = useRouter()const inputRef = useRef<HTMLTextAreaElement>(null)@@ -84,6 +87,8 @@ export function ChatPanel({// Reset focus state when clearing chatsetIsInputFocused(false)inputRef.current?.blur()+ // Reset chatId in parent component+ onNewChat?.()router.push('/')}diff --git a/components/chat.tsx b/components/chat.tsxindex e7806039..ef477f4b 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -33,14 +33,33 @@ interface ChatSection {}export function Chat({- id,+ id: providedId,savedMessages = [],query}: {- id: string+ id?: stringsavedMessages?: UIMessage[]query?: string}) {+ // Generate a stable chatId on the client side+ // - If providedId exists (e.g., /search/[id]), use it for existing chats+ // - Otherwise, generate a new ID (e.g., / homepage for new chats)+ const [chatId, setChatId] = useState(() => providedId || generateId())++ // Update chatId if providedId changes (e.g., navigating to different chat)+ useEffect(() => {+ if (providedId && providedId !== chatId) {+ setChatId(providedId)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [providedId])++ // Callback to reset chatId when user clicks "New" button+ const handleNewChat = () => {+ const newId = generateId()+ setChatId(newId)+ }+const scrollContainerRef = useRef<HTMLDivElement>(null)const [isAtBottom, setIsAtBottom] = useState(true)const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])@@ -68,7 +87,7 @@ export function Chat({addToolResult,error} = useChat({- id, // use the provided chatId+ id: chatId, // use the client-generated or provided chatIdtransport: new DefaultChatTransport({api: '/api/chat',prepareSendMessagesRequest: ({ messages, trigger, messageId }) => {@@ -82,7 +101,7 @@ export function Chat({return {body: {trigger, // Use AI SDK's default trigger value directly- chatId: id,+ chatId: chatId,messageId,message:trigger === 'regenerate-message' &&@@ -251,7 +270,7 @@ export function Chat({useEffect(() => {// Only scroll if this chat is currently visible in the URLconst isCurrentChat =- window.location.pathname === `/search/${id}` ||+ window.location.pathname === `/search/${chatId}` ||(window.location.pathname === '/' && sections.length > 0)if (isCurrentChat && sections.length > 0) {@@ -265,7 +284,7 @@ export function Chat({})}}- }, [sections, messages, id])+ }, [sections, messages, chatId])const onQuerySelect = (query: string) => {sendMessage({@@ -278,10 +297,10 @@ export function Chat({editedMessageId: string,newContentText: string) => {- if (!id) {+ if (!chatId) {toast.error('Chat ID is missing.')console.error(- 'handleUpdateAndReloadMessage: chatId (id prop) is undefined.'+ 'handleUpdateAndReloadMessage: chatId is undefined.')return}@@ -314,7 +333,7 @@ export function Chat({}const handleReloadFrom = async (reloadFromFollowerMessageId: string) => {- if (!id) {+ if (!chatId) {toast.error('Chat ID is missing for reload.')return}@@ -365,7 +384,7 @@ export function Chat({// Push URL state immediately after sending message (for new chats)// Check if we're on the root path (new chat)if (window.location.pathname === '/') {- window.history.pushState({}, '', `/search/${id}`)+ window.history.pushState({}, '', `/search/${chatId}`)}}}@@ -374,7 +393,7 @@ export function Chat({useFileDropzone({uploadedFiles,setUploadedFiles,- chatId: id+ chatId: chatId})return (@@ -392,7 +411,7 @@ export function Chat({sections={sections}onQuerySelect={onQuerySelect}status={status}- chatId={id}+ chatId={chatId}addToolResult={({toolCallId,result@@ -435,7 +454,7 @@ export function Chat({error={error}/><ChatPanel- chatId={id}+ chatId={chatId}input={input}handleInputChange={handleInputChange}handleSubmit={onSubmit}@@ -451,6 +470,7 @@ export function Chat({uploadedFiles={uploadedFiles}setUploadedFiles={setUploadedFiles}scrollContainerRef={scrollContainerRef}+ onNewChat={handleNewChat}/><DragOverlay visible={isDragging} /><AuthModal open={showAuthModal} onOpenChange={setShowAuthModal} />