Build a Node.js-powered Chatroom Web App
Last Updated :
24 Jul, 2024
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:
Similar Reads
How to Build a Node.js Proxy Server ?
A proxy server acts as an intermediary between a client and other servers. It can be used for various purposes, including load balancing, security, and caching. In the context of web development, a proxy server forwards requests from clients to other servers, fetches responses, and sends them back t
4 min read
How To Build A Node.js API For Ethereum
Ethereum is a popular blockchain platform that allows developers to build decentralized applications (dApps). It uses a smart contract system that enables the execution of self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code.The
8 min read
AI-Powered Chatbot Platform with Node and Express.js
An AI Powered Chatbot using NodeJS and ExpressJS can be created using the free OpenAI's API Key that is provided for every user login. This article covers a basic syntax of how we can use ES6 (EcmaScript Version 6) to implement the functionalities of Node.js and Express.js including the use of REST
4 min read
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
How to build Node.js Blog API ?
In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters.Functionalities:Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we w
4 min read
How to Build a JavaScript App with ChatGPT?
AI is one of the most overhyped techs right now in the market. It is said that it will soon replace Software Engineers in creating complex software applications. In this article, we will test ChatGPT to create a JavaScript application by giving ChatGPT the prompts and will see if it can actually mak
6 min read
How to Build a Progressive Web App (PWA) from Scratch?
A Progressive Web App (PWA) is a kind of application software sent through the web, formed using standard web technologies such as HTML, CSS, and JavaScript. PWAs are planned to work on any platform that uses a standards-compliant browser, containing both desktop and portable devices. Steps to Build
3 min read
Build an Online Code Compiler using React.js and Node.js
In this article, we will learn how to build an online code compiler using React.js as frontend and Express.js as backend. Users will be able to write C, C++, Python, and Java code with proper syntax highlighting as well as compile and execute it online. The main objective of building an online compi
7 min read
How to Run a Node.js App as a Background Service ?
Running a Node.js application as a background service is a common requirement for ensuring that your app stays running even after you log out, or if the system restarts. This can be particularly important for server-side applications, APIs, or any long-running processes. This article explores severa
2 min read
How to build a simple Discord bot using Node.js ?
Discord is an instant messaging application mostly used by developers and gamer communities. Many discord servers use bots to automate the task. Bots are programs that allow us to automate some tasks like messaging, maintaining our server, etc. Discord provides us with many built-in bots. Discord al
3 min read