DEV Community 👩‍💻👨‍💻

Cover image for Real time chat using

Posted on

Real time chat using

What are WebSockets?

Socket.IO enables real-time, bidirectional and event-based communication.
It works on every platform, browser or device, focusing equally on reliability and speed.

Socket.IO allows you to bridge the gap between clients and servers, or any other kind of device. It works on every platform, browser or device, focusing equally on reliability and speed. Learn how easy it is to integrate socket functionality into your web app in under ten minutes!

Now let us see how to use

The tools that we are going to use are,

  • Nodejs and Express
  • Reactjs
  • and obviously 😂

Let us start

We will be building a simple chat app using Nodejs and React.

First initialize our server
npm init

Then install the dependencies
npm install express

Run the server
node server.js

Let start coding our server now,

const express = require("express");
const socket = require("");

// App setup
const PORT = 5000;
const app = express();
const server = app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);

// Static files

// Socket setup
const io = socket(server);

io.on("connection", function (socket) {
  console.log("Made socket connection");
  const { roomId } = socket.handshake.query;

  // Listen for new messages
  socket.on(NEW_CHAT_MESSAGE_EVENT, (data) => {, data);

  // Leave the room if the user closes the socket
  socket.on("disconnect", () => {

Enter fullscreen mode Exit fullscreen mode

Once the socket is open, it listens for the event we emit in the React app. The message, that is carried by that event, is then forwarded to all users in the same room by emitting another event. The client picks up the event and adds the message to the array of all messages.

Let us create the front-end now using Reactjs,

Set up the react evironment using create-react-app
npx create-react-app socketio-chat

Install the dependencies
npm install react-router-dom

Start the app,
npm start

We will be creating two pages

  1. Home page - To enter roomId
  2. Chat Page - To chat


import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import "./app.css";
import Home from "./pages/Home";
import ChatRoom from "./page/ChatRoom";

function App() {
  return (
        <Route exact path="/" component={Home} />
        <Route exact path="/:roomId" component={ChatRoom} />

export default App;
Enter fullscreen mode Exit fullscreen mode


import React,{useState} from "react";
import { Link } from "react-router-dom";

const Home = () => {
  const [roomName, setRoomName] = useState("");

  const handleRoomNameChange = (event) => {

  return (
    <div className="home-container">
      <Link to={`/${roomName}`} className="enter-room-button">
        Join room

export default Home;
Enter fullscreen mode Exit fullscreen mode

Chat Room

import React from "react";

import useChatMessage from "../hooks/useChatMessage";

const ChatRoom = (props) => {
  const { roomId } = props.match.params; // Gets roomId from URL
  const { messages, sendMessage } = useChatMessage(roomId); // Creates a websocket and manages messaging
  const [newMessage, setNewMessage] = React.useState(""); // Message to be sent

  const handleNewMessageChange = (event) => {

  const handleSendMessage = () => {

  return (
    <div className="chat-room-container">
      <h1 className="room-name">Room: {roomId}</h1>
      <div className="messages-container">
        <ol className="messages-list">
          {, i) => (
              className={`message-item ${
                message.ownedByCurrentUser ? "my-message" : "received-message"
        placeholder="Write message..."
      <button onClick={handleSendMessage} className="send-message-button">

export default ChatRoom;

Enter fullscreen mode Exit fullscreen mode

Let us create a hook to manage the socket and incomming-outgoing messages,


import { useEffect, useRef, useState } from "react";
import socketIOClient from "";

const NEW_CHAT_MESSAGE_EVENT = "newChatMessage"; // Name of the event
const SOCKET_SERVER_URL = "http://localhost:5000";

const useChatMessage= (roomId) => {
  const [messages, setMessages] = useState([]); // Sent and received messages
  const socketRef = useRef();

  useEffect(() => {

    // Creates a WebSocket connection
    socketRef.current = socketIOClient(SOCKET_SERVER_URL, {
      query: { roomId },

    // Listens for incoming messages
    socketRef.current.on(NEW_CHAT_MESSAGE_EVENT, (message) => {
      const incomingMessage = {
        ownedByCurrentUser: message.senderId ===,
      setMessages((messages) => [...messages, incomingMessage]);

    // Destroys the socket reference
    // when the connection is closed
    return () => {
  }, [roomId]);

  // Sends a message to the server that
  // forwards it to all users in the same room
  const sendMessage = (messageBody) => {
    socketRef.current.emit(NEW_CHAT_MESSAGE_EVENT, {
      body: messageBody,

  return { messages, sendMessage };

export default useChatMessage;

Enter fullscreen mode Exit fullscreen mode

That's its friends we have created our real-time-chat-app using node-react.
P.S I have skipped the CSS, you guys can add the color to it 😁

For more information you can visit official web page

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.