DEV Community

Hamza Khan
Hamza Khan

Posted on

πŸ€– **Building a Real-Time Chatbot in Next.js with OpenAI** 🧠

In this tutorial, we’ll walk through how to build a real-time chatbot using Next.js and OpenAI's API. Combining WebSockets for real-time communication and OpenAI for generating responses, you can create an intelligent and responsive chatbot. Let’s get started! πŸš€


πŸ› οΈ Step 1: Setting Up the Next.js Project

Start by setting up a Next.js app if you don’t already have one:

npx create-next-app@latest nextjs-chatbot
cd nextjs-chatbot
npm install
Enter fullscreen mode Exit fullscreen mode

Next, install the packages we'll need: Socket.io for real-time communication and OpenAI's API client.

npm install socket.io socket.io-client openai
Enter fullscreen mode Exit fullscreen mode

Now we’re ready to begin building the chatbot!


πŸ”Œ Step 2: Setting Up the OpenAI API

To use OpenAI, you need an API key. Go to OpenAI's website and sign up for an API key.

In your Next.js project, create an .env.local file to store your OpenAI API key:

NEXT_PUBLIC_OPENAI_API_KEY=your-openai-api-key
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Step 3: Create API Route for OpenAI Integration

Next, we need to set up a Next.js API route that interacts with OpenAI and generates responses for the chatbot.

Create a file at pages/api/chatbot.js:

import { Configuration, OpenAIApi } from 'openai';

const configuration = new Configuration({
    apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

export default async function handler(req, res) {
    if (req.method === 'POST') {
        const { message } = req.body;

        // Send user message to OpenAI for a response
        const response = await openai.createChatCompletion({
            model: 'gpt-3.5-turbo',
            messages: [{ role: 'user', content: message }],
        });

        const reply = response.data.choices[0].message.content;
        res.status(200).json({ reply });
    } else {
        res.status(405).send('Method not allowed');
    }
}
Enter fullscreen mode Exit fullscreen mode

This API route listens for POST requests with a message from the user, sends it to OpenAI, and returns the AI-generated response.


πŸ“‘ Step 4: Setting Up WebSocket Server

Next, we’ll set up Socket.io to allow real-time communication between the client and server.

Create a WebSocket server in pages/api/socket.js:

import { Server } from "socket.io";

export default function handler(req, res) {
    if (!res.socket.server.io) {
        const io = new Server(res.socket.server);
        res.socket.server.io = io;

        io.on("connection", (socket) => {
            console.log("User connected:", socket.id);

            socket.on("message", async (message) => {
                // Send message to OpenAI API
                const response = await fetch("http://localhost:3000/api/chatbot", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ message }),
                });

                const { reply } = await response.json();
                socket.emit("response", reply);
            });

            socket.on("disconnect", () => {
                console.log("User disconnected:", socket.id);
            });
        });
    }
    res.end();
}
Enter fullscreen mode Exit fullscreen mode

This WebSocket server listens for incoming message events, sends them to OpenAI via the /api/chatbot route, and broadcasts the response back to the client.


πŸ’» Step 5: Client-Side WebSocket and Chat Interface

Now, let’s build the chat UI and handle communication with the WebSocket server. Create a components/ChatBot.js file for the chat interface:

import { useEffect, useState } from 'react';
import io from 'socket.io-client';

let socket;

export default function ChatBot() {
    const [message, setMessage] = useState("");
    const [messages, setMessages] = useState([]);

    useEffect(() => {
        socket = io();

        socket.on("response", (reply) => {
            setMessages((prev) => [...prev, { sender: "bot", text: reply }]);
        });

        return () => {
            socket.disconnect();
        };
    }, []);

    const sendMessage = () => {
        setMessages((prev) => [...prev, { sender: "user", text: message }]);
        socket.emit("message", message);
        setMessage("");
    };

    return (
        <div>
            <h1>Real-Time ChatBot πŸ€–</h1>
            <div className="chatbox">
                {messages.map((msg, index) => (
                    <div key={index} className={msg.sender === "user" ? "user-msg" : "bot-msg"}>
                        {msg.sender === "user" ? "You: " : "Bot: "} {msg.text}
                    </div>
                ))}
            </div>
            <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                placeholder="Ask me something..."
            />
            <button onClick={sendMessage}>Send</button>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

This component does the following:

  1. Connects to the WebSocket server when mounted.
  2. Sends messages typed by the user.
  3. Displays the conversation, showing responses from OpenAI.

πŸ“„ Step 6: Display the ChatBot in the App

Finally, update your main page to render the chatbot. In pages/index.js:

import ChatBot from '../components/ChatBot';

export default function Home() {
    return (
        <div>
            <ChatBot />
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

This will display the chatbot interface when you visit the main page of your app.


πŸ§ͺ Step 7: Testing the Chatbot

You can now test the chatbot by running your Next.js app:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000, and you’ll be able to chat with your real-time AI chatbot! Open multiple tabs to see how the real-time communication works as you send messages.


🏁 Conclusion

Congratulations! πŸŽ‰ You've built a real-time chatbot using Next.js, WebSockets, and OpenAI. This setup can be extended to create more complex chatbots with features like user authentication, chat history, and more.

WebSockets ensure seamless real-time communication, while OpenAI powers the intelligent responses of your bot. Feel free to experiment further and enhance the chatbot with more advanced AI models!


πŸ”— Additional Resources:

What kind of chatbot are you building? Let me know in the comments! πŸ’¬

Top comments (3)

Collapse
 
smaameri profile image
Sami Maameri

Useful. Thanks for sharing!

Collapse
 
youngcodes profile image
Ogala muctar Mohammad

Could we collaborate on it?

Collapse
 
hamzakhan profile image
Hamza Khan • Edited

Yeah, Sure.