Building a Chat app in Node.js using Socket.io

Haneen Mahdin
2 min readDec 9, 2022

Ever wondered how messaging apps worked behind the scenes.

Well, today we are going to take a look at how we can build a simple chat app using just Node.js.

So, let’s get started by setting up our project!

Setup

We will use npm as our package manager for this project. You can use your preferred package manager as you want.

Initialise the project:

mkdir node-chat-app
cd node-chat-app
npm init -y

Install express, cors, and socket.io and also install nodemon for development.

npm i socket.io

npm i -D nodemon

Create a frontend React app:

Run this command in your terminal to create a react app to use as our frontend.

npx create-react-app@latest chat-app-frontend

Development

Time to get our hands dirty. We will now create a simple boilerplate code for setting up our server.

server.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const PORT = 3000;

io.on('connection', (socket) => {
socket.on('message', (msg) => {
io.emit('message', msg);
});
});

http.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});

App.js

import React, { useState } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:3000');

function App() {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);

socket.on('message', (msg) => {
setMessages([...messages, msg]);
});

const sendMessage = () => {
socket.emit('message', message);
setMessage('');
};

return (
<div>
<ul>
{messages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}

export default App;

Now, we have completed our development process.

We will go ahead and start our development server by running these commands.

Starting the server:

node server.js

Starting the frontend dev server:

npm run start

This will start out the development server and now you can open up the http://localhost:3000 in your browser and find the awesome chat app we’ve made.

Thanks for reading 📖

--

--