<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Deepinder Singh</title>
    <description>The latest articles on DEV Community by Deepinder Singh (@deepinder10).</description>
    <link>https://dev.to/deepinder10</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F671912%2F100ba498-36d9-4544-a46d-4e1a91881be0.jpeg</url>
      <title>DEV Community: Deepinder Singh</title>
      <link>https://dev.to/deepinder10</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/deepinder10"/>
    <language>en</language>
    <item>
      <title>Create a realtime chat app with React hooks, socket.io and NodeJS</title>
      <dc:creator>Deepinder Singh</dc:creator>
      <pubDate>Tue, 27 Jul 2021 22:29:15 +0000</pubDate>
      <link>https://dev.to/deepinder10/create-a-realtime-chat-app-with-react-hooks-socket-io-and-nodejs-dpc</link>
      <guid>https://dev.to/deepinder10/create-a-realtime-chat-app-with-react-hooks-socket-io-and-nodejs-dpc</guid>
      <description>&lt;p&gt;In this tutorial, we'll learn how to build a real-time chat application with React Hooks, Socket.IO, WebSockets, ExpressJS and NodeJS. This would also work with React Native.&lt;/p&gt;

&lt;p&gt;This might be the most searched query among all developers on how to make a live chat application with &lt;code&gt;React&lt;/code&gt; and &lt;code&gt;Socket.io&lt;/code&gt; .We will be using expressJS on top of NodeJS as a backend.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Read more of these stories on my &lt;a href="https://deepinder.me" rel="noopener noreferrer"&gt;website&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Creating a NodeJS Express App
&lt;/h3&gt;

&lt;p&gt;Let’s start by creating a &lt;code&gt;nodejs&lt;/code&gt; project first.&lt;/p&gt;

&lt;p&gt;Create a new &lt;code&gt;directory&lt;/code&gt; and then enter it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir socketio-node
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will create a empty folder with name &lt;code&gt;socketio-node&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We’re going to use the Node.JS web framework &lt;code&gt;expressJS&lt;/code&gt;. Make sure &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;NodeJS&lt;/a&gt; is installed on your system.&lt;/p&gt;

&lt;p&gt;First let’s create a &lt;code&gt;package.json&lt;/code&gt; manifest file that describes our project.&lt;br&gt;
Create a file named package.json and paste the below code into it.(You can also do it with &lt;code&gt;npm init&lt;/code&gt;)&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
    "name": "socketio-node",
    "version": "0.0.1",
    "description": "my first socket.io app",
    "dependencies": {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, in order to easily populate the &lt;code&gt;dependencies&lt;/code&gt; property we need to install &lt;code&gt;express&lt;/code&gt;, type this in the terminal.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It will install and add the latest version of express into our project and your &lt;code&gt;dependencies&lt;/code&gt; will now look like. The version can be different depending on the latest version at the time you install it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"dependencies": {
  "express": "^4.17.1"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now that express is installed we can create an &lt;code&gt;index.js&lt;/code&gt; file that will setup our application.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = require('express')();
const http = require('http').createServer(app);

app.get('/', (req, res) =&amp;gt; {
  res.send('&amp;lt;h1&amp;gt;Hey Socket.io&amp;lt;/h1&amp;gt;');
});

http.listen(3000, () =&amp;gt; {
  console.log('listening on *:3000');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This code is explained in the following steps:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Express initializes &lt;code&gt;app&lt;/code&gt; to be a function handler that you can supply to an HTTP server (as seen in line 2).&lt;/li&gt;
&lt;li&gt;We define a route handler &lt;code&gt;/&lt;/code&gt; that gets called when we hit our website home.&lt;/li&gt;
&lt;li&gt;We make the http server listen on port 3000.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you run &lt;code&gt;node index.js&lt;/code&gt; you should see the following:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2F1_BL3MXnEZKZmq6-kPQp-9Xw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2F1_BL3MXnEZKZmq6-kPQp-9Xw.png" alt="node server listening on port 3000"&gt;&lt;/a&gt;node server listening on port 3000&lt;/p&gt;

&lt;p&gt;Opening &lt;a href="http://localhost:3000/" rel="noopener noreferrer"&gt;http://localhost:3000&lt;/a&gt; in browser would look like:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2F1_xaoZXJEsstsrdKTFhVs0vA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2F1_xaoZXJEsstsrdKTFhVs0vA.png" alt="node server serving html on 3000"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Integrating Socket.io with NodeJS
&lt;/h3&gt;

&lt;p&gt;Now let’s integrate socket.io into our node app. Firstly, we need to install &lt;code&gt;socket.io&lt;/code&gt; dependency into our app. Run this in the terminal.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install socket.io
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will install the module and add the dependency to &lt;code&gt;package.json&lt;/code&gt;. Now let’s edit &lt;code&gt;index.js&lt;/code&gt; to add it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
  cors: {
    origins: ['http://localhost:3001']
  }
});

app.get('/', (req, res) =&amp;gt; {
  res.send('&amp;lt;h1&amp;gt;Hey Socket.io&amp;lt;/h1&amp;gt;');
});

io.on('connection', (socket) =&amp;gt; {
  console.log('a user connected');
  socket.on('disconnect', () =&amp;gt; {
    console.log('user disconnected');
  });
});

http.listen(3000, () =&amp;gt; {
  console.log('listening on *:3000');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Notice that I initialize a new instance of &lt;code&gt;socket.io&lt;/code&gt; on line 3 by passing the &lt;code&gt;http&lt;/code&gt; (the HTTP server) object and the cors options(updated for socket.io v3) to allow our react localhost url, you can put in the url or your frontend client, in my case it was &lt;code&gt;localhost:3001&lt;/code&gt;&lt;br&gt;
Then I listen on the &lt;code&gt;connection&lt;/code&gt; and &lt;code&gt;disconnection&lt;/code&gt; events for incoming sockets, and I log it to the console.&lt;/p&gt;

&lt;p&gt;Our Backend is good to go for now, we will come back to our &lt;code&gt;node&lt;/code&gt; code when we will implement more events further on.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating a React app
&lt;/h3&gt;

&lt;p&gt;Let’s start by creating an &lt;code&gt;React&lt;/code&gt; app now. I will be creating a new &lt;code&gt;React&lt;/code&gt; app from scratch with &lt;code&gt;create-react-app&lt;/code&gt;, while most of you would already have one created with you.&lt;br&gt;
Those who already have a working &lt;code&gt;React&lt;/code&gt; app can skip the following code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app socketio-react
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;(&lt;a href="https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b" rel="noopener noreferrer"&gt;npx&lt;/a&gt; comes with npm 5.2+ and higher, see &lt;a href="https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f" rel="noopener noreferrer"&gt;instructions for older npm versions&lt;/a&gt;)&lt;/em&gt;&lt;br&gt;
This would install the latest version of &lt;code&gt;CRA&lt;/code&gt; and create a new template React app from scratch.&lt;/p&gt;

&lt;p&gt;Now let’s add socket.io &lt;code&gt;dependency&lt;/code&gt; in our React app.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd socketio-react
npm install socket.io-client
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This would install the latest &lt;code&gt;socket.io-client&lt;/code&gt; library in our React app.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating a socket client service
&lt;/h3&gt;

&lt;p&gt;Now let’s start by creating a &lt;code&gt;file&lt;/code&gt; to handle socket.io connection. I would create a root level file named &lt;code&gt;socketio.service.js&lt;/code&gt; and include that in the &lt;code&gt;src&lt;/code&gt; folder.&lt;/p&gt;

&lt;p&gt;You can create the file by running the following command.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd src
touch socketio.service.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This would create a file named socketio.service.js . The directory structure would look something like this. This is just a simple one page demo, so i added the file into the src folder like this.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-15-at-2.20.56-AM-1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-15-at-2.20.56-AM-1.png" alt="file structure of project"&gt;&lt;/a&gt;&lt;br&gt;
Now, go into the &lt;code&gt;socketio.service.js&lt;/code&gt; file and import the following:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { io } from 'socket.io-client';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now let’s add the socket endpoint/url that we would connect the socket.io client to the backend. We will start by creating a .env file in the root of the folder which would our environment variables.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch .env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-15-at-2.23.58-AM-3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-15-at-2.23.58-AM-3.png" alt=".env file location"&gt;&lt;/a&gt;&lt;br&gt;
We will add the following url in &lt;code&gt;.env&lt;/code&gt; file&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;REACT_APP_SOCKET_ENDPOINT=http://localhost:3000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We have to write &lt;code&gt;REACT_APP&lt;/code&gt; as a prefix as it is needed by &lt;code&gt;create-react-app&lt;/code&gt;. For more details you can check this &lt;a href="https://create-react-app.dev/docs/adding-custom-environment-variables/" rel="noopener noreferrer"&gt;link&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let's start by writing our &lt;code&gt;socketio.service.js&lt;/code&gt; and write a socket init function.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { io } from 'socket.io-client';

let socket;

export const initiateSocketConnection = () =&amp;gt; {
    socket = io(process.env.REACT_APP_SOCKET_ENDPOINT);
    console.log(`Connecting socket...`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will declare a variable named &lt;code&gt;socket&lt;/code&gt; and then after calling the &lt;code&gt;initiateSocketConnection&lt;/code&gt; function, &lt;code&gt;socket&lt;/code&gt; connect would be initialized on the &lt;code&gt;URL&lt;/code&gt; provided in &lt;code&gt;.env&lt;/code&gt; file and &lt;code&gt;socket&lt;/code&gt; variable would be containing the connected socket object.&lt;/p&gt;

&lt;p&gt;We have to use the variables inside &lt;code&gt;.env&lt;/code&gt; file like this &lt;code&gt;process.env.yourvariablename&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Since we have created a function, let's call it from our Component.&lt;/p&gt;

&lt;p&gt;Start by opening &lt;code&gt;App.js&lt;/code&gt; file and lets make use of the hooks. We will use &lt;code&gt;useEffect&lt;/code&gt;hook which would only run once on render since we have to init the socket connection only once.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react';

function App() {

  useEffect(() =&amp;gt; {
    initiateSocketConnection();
  }, []);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Doing this would create a socket connection only once on component render and create our connection.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: I am importing only { useEffect } from 'react'; but not import React, {useEffect} from 'react'; since i am on React 17 and it doesn't need that, if you are on old versions(&amp;lt; 17) you might end up importing the last one.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We will run the React app now using&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PORT=3001 npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I used port prefix 3001 as CRA runs on 3000 by default and NodeJS is also running on that port.&lt;br&gt;
You can see the socket connected and our node app console showing &lt;code&gt;a user connected&lt;/code&gt; when we open our browser tab running the React app&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2F1_CLVOixL-yyE4Yg5h8zHH4A--1-.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2F1_CLVOixL-yyE4Yg5h8zHH4A--1-.png" alt="logging of nodejs server"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Disconnection
&lt;/h3&gt;

&lt;p&gt;Now, let's try to disconnect the socket, we will use the cleanup function of the hooks.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react';

function App() {

  useEffect(() =&amp;gt; {
    initiateSocketConnection();
    return () =&amp;gt; {
      disconnectSocket();
    }
  }, []);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In your &lt;code&gt;socketio.service.js&lt;/code&gt; file add this for disconnection&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const disconnectSocket = () =&amp;gt; {
  console.log('Disconnecting socket...');
  if(socket) socket.disconnect();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will disconnect our socket as soon as the component gets destroyed. Also, the socket would get disconnected when we close the tab automatically, whether we handle it here or not, tab closing is handled by default.&lt;/p&gt;

&lt;p&gt;When you disconnect the socket or close the webpage, you can see &lt;code&gt;user disconnected&lt;/code&gt; message on console.&lt;/p&gt;

&lt;p&gt;With this, we have completed our initialization and disconnection of sockets. Now we will learn about how to emit and listen to events.&lt;/p&gt;

&lt;h3&gt;
  
  
  Event Handling
&lt;/h3&gt;

&lt;p&gt;Let’s register an event called &lt;code&gt;my message&lt;/code&gt; inside our &lt;code&gt;index.js&lt;/code&gt; node file and console the data and we will emit the same event from &lt;code&gt;React&lt;/code&gt; app.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;io.on('connection', (socket) =&amp;gt; {

  console.log('a user connected');

  socket.on('disconnect', () =&amp;gt; {
    console.log('user disconnected');
  });

  socket.on('my message', (msg) =&amp;gt; {
    console.log('message: ' + msg);
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And let’s emit the same event from React code in socket.service.js&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const subscribeToChat = (cb) =&amp;gt; {
    socket.emit('my message', 'Hello there from React.');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We will call this function from &lt;code&gt;useEffect&lt;/code&gt; where we initialized our socket connection in App.js&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    initiateSocketConnection();
    subscribeToChat((err, data) =&amp;gt; {
      console.log(data);
    });
    return () =&amp;gt; {
      disconnectSocket();
    }
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This code would emit the event named &lt;code&gt;my message&lt;/code&gt; and it would print the following on our node console. You can see the message ‘Hello there from React’. Our custom events are now working.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-16-at-8.45.11-PM.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-16-at-8.45.11-PM.png" alt="message from react on node server"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Broadcasting Event
&lt;/h3&gt;

&lt;p&gt;Now, let’s &lt;code&gt;emit&lt;/code&gt; an event from the &lt;code&gt;server side&lt;/code&gt; to client side. We will broadcast the event to all connected users. We will broadcast the same message that we received from client and prepend a server string to it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;io.on('connection', (socket) =&amp;gt; {
  socket.on('my message', (msg) =&amp;gt; {
    io.emit('my broadcast', `server: ${msg}`);
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This would emit the message received to all connected sockets.&lt;/p&gt;

&lt;p&gt;Let’s add an listener for &lt;code&gt;my broadcast&lt;/code&gt; event on our &lt;code&gt;React&lt;/code&gt; app now.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const subscribeToChat = (cb) =&amp;gt; {
    socket.emit('my message', 'Hello there from React.');

    socket.on('my broadcast', msg =&amp;gt; {
        return cb(null, msg);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here, we receive the &lt;code&gt;my broadcast&lt;/code&gt; event and call the registered callback in App.js&lt;br&gt;
Since we already had a console.log written in App.js subscription, it will print the message received from server.&lt;/p&gt;

&lt;p&gt;You can check your &lt;code&gt;browser console&lt;/code&gt;, it would &lt;code&gt;print&lt;/code&gt; something like this. It prints a message from server, that emitted the broadcast.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-16-at-4.53.44-PM-1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fdeepinder%2Fimage%2Fupload%2Fw_600%2Ch_400%2Cc_fit%2Cdpr_2.0%2Fblog%2FScreenshot-2021-02-16-at-4.53.44-PM-1.png" alt="view of react app in browser"&gt;&lt;/a&gt;&lt;br&gt;
We have covered the &lt;code&gt;basic&lt;/code&gt; parts of connecting an node socket.io app with an React app.&lt;/p&gt;

&lt;h3&gt;
  
  
  BONUS: Authentication
&lt;/h3&gt;

&lt;p&gt;You can also send &lt;code&gt;authentication parameters&lt;/code&gt; to the Backend when connecting to the socket by using &lt;code&gt;auth&lt;/code&gt; object in options in a connection.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const initiateSocketConnection = (room) =&amp;gt; {
    socket = io(process.env.REACT_APP_SOCKET_ENDPOINT, {
      auth: {
        token: 'cde'
      },
    });
    console.log(`Connecting socket...`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I am sending token key here. You can use any key you want, to provide auth token or any other key.&lt;/p&gt;

&lt;p&gt;To &lt;code&gt;fetch&lt;/code&gt; this information on the Backend, we have to do it like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;io.on('connection', (socket) =&amp;gt; {
  let token = socket.handshake.auth.token;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This would return the value &lt;code&gt;cde&lt;/code&gt; passed by Frontend.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can check all of the above written example code at my &lt;a href="https://github.com/deepinder10/socketio-example" rel="noopener noreferrer"&gt;github&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This concludes my article about creating a &lt;code&gt;real time application&lt;/code&gt; with &lt;code&gt;React&lt;/code&gt; and &lt;code&gt;Socket.io&lt;/code&gt; with &lt;code&gt;NodeJS&lt;/code&gt; and &lt;code&gt;ExpressJS&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The next part of this article which explains the concept of rooms, realtime one to one chat and group chat is &lt;a href="https://deepinder.me/create-a-realtime-chat-app-with-react-hooks-socket-io-rooms-part-2" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Do write down your reviews and remember to &lt;a href="https://buttondown.email/deepinder" rel="noopener noreferrer"&gt;subscribe&lt;/a&gt; for more content like this.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Read more of these stories on my &lt;a href="https://deepinder.me" rel="noopener noreferrer"&gt;website&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Liked my work? Buy me a &lt;a href="https://paypal.me/iamdeepinder" rel="noopener noreferrer"&gt;coffee&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>react</category>
      <category>nodejs</category>
      <category>socketio</category>
      <category>reactnative</category>
    </item>
  </channel>
</rss>
