Building Real-Time Web Applications With WebSockets in Node.js and React

Real-time features like live notifications, chat, and collaborative editing have become integral to modern web apps. In this guide, we’ll walk through building a basic real-time communication system using WebSockets with Node.js and React.

Step 1: Set Up a WebSocket Server With Socket.IO

We’ll use socket.io for its simplicity and reliability across platforms. First, initialize a Node.js project:

mkdir websocket-server
cd websocket-server
npm init -y
npm install express socket.io

Then create a basic server in index.js:

const express = require("express");
const http = require("http");
const { Server } = require("socket.io");

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*"
  }
});

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

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

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

server.listen(4000, () => console.log("WebSocket server running on port 4000"));

Step 2: Connect React Frontend to the WebSocket Server

In your React app, install the client library:

npm install socket.io-client

Then in your component:

import { useEffect, useState } from "react";
import { io } from "socket.io-client";

const socket = io("http://localhost:4000");

function ChatApp() {
  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState([]);

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

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

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

  return (
    
{messages.map((msg, idx) => (
{msg}
))}
setMessage(e.target.value)} placeholder="Type a message..." className="border p-2 rounded" />
); } export default ChatApp;

Step 3: Enable CORS for Development

Make sure the backend allows CORS requests while developing locally:

// Already added in server config:
cors: {
  origin: "*"
}

Use Cases for WebSockets

  • Live chat support
  • Real-time notifications
  • Collaborative document editing
  • Live dashboards and analytics

Conclusion

WebSockets make it easy to build real-time apps with a responsive, modern user experience. Paired with Socket.IO and React, this stack is a powerful foundation for anything from chat apps to multiplayer games and collaborative tools.

For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:

Using React Portals Like a Pro.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift