DEV Community

Rishikesh-Programmer
Rishikesh-Programmer

Posted on

Creating a chat application like messenger with node js

Creating a full-fledged chat application like Messenger from scratch is a complex and time-consuming task. However, I can provide you with a basic outline and steps to get you started with building a simple chat application using Node.js and some other technologies.

Set Up the Project:
First, make sure you have Node.js installed on your system. Create a new directory for your project and initialize a new Node.js project using npm (Node Package Manager).

mkdir chat-app
cd chat-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install Dependencies:
For our chat application, we will use Express.js as the web server and Socket.io for real-time communication between clients. Additionally, we'll use other libraries to handle user authentication and UI.

npm install express socket.io socket.io-client moment body-parser ejs passport passport-local express-session
Enter fullscreen mode Exit fullscreen mode

Create Server and Basic HTML:
Create a new file named app.js (or index.js) to set up the server and handle the basic routes.

// app.js
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const moment = require('moment');

// Basic route for serving HTML page
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

http.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Create the HTML page:
Create a new file named index.html in the root folder of your project.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Chat Application</title>
</head>
<body>
  <h1>Welcome to the Chat Application</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Set up Socket.io for Real-Time Communication:
Modify index.html to include Socket.io library and establish a connection to the server.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Chat Application</title>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();
  </script>
</head>
<body>
  <h1>Welcome to the Chat Application</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Handle User Authentication (Optional):
You may choose to implement user authentication to make your chat application secure. You can use Passport.js with the passport-local strategy for this purpose. I'll provide a basic setup, but it's recommended to further enhance security features for production use.

Implement Real-Time Messaging:
Now, we'll implement the core functionality of real-time messaging using Socket.io. Add the following code to app.js:

// app.js
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const moment = require('moment');

app.use(express.static(__dirname));
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

// Basic route for serving HTML page
app.get('/', (req, res) => {
  res.render('index');
});

// Socket.io
io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });

  socket.on('chat message', (msg) => {
    console.log('Message: ', msg);
    io.emit('chat message', {
      username: socket.username,
      message: msg,
      time: moment().format('h:mm A')
    });
  });
});

http.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Update index.html to include the chat interface and handle message submission:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Chat Application</title>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();

    function sendMessage() {
      const message = document.getElementById('messageInput').value;
      socket.emit('chat message', message);
      document.getElementById('messageInput').value = '';
    }

    socket.on('chat message', (data) => {
      const messages = document.getElementById('messages');
      const li = document.createElement('li');
      li.textContent = `${data.username} (${data.time}): ${data.message}`;
      messages.appendChild(li);
    });
  </script>
</head>
<body>
  <h1>Welcome to the Chat Application</h1>
  <ul id="messages"></ul>
  <input type="text" id="messageInput" placeholder="Type your message here">
  <button onclick="sendMessage()">Send</button>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now, when you run the application using node app.js, it will start the server at http://localhost:3000, and users can join the chat, send messages, and see real-time updates.

Keep in mind that this is a basic implementation and lacks many features that a full-fledged messaging app would have, such as user accounts, private messaging, message history, file sharing, and more. If you want to build a production-ready chat application like Messenger, you'll need to implement additional features, consider scalability, and handle various security concerns.

Top comments (0)