Open In App
Related Articles

Build a Node.js-powered Chatroom Web App

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we are going to create a chatroom web app using Node.js. A Chatroom Web App is basically used to create a chatroom that is similar to a group chat, where users can come and join the group/ chatroom, send messages to the chatroom, and see other users’ messages.

We are going to set up a middleware EJS. EJS makes it easy to send data from your server file (app.js or server.js) to a web page. After that, we are going to use Body Parser by which we can capture user input values which are messages from the message box & store them in a collection. Then we are going to send the data of the collection to the chatroom using EJS so that other users can read it. 

Approach: Below is the step-by-step implementation of the above approach.

Step 1: Project Setup

Initializes NPM: Create and Locate your project folder into the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express ejs body-parser

To install Express, EJS, and Body Parser as dependencies inside your project

Create Server File: Create an ‘app.js’ file, inside this file require the Express Module, and create a constant ‘app’ for creating an instance of the express module, then set the EJS as the default view engine.

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

app.set('view engine', 'ejs');

Rearrange Your Directories: It is required to use ‘.ejs’ as an extension for the HTML file instead of ‘.html’ for using EJS inside it. Then you have to move every ‘.ejs’ file in the views directory inside your root directory. EJS is by default looking for ‘.ejs’ files inside the views folder.

Use EJS variable: Inside your updated .ejs file, you have to use EJS Variables to receive values from your server file. You can declare variables in EJS like

<%= variableName %>

home.ejs

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
</head>
  
<body>
    <%= variableName %>
</body>
  
</html>

                    

Send data to a variable: Inside your server file ( app.js or index.js ), you can send an EJS file along with some data by using the render method.

app.get("/", (req, res) => {
    res.render("home", { variableName: "Hello World!" })
})

app.js

Javascript

const express = require('express')
const app = express()
app.set('view engine', 'ejs')
  
app.get("/", (req, res) => {
     res.render("home", { variableName: "Hello World!" })
})
  
app.listen(3000, (req, res) => {
     console.log("App is running on port 3000")
})

                    

Fetching data from form to app.js: To receive input values of a form, we have to use a node package named body-parser.

Install body-parser:

npm install body-parser

Require body-parser module:

const bodyParser = require('body-parser')

And then

app.use( bodyParser.json() );      
app.use(bodyParser.urlencoded({    
     extended: true
}))

Then we can handle form data using the request object.

Step 2: Fetch Current Users and their messages: We have an array of lists of default users with their messages. Let’s send the array to our web page and show the list of default users with their messages. In the previous step, we just send a value to the variable, now we are sending the complete array.

app.js

Javascript

const express = require('express')
const bodyParser = require('body-parser')
const users = [{
    userMessage: "Hi",
    userName: "Aditya Gupta"
}, {
    userMessage: "Hello",
    userName: "Vanshita Jaiswal"
}]
  
const app = express()
  
app.set('view engine', 'ejs')
  
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}))
  
  
app.get("/", function (req, res) {
    res.render("home", {
        data: users
    })
})
  
app.listen(3000, (req, res) => {
    console.log("App is running on port 3000")
})

                    

Since we have so many elements inside our array and we have to print each of them so we have to use For Each Loop to loop through every single element inside our collection and display the details.

home.ejs

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>ChatRoom</title>
  
    <style>
        h2{
            margin: 12px 0px 0px 0px;
            padding: 0px;
        }
        p{
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
    
<body>
    <h1>ChatRoom</h1>
    <% data.forEach(element=> { %>
    <h2><%= element.userMessage %></h2>
      
<p> <%= element.userName %></p>
  
    <% }) %>
</body>
  
</html>

                    

Step 3: Add Users and their messages to the list: For this, we have to create a form and handle the form data inside our ‘app.js’ file using Body Parser.

home.ejs

<h1>Add Message</h1>

<form action="/" method="post">
     <input type="text" placeholder="User Name"
          name="userName">
     <input type="text" placeholder="Message"
          name="userMessage">
     <button type="submit">Send</button>
</form>

Handle form data inside ‘app.js’: We have to fetch values from a form using req.body.valueName, and then arrange it like an object and push it inside our user’s array.

app.js

app.post("/", (req, res) => {
   const inputUserName = req.body.userName
   const inputUserMessage = req.body.userMessage
   
   users.push({
       userName: inputUserName,
       userMessage: inputUserMessage,
   })
   
   res.render("home", {
       data: users
   })
})

Complete Code:

app.js

Javascript

const express = require('express')
const bodyParser = require('body-parser')
const users = [{
        userMessage: "Hi",
        userName: "Aditya Gupta"
    },
    {
        userMessage: "Hello",
        userName: "Vanshita Jaiswal"
    }
]
  
const app = express()
  
app.set('view engine', 'ejs')
  
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}))
  
  
app.get("/", function (req, res) {
    res.render("home", {
        data: users
    })
})
  
app.post("/", (req, res) => {
    const inputUserName = req.body.userName
    const inputUserMessage = req.body.userMessage
  
    users.push({
        userName: inputUserName,
        userMessage: inputUserMessage,
    })
  
    res.render("home", {
        data: users
    })
})
  
app.listen(3000, (req, res) => {
    console.log("App is running on port 3000")
})

                    

home.ejs

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>ChatRoom</title>
  
    <style>
        h2 {
            margin: 12px 0px 0px 0px;
            padding: 0px;
        }
  
        p {
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
    
<body>
    <h1>ChatRoom</h1>
    <% data.forEach(element=> { %>
    <h2><%= element.userMessage %></h2>
      
<p>by <%= element.userName %></p>
  
    <% }) %>
  
    <h1>Add Message</h1>
  
    <form action="/" method="post">
        <input type="text" placeholder="User Name"
               name="userName">
        <input type="text" placeholder="Message"
               name="userMessage">
        <button type="submit">Send</button>
    </form>
</body>
  
</html>

                    

Steps to run the application: Inside the terminal type the command to run your script.

node app.js

Output:

 



Last Updated : 20 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads