Make a connection between react and node.js through socket.io – 1

During the way of learning technology today we learn how to make real time connection between react and node.js server through socket.io. To guys who don’t know about real time connectivity between client and server, so I’m giving you a simple example. Let suppose you open two browser and open same application now if i triggered some kind of event in one of browser and you see some kind of a reaction on browser but at the same time you see same action happen on another browser without any refresh on other browser. This is little scenario about real time connection.

Environment Setup

First of all you need to install node.js in your systems

Now make a folder called NodeServer, this folder is for node.js setup now open this folder in CMD and this below command

npm init

through this command you are gonna initialized npm in your project. Now we need to install 2 packages called express and socket.io.

npm install express, socket.io

express is a framework for node.js you can study it more on official site ( Express ). and socket.io use for real time communication between client and server.

Now make 1 file called app.js you can name it what ever you want, this is main file where server setup is configured

Paste a below code in app.js

const http = require('http');
const express = require('express'); 
const app = express();


const server = http.createServer(app);

server.listen(4000, () => {
    console.log('Server Connected');
})

In above code just initialized express and http and setup the server on port 4000. Now open your CMD and run command node app.js you see message server connected.

Now make another folder name it what ever you want, this is for react setup. Run this below command to generate new react setup

npx create-react-app react-app

Configure socket io in node.js

Make a new file called socket.js on root directory of node setup. Paste a below code.

let io;

module.exports = {
  init: server => {
    io = require('socket.io')(server);
    return io;
  },

  getIO: () => {
    if (!io) {
      throw new Error('Socket is not initialized!');
    }

    return io;
  }

}

In this file we export 1 object containing 2 functions in first function we initialized socket.io and pass server which is setup in app.js file and save in global variable called io. Second function getIO is use for get socket connection in another file if we want!

Now get this connection in main file app.js because we want when any new user open our website we need to received any notification or message something

const http = require('http');
const express = require('express'); 
const { error } = require('console');
const app = express();


const server = http.createServer(app);

const io = require("./socket").init(server)
io.on("connection", async (socket) => {

    if (socket) {
        console.log('New Socket Connection');
    } 

    throw error;

});

server.listen(4000, () => {
    console.log('Server Connected');
})

import socket.js file in app.js and pass server variable to init function to initialized socket connection. Next step we use connection event to check new user who open the site.

Configure socket io in react

First of all on react side install socket.io-client package, run command below

npm install socket.io-client

after install this package update the code of App.js in react application. Code Below

import './App.css';
import { useEffect, useState } from 'react';
import openSocket from "socket.io-client";
const socket = openSocket("http://localhost:4000/", { transports : ['websocket'] });

function App() {

  const [socketAlet, setSocketAlert] = useState('');
  const [message, setMessage] = useState('');

  useEffect(() => {
    socket.on('socketTest', data => {
      console.log(data.sender);
      console.log(socket.id);
      setSocketAlert(data.status);
    });
  }, [])

  return (
    <div className="App">
      <h1>Socket Connection</h1>
    </div>
  );
}

export default App;

call function openSocket it take 2 arguments replace the first argument with your node.js url with respect to port. using useEffect hook to check socket connection and also made business logic according to this connection.

Testing

Now for testing purpose open node and react project in cmd.

start react project through cmd and also on node side run this command node app.js according to your node main file.

and now open react app in 1 browser you will see a message “New Socket Connection” on node CMD panel that mean a new user come to your site and now through out when you open react app in new browser you will see same message on node CMD panel.

Wrap Up

In this blog, you learned how you make real-time connections between react and node.js. you can do several things through this connection like make chat systems.

Unveiling the Power of JavaScript’s Unary Plus Operator: Converting Strings to Numbers

Make Your Own CLI Command Using Node.js: A Step-by-Step Guide

https://nodejs.org/en

Leave a Comment