Open In App

How to build User Management System using Node.js ?

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a User Management System. A User Management System is basically used to manage the users of any organization, organizations can View Users, Add Users, Delete Users and Update Users. 

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 from the form & store them in a collection. Then we are going to send the data of the collection to the web page. We are also going to create the Delete Route for deleting users and an Update Route for updating the data of users.

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




<!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




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: We have an array of lists of users with different properties. Let’s send the array to our web page and show the list of current users. In the previous step, we just send a value to the variable, now we are sending the complete array.

app.js




const express = require('express')
const bodyParser = require('body-parser')
const users = [{
    userName: "Aditya Gupta",
    userEmail: "aditya@gmail.com",
    userAge: "22",
    userUniqueId: '1'
},
{
    userName: "Vanshita Jaiswal",
    userEmail: "vanshita@gmail.com",
    userAge: "21",
    userUniqueId: '2'
},
{
    userName: "Sachin Yadav",
    userEmail: "sachin@gmail.com",
    userAge: "22",
    userUniqueId: '3'
}
]
  
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




<!DOCTYPE html>
<html>
  
<head>
    <title>User Management System</title>
</head>
<style>
    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }
  
    td,
    th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
    }
  
    tr:nth-child(even) {
        background-color: #dddddd;
    }
</style>
  
<body>
    <h2>User Management System</h2>
    <table>
        <tr>
            <th>User Id</th>
            <th>User Name</th>
            <th>User Email</th>
            <th>Age</th>
        </tr>
        <% data.forEach(element=> { %>
            <tr>
                <td>
                    <%= element.userUniqueId %>
                </td>
                <td>
                    <%= element.userName %>
                </td>
                <td>
                    <%= element.userEmail %>
                </td>
                <td>
                    <%= element.userAge %>
                </td>
            </tr>
        <% }) %>
    </table>
</body>
  
</html>


Step 2: Add Users 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

<h2>Add User</h2>

<form action="/" method="post">
       <input type="text" placeholder="User
         Unique Id" name="userUniqueId">
       <input type="text" placeholder="User Name" 
           name="userName">
       <input type="text" placeholder="User Email"
            name="userEmail">
       <input type="text" placeholder="User Age"
            name="userAge">
       <button type="submit">Submit</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.post("/", (req, res) => {
   const inputUserName = req.body.userName
   const inputUserEmail = req.body.userEmail
   const inputUserAge = req.body.userAge
   const inputUserUniqueId = req.body.userUniqueId
   
   users.push({
        userName: inputUserName,
        userEmail: inputUserEmail,
        userAge: inputUserAge,
        userUniqueId: inputUserUniqueId
   })
   
   res.render("home", {
       data: users
   })
})

Step 3: Delete Users:  Updating Web Page giving a delete option: We have to create a form that sends the uersUniqueId to the server file ‘app.js’.

home.ejs

<table>
       <tr>
         <th>User Id</th>
         <th>User Name</th>
         <th>User Email</th>
         <th>Age</th>
         <th>Delete</th>
       </tr>
       <% data.forEach(element => { %>
       <tr>
         <td><%= element.userUniqueId %></td>
         <td><%= element.userName %></td>
         <td><%= element.userEmail %></td>
         <td><%= element.userAge %></td>
         <td>
               <form action="/delete" method="post">
                 <input type="text" style="display: none;" 
                    name="userUniqueId" 
                    value="<%= element.userUniqueId %>">
                 <button type="submit">Delete</button>
               </form>
         </td>
       </tr>
       <% }) %>
 </table>

For deleting a user, we have to create a delete route where we are going to fetch the requested user’s ‘userUniqueId’ which the organization wants to delete, and search for the element which has the same ‘userUniqueId’, and delete the element.

app.js

app.post('/delete', (req, res) => {
       var requestedUserUniqueId = req.body.userUniqueId;
       var j = 0;
       users.forEach(user => {
           j = j + 1;
           if (user.userUniqueId === requestedUserUniqueId) {
               users.splice((j - 1), 1)
           }
       })
       res.render("home", {
           data: users
       })
})

Step 4: Update the user’s data: Let’s add a form to update the user’s data

home.ejs

<h2>Update User</h2>

<form action="update" method="post">
       <input type="text" placeholder="User Unique Id"
        name="userUniqueId">
       <input type="text" placeholder="User Name" 
           name="userName">
       <input type="text" placeholder="User Email" 
           name="userEmail">
       <input type="text" placeholder="User Age" 
           name="userAge">
       <button type="submit">Update</button>
</form>

Making update route for updating the data of the users: Again we have to fetch the details from the update form, and we search for the element having ‘userUniqueId’ same as we fetch from the form, and then we rewrite all the fetch details to the found element.

app.js

app.post('/update', (req, res) => {
       const inputUserName = req.body.userName
       const inputUserEmail = req.body.userEmail
       const inputUserAge = req.body.userAge
       const inputUserUniqueId = req.body.userUniqueId
       var j = 0;
   
       users.forEach(user => {
           j = j + 1;
           if (user.userUniqueId === inputUserUniqueId) {
               user.userName = inputUserName
               user.userEmail = inputUserEmail
               user.userAge = inputUserAge
           }
       })
   
       res.render("home", {
           data: users
       })
})

Complete Code:

home.ejs




const express = require('express')
const bodyParser = require('body-parser')
const users = [{
        userName: "Aditya Gupta",
        userEmail: "aditya@gmail.com",
        userAge: "22",
        userUniqueId: '1'
    },
    {
        userName: "Vanshita Jaiswal",
        userEmail: "vanshita@gmail.com",
        userAge: "21",
        userUniqueId: '2'
    },
    {
        userName: "Sachin Yadav",
        userEmail: "sachin@gmail.com",
        userAge: "22",
        userUniqueId: '3'
    }
]
  
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 inputUserEmail = req.body.userEmail
    const inputUserAge = req.body.userAge
    const inputUserUniqueId = req.body.userUniqueId
  
    users.push({
         userName: inputUserName,
         userEmail: inputUserEmail,
         userAge: inputUserAge,
         userUniqueId: inputUserUniqueId
    })
  
    res.render("home", {
        data: users
    })
})
  
app.post('/delete', (req, res) => {
    var requestedUserUniqueId = req.body.userUniqueId;
    var j = 0;
    users.forEach(user => {
        j = j + 1;
        if (user.userUniqueId === requestedUserUniqueId) {
            users.splice((j - 1), 1)
        }
    })
    res.render("home", {
        data: users
    })
})
  
app.post('/update', (req, res) => {
    const inputUserName = req.body.userName
    const inputUserEmail = req.body.userEmail
    const inputUserAge = req.body.userAge
    const inputUserUniqueId = req.body.userUniqueId
  
    var j = 0;
    users.forEach(user => {
        j = j + 1;
        if (user.userUniqueId === inputUserUniqueId) {
            user.userName = inputUserName
            user.userEmail = inputUserEmail
            user.userAge = inputUserAge
        }
    })
    res.render("home", {
        data: users
    })
})
  
app.listen(3000, (req, res) => {
    console.log("App is running on port 3000")
})


app.js




const express = require('express')
const bodyParser = require('body-parser')
const users = [{
    userName: "Aditya Gupta",
    userEmail: "aditya@gmail.com",
    userAge: "22",
    userUniqueId: '1'
},
{
    userName: "Vanshita Jaiswal",
    userEmail: "vanshita@gmail.com",
    userAge: "21",
    userUniqueId: '2'
},
{
    userName: "Sachin Yadav",
    userEmail: "sachin@gmail.com",
    userAge: "22",
    userUniqueId: '3'
}
]
  
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 inputUserEmail = req.body.userEmail
    const inputUserAge = req.body.userAge
    const inputUserUniqueId = req.body.userUniqueId
  
    users.push({
        userName: inputUserName,
        userEmail: inputUserEmail,
        userAge: inputUserAge,
        userUniqueId: inputUserUniqueId
    })
  
    res.render("home", {
        data: users
    })
})
  
app.post('/delete', (req, res) => {
    var requestedUserUniqueId = req.body.userUniqueId;
    var j = 0;
    users.forEach(user => {
        j = j + 1;
        if (user.userUniqueId === requestedUserUniqueId) {
            users.splice((j - 1), 1)
        }
    })
    res.render("home", {
        data: users
    })
})
  
app.post('/update', (req, res) => {
    const inputUserName = req.body.userName
    const inputUserEmail = req.body.userEmail
    const inputUserAge = req.body.userAge
    const inputUserUniqueId = req.body.userUniqueId
  
    var j = 0;
    users.forEach(user => {
        j = j + 1;
        if (user.userUniqueId === inputUserUniqueId) {
            user.userName = inputUserName
            user.userEmail = inputUserEmail
            user.userAge = inputUserAge
        }
    })
    res.render("home", {
        data: users
    })
})
  
app.listen(3000, (req, res) => {
    console.log("App is running on port 3000")
})


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads