Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen-max-2025-01-25· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

Write a realtime chat in Nextjs.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-30b-a3b’s answer.
  1. User

    Write a realtime chat in Nextjs.

  2. Qwen Assistant

    Creating a real-time chat application using Next.js involves multiple components, including frontend UI, backend API routes, and WebSocket communication for real-time updates. Below is an example of how you can build a simple real-time chat app using Next.js and Socket.IO.

    Steps to Build the Chat App:

    1. Set up a Next.js project.
    2. Install necessary dependencies (like socket.io).
    3. Create Socket.IO server (in the Next.js API route).
    4. Build the frontend with real-time messaging capabilities.
    5. Handle user connection/disconnection and message broadcasting.

    Step 1: Set Up a Next.js Project

    First, create a new Next.js project if you haven't already:

    npx create-next-app realtime-chat
    cd realtime-chat
    

    Step 2: Install Dependencies

    Install the required dependencies:

    npm install socket.io socket.io-client
    
    • socket.io: handles WebSocket connections on the server.
    • socket.io-client: allows client-side interaction with the WebSocket server.

    Step 3: Create the Socket.IO Server in the API Route

    We'll use Next.js's API routes to set up our WebSocket server. Create a file called pages/api/socket.js and add the following code:

    // pages/api/socket.js
    import { Server } from "socket.io";
    
    export default function handler(req, res) {
      // Ensure this is only run once when the server starts
      if (res.socket.server.io) {
        console.log("Socket is already running");
        res.end();
        return;
      }
    
      console.log("Starting Socket.IO server...");
      
      const io = new Server(res.socket.server);
    
      io.on("connection", (socket) => {
        console.log("A user connected:", socket.id);
    
        // Listen for chat messages
        socket.on("sendMessage", (message) => {
          console.log("Message received:", message);
          io.emit("receiveMessage", message);  // Broadcast the message to all clients
        });
    
        // Handle disconnection
        socket.on("disconnect", () => {
          console.log("User disconnected:", socket.id);
        });
      });
    
      res.socket.server.io = io;
      res.end();
    }
    

    This sets up a WebSocket server that listens for incoming connections and broadcasts messages to all connected clients.

    Step 4: Build the Frontend

    Now let's create the frontend where users can send and receive messages.

    4.1 Update _app.js for Global Styles

    You can add some basic styles to your _app.js file for better presentation:

    // pages/_app.js
    import '../styles/globals.css';
    
    function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />;
    }
    
    export default MyApp;
    

    4.2 Create the Chat Component

    Create a new file components/Chat.js:

    // components/Chat.js
    import { useEffect, useState } from 'react';
    import io from 'socket.io-client';
    
    let socket;
    
    export default function Chat() {
      const [message, setMessage] = useState('');
      const [messages, setMessages] = useState([]);
    
      useEffect(() => {
        // Connect to the Socket.IO server
        socket = io('http://localhost:3000');
    
        // Listen for incoming messages
        socket.on('receiveMessage', (message) => {
          setMessages((prevMessages) => [...prevMessages, message]);
        });
    
        // Cleanup on unmount
        return () => {
          socket.disconnect();
        };
      }, []);
    
      const sendMessage = () => {
        if (message.trim()) {
          socket.emit('sendMessage', message);
          setMessage('');
        }
      };
    
      return (
        <div style={{ padding: '20px' }}>
          <h1>Realtime Chat</h1>
    
          <div style={{ height: '300px', overflowY: 'scroll', border: '1px solid #ccc', padding: '10px' }}>
            {messages.map((msg, index) => (
              <div key={index}>{msg}</div>
            ))}
          </div>
    
          <input
            type="text"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder="Type a message..."
            style={{ width: '80%', padding: '10px', marginTop: '10px' }}
          />
          <button onClick={sendMessage} style={{ padding: '10px 20px', marginLeft: '10px' }}>Send</button>
        </div>
      );
    }
    

    4.3 Update pages/index.js to Render the Chat Component

    Update the main page (pages/index.js) to render the chat component:

    // pages/index.js
    import Chat from '../components/Chat';
    
    export default function Home() {
      return (
        <div>
          <Chat />
        </div>
      );
    }
    

    Step 5: Run the Application

    Start your Next.js development server:

    npm run dev
    

    Visit http://localhost:3000 in your browser, and you should see the chat interface. Open multiple tabs or browsers, and you will be able to send and receive messages in real-time across them.


    Explanation:

    1. Socket.IO Server: The server listens for WebSocket connections and broadcasts any received message to all connected clients.

    2. Frontend (React): The frontend connects to the WebSocket server via socket.io-client. It listens for incoming messages and displays them. Users can type messages into the input box and send them to the server, which broadcasts the message to everyone else.

    3. Real-time Updates: Whenever a user sends a message, the server emits it to all connected clients, and those clients update their UI accordingly.


    Additional Features You Can Add:

    1. Usernames: Allow users to choose a username before joining the chat.
    2. Message Timestamps: Show timestamps for each message.
    3. Private Messaging: Implement private messaging between specific users.
    4. Room Support: Add support for different chat rooms.
    5. Persist Messages: Store chat history in a database (like MongoDB or Firebase).

    With these steps, you've built a fully functional real-time chat application using Next.js and Socket.IO!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.