DEV Community

Avinash Krishnan
Avinash Krishnan

Posted on

Introduction to Socket.IO in MERN Stack

If you’ve ever wondered how chat apps, live notifications, or multiplayer games update instantly without refreshing the page, the magic behind these features is often powered by real-time communication. One popular tool that makes this possible is Socket.IO. In this guide, we'll introduce you to the basics of Socket.IO and show you how to set it up in a MERN stack (MongoDB, Express, React, Node.js) application.

What is Socket.IO?

Socket.IO is a JavaScript library that lets your application talk to clients in real time. This means that the server can send updates to the client (like a new chat message) the moment something happens, without the client having to ask for it repeatedly. It’s a bit like a two-way street where information can travel back and forth instantly between your server and the users.

Prerequisites

Before we dive into the integration, ensure you have Node.js installed on your machine and a basic MERN stack setup ready. We'll be using:

  • Node.js and Express for the backend server
  • React for the frontend
  • Socket IO for real-time communication

Setting up the backend first

  1. Install required dependencies
npm install socket.io nodemon express cors
Enter fullscreen mode Exit fullscreen mode

2.Create a server with Socket.io
Now, let's create a simple server in server.js (or app.js) and integrate Socket.IO with Express:

import express from "express";

import { Server } from "socket.io";
import { createServer } from "http";

import cors from "cors";

const port = 3030;
const app = express();
app.use(
  cors({
    origin: "http://localhost:5173",
    methods: ["GET", "POST"],
    credentials: true,
  })
);

const server = createServer(app);
const io = new Server(server);

app.get("/", (req, res) => {
  res.send("Hello World!");
});

io.on("connection", (socket) => {
  console.log("User Connected::::", socket.id);
  socket.emit("welcome", "Welcome to my server huihuihui");
});

server.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Enter fullscreen mode Exit fullscreen mode

3.You can add more features and list them down under connection
Such as:

socket.emit("welcome", "Welcome to my server huihuihui");
  socket.broadcast.emit("welcome", `${socket.id} has joined the server`);
  socket.on("message", (data) => {
    console.log("DATA::::", data);
    io.to(data.room).emit("receive-message", data);
  });
  socket.on("disconnect", () => {
    console.log(`User with id: ${socket.id} has been DISCONNECTED`);
  });
  socket.on("join-room", (room) => {
    socket.join(room);
  });
Enter fullscreen mode Exit fullscreen mode

This should be pretty much about the backend initially

Setting up the frontend

  1. Install Socket.io client
npm install socket.io-client
Enter fullscreen mode Exit fullscreen mode

2.Connect React to Socket.io server
Firstly import io from socket.io-client

import { io } from "socket.io-client";
Enter fullscreen mode Exit fullscreen mode

Next up connect it to your backend api

  const socket = useMemo(() => io("http://localhost:3030"), []);
Enter fullscreen mode Exit fullscreen mode

3.Once this setup is done we can start working upon using the api built we built earlier
Doing it under a useEffect would be helpful.
This is the code for the same

useEffect(() => {
    socket.on("connect", () => {
      setSocketId(socket.id);
      console.log("connected with ID::", socket.id);
    });

    socket.on("welcome", (s) => {
      console.log(`User with ID:: ${socket.id}`, "\n", s);
    });

    socket.on("receive-message", (data) => {
      console.log("RECEIVE-MESSAGE EMIT::::", data);
      setMessages((messages) => [...messages, data.message]);
    });
  }, []);
Enter fullscreen mode Exit fullscreen mode

This would pretty much complete the setup and give user a chance to build upon as per requirement.

This is just the beginning—Socket.IO can power various real-time features, such as notifications, live updates, and collaborative tools. By adding real-time functionality to your apps, you can create more interactive and engaging user experiences.

The complete code has been pushed in my github don't forget to check it out.

GitHub: https://github.com/Krishnan-Avinash/socket

Top comments (0)