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.
- Create a Socket.IO API route:
In thepages/api
folder, create a file likesocket.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.
- 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.
- Set up a custom hook for managing the WebSocket connection: Create a file like
useSocket.js
in yourhooks
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;
- Connect the client to the server:
In your components (e.g., a chat interface), use theuseSocket
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
- Start your Next.js app with
npm run dev
. - Open multiple browser tabs pointing to your app.
- Send messages, and you should see real-time updates across all tabs.
Optional Enhancements
- Persist Messages: Store chat messages in a database like MongoDB or Firebase for persistence.
- Authentication: Add user authentication with tools like
next-auth
orJWT
to handle user identification. - 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
Leave a Reply