Frontend

Open your root page and replace it's contents with the following:

app/page.tsx
export default function ChatPage() {
  return <div>Hello, world.</div>;
}

Mark the page as a client component.

app/page.tsx
"use client"

export default function ChatPage() {
  return <div>Hello, world.</div>;
}

Note: we are marking the page as a client component because we will be using hooks and interactivity.

Import and call useChat.

app/page.tsx
"use client";

import { useChat } from "ai/react"; 

export default function ChatPage() {
  const { } = useChat(); 
  return <div>Hello, world.</div>;
}

Destructure messages from useChat and then iterate over them in the UI.

app/page.tsx
"use client";

import { useChat } from "ai/react";

export default function Chat() {
  const { messages } = useChat(); 
  return (
    <div>
      {messages.map((m) => ( 
        <div key={m.id}>
          {m.role === "user" ? "User: " : "AI: "}
          {m.content}
        </div> 
      ))}
    </div>
  );
}

Destructure input, handleInputChange, and handleSubmit from useChat. Render a form and use the newly destructured items to handle the state.

app/page.tsx
"use client";

import { useChat } from "ai/react";

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat(); 
  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          {m.role === "user" ? "User: " : "AI: "}
          {m.content}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input
          value={input} 
          placeholder="Say something..."
          onChange={handleInputChange} 
        />
      </form>
    </div>
  );
}

Done! Run the dev server.

npm run dev

Head to localhost:3000 and send a message to your chatbot!