Monday, 13 June 2022

How to Create Login System in Node.js Express with MySQL


In this Node.js Tutorial, we will step by step show you how to create simple login system in Node.js, Express and MySQL Database. So by using Login System only authenticated users on your web application can view or access restricted web pages of your website.

Under this post, you will learn how to make login with MySQL in Node.js using Express and we will create Node.js Express Login with MySQL Database and for validate user login we will use Session in Node.js Express application and store user login data in Session variable for authenticate user login access whole website, this is because we can access session data from any web page.

As we have know in any Software or Web based application Login page is required, so only authenticated user can access some restricted web page which we do not want to access general public. So for this we have to build Login page in our application and login is the passport for access our web application and only login user or authenticate user can access our web application. So login is the required feature of any web application. So for this reason we have build login page in Node JS.


How to Create Login System in Node.js Express with MySQL


Step for Create Node JS Express Login with MySQL Database


  1. MySQL Database Structure
  2. Install Node Express Application
  3. Make MySQL Database Connection with Node Express Application
  4. Configure Session
  5. Create Route
  6. Create Views
  7. Start Node Server & Check Output in browser

Step 1 - MySQL Database Structure


Before build Login System in Node js, first we have to create user_login table in your MySQL database. So for this you have to run following .sql script which will create user_login table in your MySQL Database.


<pre class="line-numbers language-sql">
<code class="language-sql">
--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `user_login`
--

CREATE TABLE `user_login` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(100) NOT NULL,
  `user_password` varchar(100) NOT NULL,
  `user_session_id` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_login`
--

INSERT INTO `user_login` (`user_id`, `user_email`, `user_password`, `user_session_id`) VALUES
(1, 'johnsmith@gmail.com', 'password', ''),
(2, 'peterparker@gmail.com', 'password', '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_login`
--
ALTER TABLE `user_login`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_login`
--
ALTER TABLE `user_login`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
</code>
</pre>

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/prism.js" type="text/javascript"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/themes/prism.css" rel="stylesheet" type="text/css"/>



So in this MySQL table, we can see two user login details already inserted, so we will use this data for build login system in Node js and we will validate this user login data under this Node js login application.

Step 2 - Install Node Express Application


For Create Login system in Node.js, here we have use Node Express framework. So first we need to download and install Node Express Framework Application.

So first we have to go directory in which we have run Node js. So for this we have to run following command.


f:
cd node


This command will first we have goes into f: drive and then after we have goes into node directory. Now under this directory, we have to create login directory. So for this, we have to run following command.


mkdir login


After creating this login directory, now we have goes into this directory, so for this we have to run following command.


cd login


After goes into this directory, we have to first download and install node express generator, so for this we have to run following command in your command prompt.


npm install -g express-generator


In the next process we have to install Express JS Application. So for this, we have to run following command which will download and install Node Express JS Application.


npx express --view=ejs


In this above command we have use ejs which template engine which we will for layout support in Express application, and once we have run this command then it will display complete directory structure of your Node Express JS Application directory structure which you can seen below.


create : public\
   create : public\javascripts\
   create : public\images\
   create : public\stylesheets\
   create : public\stylesheets\style.css
   create : routes\
   create : routes\index.js
   create : routes\users.js
   create : views\
   create : views\error.ejs
   create : views\index.ejs
   create : app.js
   create : package.json
   create : bin\
   create : bin\www

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=crud:* & npm start


In the next step, we need to install required default Node JS modules in your Express JS Application, so we have to run following command which will download required Node js modules in module directory.


npm install


After run this command here our download and install of Node JS Express Application process has been completed and we are ready to build simplete login application in Node js.





Step 3 - Make MySQL Database Connection with Node Express Application


Once we have download and install Node JS Express application in our computer, now first for build login system with mysql database in Node.js, we have need to make mysql database connection. So for make database connection Node.js Express application first we have to download and install node js mysql module. So for this we have to run following command.


npm install mysql


After download and install Node JS MySQL module, now for make MySQL database connection, we have to create database.js file in the root directory and under this file we have to define MySQL database configuration for make database connection in Node.js Express Application. You can see, we have to define following MySQL database configuration details under database.js file.

database.js

const mysql = require('mysql');

const connection = mysql.createConnection({
	host : 'localhost',
	database : 'testing',
	user : 'root',
	password : ''
});

connection.connect(function(error){
	if(error)
	{
		throw error;
	}
	else
	{
		console.log('MySQL Database is connected Successfully');
	}
});

module.exports = connection;


Step 4 - Configure Session


In this tutorial, we have use Session for store user login detail under session variable. So here we have use express-session module has been used for building a user session. So first we need to download express-session module in our Node JS Express Application. So we have go to command prompt and run following command, which will download and install express-session module in our Node JS Express Application.


npm install express-session --save


After download and Install express-session module, now for use session in our Node JS Express application, we have to configure session in app.js file. So under this file, we have to add following session configuration details in app.js file after var app = express() code.

app.js

app.use(session({
  secret : 'webslesson',
  resave : true,
  saveUninitialized : true
}));


So after add session configuration in app.js file, now we can see session in our Node JS Express Application.

Step 5 - Create Route


In this step, we have to create route for load login web page and handle login form data for validate user login details. So for create route, we have to open routes/index.js file.

Under this file for load login page in the browser, we have to create get route, which will load views/index.ejs file in the browser and while loading this page, we have render session data also with this route. So we can validate user login status.

After this for handle login form data for authenticate user login. Here we have create post(/login) route. Under this route first it has store login form data in local variable and after this it has validate user login form data with MySQL database data. If both data match then it will store user id in session variable and redirect web page to index route on which user can view welcome message with logout button for logout from system.

And after this, we have create get route for handle logout request. Under this route, it has delete all session data and user will redirect to login page.

routes/index.js

var express = require('express');
var router = express.Router();

var database = require('../database');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express', session : req.session });
});

router.post('/login', function(request, response, next){

    var user_email_address = request.body.user_email_address;

    var user_password = request.body.user_password;

    if(user_email_address && user_password)
    {
        query = `
        SELECT * FROM user_login 
        WHERE user_email = "${user_email_address}"
        `;

        database.query(query, function(error, data){

            if(data.length > 0)
            {
                for(var count = 0; count < data.length; count++)
                {
                    if(data[count].user_password == user_password)
                    {
                        request.session.user_id = data[count].user_id;

                        response.redirect("/");
                    }
                    else
                    {
                        response.send('Incorrect Password');
                    }
                }
            }
            else
            {
                response.send('Incorrect Email Address');
            }
            response.end();
        });
    }
    else
    {
        response.send('Please Enter Email Address and Password Details');
        response.end();
    }

});

router.get('/logout', function(request, response, next){

    request.session.destroy();

    response.redirect("/");

});

module.exports = router;




Step 6 - Create Views


In this step, we have to create ejs template file for display HTML output in the browser. So in this tutorial, we have create views/index.ejs template file. This file has been receive data from route and it has receive session data also.

This session data has been used to check user is login into system or not. If user is login then on this template file user will see welcome message with logout link and if user is not login into system then user will sess login form on the web page. So below you can find source code of views template file.

views/index.ejs

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>Login System in Node.js Express</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-primary"><b>Login System in Node.js Express</b></h1>

            <div class="row mt-5">
                <div class="col-md-3">&nbsp;</div>
                <div class="col-md-6">
                <% if(session.user_id) { %>

                    <h1>Hi User, Welcome</h1>

                    <a href="/logout" class="btn btn-primary">Logout</a>

                <% } else { %>

                    <div class="card">
                        <div class="card-header">Login</div>
                        <div class="card-body">
                            <form method="post" action="/login">
                                <div class="mb-3">
                                    <label>Email Address</label>
                                    <input type="email" name="user_email_address" class="form-control" />
                                </div>
                                <div class="mb-3">
                                    <label>Password</label>
                                    <input type="password" name="user_password" class="form-control" />
                                </div>
                                <div class="mb-3">
                                    <input type="submit" class="btn btn-primary" value="Login" />
                                </div>
                            </form>
                        </div>
                    </div>

                <% } %>
                </div>
            </div>
        </div>
    </body>
</html>


Step 7 - Start Node Server & Check Output in browser


Once you have follow all above step, so you have almost build Login System in Node JS Exppress framework. Now you need to check output in the browser. So first we have to start Node JS server, so we have go into command prompt and run following command.


npm start


This command will start node js server and for check output in the browser, you have to hit following url in the browser which will display node js express application login page on the web page.


http://localhost:3000/


So if you have following all above step and check output in the browser. So in this tutorial you have learn How to create simple Login system in Node js Express application with MySQL database. So if you have use MySQL with Node js then this tutorial will help to create Login page in Node js using Express framework.





1 comment:

  1. I think you have a typo.

    router.get('/', function(req, res, next) {

    should read:

    router.get('/login', function(req, res, next) {

    ReplyDelete