DEV Community

Hamza Khan
Hamza Khan

Posted on

πŸ”₯ Building a Real-Time Chat App with Sockets in Next.js πŸ’¬

Real-time chat is one of the most popular features in modern applications, allowing users to communicate instantly. In this tutorial, we’ll walk through how to implement a real-time chat app using Next.js with WebSockets.

WebSockets allow for two-way communication between the client and server, making them perfect for real-time features. Let’s dive into building this in Next.js! πŸš€


πŸ› οΈ Step 1: Setting Up a Next.js App

First, you need a Next.js app. If you don’t have one yet, you can set it up like this:

npx create-next-app@latest real-time-chat
cd real-time-chat
npm install
Enter fullscreen mode Exit fullscreen mode

Now, we have a basic Next.js app ready.


βš™οΈ Step 2: Installing Socket.io

We'll use Socket.io to handle WebSockets. Install the necessary packages for both the client and server:

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

This will install the server-side Socket.io package and the client-side socket.io-client package.


πŸ”Œ Step 3: Setting Up the Server-Side WebSocket in Next.js

Next.js uses its API routes to manage server-side logic, which is where we’ll handle WebSocket connections.

  1. Create a new API route at pages/api/socket.js:
import { Server } from "socket.io";

export default function handler(req, res) {
    if (!res.socket.server.io) {
        console.log("Starting socket.io server...");
        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", (msg) => {
                socket.broadcast.emit("message", msg); // Send message to all except sender
            });

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

This API route initializes the Socket.io server when a client connects. It listens for message events and broadcasts them to all other clients.


πŸ’» Step 4: Connecting the Client-Side WebSocket

Now, we’ll set up the client-side connection to the WebSocket server. In your Next.js app, create a chat component in 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(() => {
        socket = io();

        // Listen for messages from the server
        socket.on("message", (msg) => {
            setMessages((prev) => [...prev, msg]);
        });

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

    const sendMessage = () => {
        socket.emit("message", message); // Send message to server
        setMessages((prev) => [...prev, message]); // Add your message to the chat
        setMessage(""); // Clear input field
    };

    return (
        <div>
            <h1>Real-Time Chat</h1>
            <div>
                {messages.map((msg, index) => (
                    <div key={index}>{msg}</div>
                ))}
            </div>
            <input
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                placeholder="Type a message..."
            />
            <button onClick={sendMessage}>Send</button>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

This component handles the client-side logic:

  • It connects to the Socket.io server.
  • Sends and receives messages in real-time.

πŸ”„ Step 5: Update pages/_app.js to Initialize WebSocket

To ensure the WebSocket server is initialized, we need to make a request to our API route when the app starts:

// pages/_app.js
import { useEffect } from "react";
import "../styles/globals.css";

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        fetch("/api/socket"); // Initialize the WebSocket server
    }, []);

    return <Component {...pageProps} />;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

By making a call to the api/socket route in useEffect, we ensure that the WebSocket server starts as soon as the app is loaded.


πŸ§ͺ Step 6: Testing the Real-Time Chat

You can now test your chat app by running your Next.js development server:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open multiple browser windows to http://localhost:3000, and you’ll see real-time communication between them! πŸ₯³


🏁 Conclusion

Using Next.js and Socket.io, we've built a simple real-time chat app. This setup allows you to extend the app with more features like user authentication, rooms, and more complex events.

WebSockets are incredibly powerful for any real-time feature in your apps. Whether it's a chat app, live notifications, or real-time collaboration, this setup provides a great starting point for real-time web applications.


πŸ”— Additional Resources:

Feel free to experiment and add more advanced features to your chat app! What real-time feature are you planning to build next? Let me know in the comments! πŸ’¬

Top comments (1)

Collapse
 
hanzla-mirza profile image
Mirza Hanzla

πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘