#Add Chat in Next js app router

1 messages · Page 1 of 1 (latest)

vocal lionBOT
#

Hi @cloud magnet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To add chat functionality in a Next.js application using the App Router, you can follow these steps:

Step 1: Create the Chat Component

First, create a Chat component that will render the chat interface. This component will display the list of messages and the input form for the user to send messages.

Create a file named Chat.tsx inside your components directory and add the following code:

// components/Chat.tsx
import React, { FormEvent, ChangeEvent } from "react";
import Messages from "./Messages";
import { Message } from "ai/react";

interface ChatProps {
  input: string;
  handleInputChange: (e: ChangeEvent<HTMLInputElement>) => void;
  handleMessageSubmit: (e: FormEvent<HTMLFormElement>) => Promise<void>;
  messages: Message[];
}

const Chat: React.FC<ChatProps> = ({ input, handleInputChange, handleMessageSubmit, messages }) => {
  return (
    <div id="chat" className="...">
      <Messages messages={messages} />
      <form onSubmit={handleMessageSubmit} className="...">
        <input
          type="text"
          className="..."
          value={input}
          onChange={handleInputChange}
        />
        <span className="...">Press ⮐ to send</span>
      </form>
    </div>
  );
};

export default Chat;

Step 2: Create the Page Component

Next, create a page.tsx file inside the app/chat/ directory and add the following code. This will use the useChat hook from the Vercel AI SDK to manage the chat state.

// app/chat/page.tsx
'use client';
import Header from "@/components/Header";
import Chat from "@/components/Chat";
import { useChat } from "ai/react";
import { useState } from "react";

const Page: React.FC = () => {
  const [context, setContext] = useState<string[] | null>(null);
  const { messages, input, handleInputChange, handleSubmit } = useChat();
#

return (
<div className="...">
<Header className="..." />
<div className="...">
<Chat
input={input}
handleInputChange={handleInputChange}
handleMessageSubmit={handleSubmit}
messages={messages}
/>
</div>
</div>
);
};

export default Page;


### Step 3: Create the Route Handler

Finally, create a route handler to stream in your chat response from OpenAI. Create a file named `route.ts` inside the `api/chat/` directory and add the following code:

```ts
// api/chat/route.ts
import { Configuration, OpenAIApi } from 'openai-edge';
import { OpenAIStream, StreamingTextResponse } from 'ai';
import { kv } from '@vercel/kv';
import { Ratelimit } from '@upstash/ratelimit';

// Create an OpenAI API client (that's edge friendly!)
const config = new Configuration({
  apiKey: process.env.OPENAI_API_KEY
});
const openai = new OpenAIApi(config);

// Set the runtime to edge to allow for Edge Streaming (<https://vercel.fyi/streaming>)
export const runtime = 'edge';

Summary

By following these steps, you will have a basic chat functionality integrated into your Next.js application using the App Router. The useChat hook from the Vercel AI SDK will manage the state for the messages displayed in the Chat component.

For more detailed information, you can refer to

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: