DEV Community

Hamza Khan
Hamza Khan

Posted on

17 1 1 1 1

๐Ÿ”ฅ 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! ๐Ÿ’ฌ

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (3)

Collapse
 
hanzla-baig profile image
Hanzla Baig โ€ข

๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘

Collapse
 
youngcodes profile image
Ogala muctar Mohammad โ€ข

Can I collaborate?

Collapse
 
hamzakhan profile image
Hamza Khan โ€ข

Yeah, sure.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools canโ€™t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay