Integrating WebSockets in a Next.js app with Socket.IO

·

, ,
Integrating WebSockets in a Next.js app with Socket.IO

Hello guys how are you? Welcome back to my blog. Today in this blog post I will show you Integrating WebSockets in a Next.js app with Socket.IO.

For react js new comers, please check the below links:

Reactjs Tutorials
Nextjs
Bootstrap 5
React Free Ecommerce Templates
React Free Admins

Guys here is the code snippet and please use carefully:

Guys integrating WebSockets in a Next.js app with Socket.IO enables you to add real-time features like live chat, notifications, and live updates. Here’s a step-by-step guide to set up Socket.IO in your Next.js app:


Step 1: Install Dependencies

Guys we need both the client and server packages of Socket.IO.

npm install socket.io socket.io-client

Step 2: Set Up the Socket.IO Server

Since Next.js has an API route system, you can use it to set up the server-side part of Socket.IO.

  1. Create a Socket.IO API route:
    In the pages/api folder, create a file like socket.js:
   import { Server } from "socket.io";

   let io;

   export default function handler(req, res) {
     if (!io) {
       io = new Server(res.socket.server, {
         path: "/api/socket",
         cors: {
           origin: "*",
         },
       });

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

         socket.on("message", (msg) => {
           console.log("Message received: ", msg);
           io.emit("message", msg); // Broadcast to all clients
         });

         socket.on("disconnect", () => {
           console.log("Client disconnected", socket.id);
         });
       });

       console.log("Socket.IO initialized");
     }

     res.end(); // Required to complete the request
   }

This will set up a Socket.IO server that listens for incoming WebSocket connections.

  1. Start the server only once:
    Next.js hot-reloads the backend during development, which can restart the server multiple times. The above code ensures the Socket.IO server is initialized only once.

Step 3: Integrate the Socket.IO Client

You need to connect to the server from the client-side.

  1. Set up a custom hook for managing the WebSocket connection: Create a file like useSocket.js in your hooks folder:
   import { useEffect, useState } from "react";
   import { io } from "socket.io-client";

   const useSocket = () => {
     const [socket, setSocket] = useState(null);

     useEffect(() => {
       const socketInstance = io({
         path: "/api/socket",
       });

       setSocket(socketInstance);

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

     return socket;
   };

   export default useSocket;
  1. Connect the client to the server:
    In your components (e.g., a chat interface), use the useSocket hook.
   import { useState } from "react";
   import useSocket from "../hooks/useSocket";

   export default function Chat() {
     const [messages, setMessages] = useState([]);
     const [input, setInput] = useState("");
     const socket = useSocket();

     useEffect(() => {
       if (!socket) return;

       socket.on("message", (msg) => {
         setMessages((prev) => [...prev, msg]);
       });

       return () => {
         socket.off("message");
       };
     }, [socket]);

     const sendMessage = () => {
       if (socket && input.trim()) {
         socket.emit("message", input);
         setInput("");
       }
     };

     return (
       <div>
         <ul>
           {messages.map((msg, idx) => (
             <li key={idx}>{msg}</li>
           ))}
         </ul>
         <input
           value={input}
           onChange={(e) => setInput(e.target.value)}
           placeholder="Type a message..."
         />
         <button onClick={sendMessage}>Send</button>
       </div>
     );
   }

Step 4: Test the Setup

  1. Start your Next.js app with npm run dev.
  2. Open multiple browser tabs pointing to your app.
  3. Send messages, and you should see real-time updates across all tabs.

Optional Enhancements

  1. Persist Messages: Store chat messages in a database like MongoDB or Firebase for persistence.
  2. Authentication: Add user authentication with tools like next-auth or JWT to handle user identification.
  3. Namespaces/Rooms: Use Socket.IO’s namespaces and rooms to isolate communication channels for different chat groups.

Now you have a functional WebSocket-powered chat application in your Next.js app! ????

This is it guys and if you will have any kind of query, suggestion or requirement then feel free to comment below.

Thanks

Ajay

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.