• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms And Conditions
  • Contact Us

CodingStatus

- Learn to Build Web Applications

  • Home
  • HTML
  • CSS
  • JavaScript
  • jQuery
  • Ajax
  • Node.js
  • PHP
  • Tips

Create Registration and Login Form in Node.js & MySQL

November 1, 2020 By Noor Khan Leave a Comment

In this tutorial, You will learn to create a Registration and Login Form in Node.js, Express & MySQL. Even you will get its complete source code with a complete guide step by step. Once you configure all the given steps, You will easily integrate Sign-in & signup system in your project.

registration and login form in node.js, mysql

Contents

  • User Login and Registration using node.js & Express
    • 1. Install Express Application
    • 2. Install Express Session
    • 3. Create MySQL Database & Table
    • 4. Connect Node.js App to MySQL Database
  • Create Registration Form in Node.js & MySQL
    • 1. Create a Registration Form
    • 2. Create Registration Route
    • 3. Load Registration Route
    • 4. Open Registration Form
  • Create Login Form in Node.js & MySQL
    • 1. Create a Login Form Form
    • 2. Create Login Route
    • 3. Load Login Route
    • 4. Open Login Form
  • Create a Dashboard in Node.js & Express
    • 1. Create a Dashboard Page
    • 2. Create Dashboard Route
    • 3. Load Dashboard Route
  • Create Logout in Node.js & Express
    • 2. Create Logout Route
    • 3. Load Logout Route

User Login and Registration using node.js & Express

Before creating the Login and Registration form, you will have to configure the following things –

1. Install Express Application

First of all, Make sure Node.js is installed on your computer/laptop. After that. You should install the Express Application.

Here is the folder structure of the Express App is shown with only necessary files & folders.

nodeapp/
  |__routes/
  |    |__registration.js
  |    |__login.js
  |    |__dashboard.js
  |    |__logout.js
  |__views/
  |    |__registration-form.ejs
  |    |__login-form.ejs
  |    |__dashbora.ejs
  |__app.js
  |__database.js
  |

2. Install Express Session

Install express session with the help of the following command –

nodeapp> npm install express-session

 

After that, include the following session package just after require('morgan') in the root file app.js

var session = require('express-session')

 

Also, include the following line of code just after app.use(cookieParser()) in app.js

app.use(session({ 
  secret: '123456cat',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 }
}))

3. Create MySQL Database & Table

Create a MySQL database with the name nodeapp

CREATE DATABASE nodeapp

Also, create a table with the name registration in the database nodeapp. This table will be used to store the log in detail of registered users –

CREATE TABLE `registration` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `first_name` varchar(30) DEFAULT NULL,
  `last_name` varchar(30) DEFAULT NULL,
  `gender` varchar(10) DEFAULT NULL,
  `email_address` varchar(50) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

4. Connect Node.js App to MySQL Database

First, create a connection file database.js and use the following script to connect the Node.js app to the MySQL database

File Name – database.js

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // assign your host name
  user: 'root',      //  assign your database username
  password: '',      // assign your database password
  database: 'nodeapp' // assign database Name
}); 
conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
});
module.exports = conn;

After configuring the above steps successfully, go to setup Registration and Login Form from the next steps –

Create Registration Form in Node.js & MySQL

Now, you have to set up a registration form through the following steps that are very simple & understandable

1. Create a Registration Form

Create a Registration form with the following input fields & its necessary attributes –

 Field Name   Type Attribute  Name Attribute
 First Name  type=”text”  name=”first_name”
 Last Name  type=”text”  name=”last_name”
 Gender  type=”radio”  name=”gender”
 Email Address  type =”email”  name=”email_address”
 Password  type=”password”  name=”password”
 Confirm Password  type=”password”  name=”confirm_password”

Also, Form must have the following two attribute –

  • method=”post”
  • action=”/register”

Path – views/registration-form.ejs

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="registration-form">
  <h3>Registration Form</h3>
<p> <%=(typeof alertMsg!='undefined')? alertMsg:''%></p>
<form method="post" action="register">
<div class="form-container">
   <div<input type="text" placeholder="First Name" name="first_name" required"></div>
   <div><input type="text" placeholder="Last Name Name" name="last_name" required></div>
</div>
<div class="form-container">
  <div><input type="password" placeholder="Password" name="password"></div>
  <div><input type="password" placeholder="Confirm Password" name="confirm_password" ></div> 
</div>
<div class="form-container">  
   <div><input type="email" placeholder="Email Address" name="email_address" required></div>
   <div><br><input type="radio" value="male" name="gender" required><label>Male</label>
       <input type="radio" value="female" name="gender" required><label>Female</label>
  </div>
</div>
<button type="submit">Register Now</button>
<a href="/login">Login</a>
</form>
</div>

</body>
</html>

2. Create Registration Route

To create a registration route, you have to configure the following steps –

  • Include database connection file database.js
  • Create /register route with get method to display registration form in the web browser
  • Also, Create /register route with post method to store user input into the MySQL table. Thi route will be called when you submit the registration form.

Path – routes/registration.js

var express = require('express');
var router = express.Router();
var db=require('../database');

// to display registration form 
router.get('/register', function(req, res, next) {
  res.render('registration-form');
});

// to store user input detail on post request
router.post('/register', function(req, res, next) {
    
    inputData ={
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email_address: req.body.email_address,
        gender: req.body.gender,
        password: req.body.password,
        confirm_password: req.body.confirm_password
    }
// check unique email address
var sql='SELECT * FROM registration WHERE email_address =?';
db.query(sql, [inputData.email_address] ,function (err, data, fields) {
 if(err) throw err
 if(data.length>1){
     var msg = inputData.email_address+ "was already exist";
 }else if(inputData.confirm_password != inputData.password){
    var msg ="Password & Confirm Password is not Matched";
 }else{
     
    // save users data into database
    var sql = 'INSERT INTO registration SET ?';
   db.query(sql, inputData, function (err, data) {
      if (err) throw err;
           });
  var msg ="Your are successfully registered";
 }
 res.render('registration-form',{alertMsg:msg});
})
     
});
module.exports = router;

3. Load Registration Route

Load the following registration route just below the require('./routes/users') in root file app.js

var registrationRouter = require('./routes/registration');

 

Also, use the registration route just below app.use('/users', usersRouter) in app.js

app.use('/', registrationRouter);

4. Open Registration Form

After completing the previous steps, open the registration form in your web browser by entering the following URL

http://localhost:3000/register

After that, Enter the required information and submit the registration form. Then you will be registered successfully and your registered data will be saved in the registration table.

Create Login Form in Node.js & MySQL

Now, you have to set up a login form through the following steps that are very simple & understandable

1. Create a Login Form Form

Create a Registration form with the following input fields & its necessary attributes –

 Field Name   Type Attribute  Name Attribute
 Email Address  type =”email”  name=”email_address”
 Password  type=”password”  name=”password”

Also, Form must have the following two attribute –

  • method=”post”
  • action=”/login”

Path – views/login-form.ejs

<!DOCTYPE html>
<html>
<head>  
</head>
<body>
<div class="login-form">
  <h3>Login Form</h3>
<p><%=(typeof alertMsg!='undefined')? alertMsg:''%></p>
<form method="post" action="/login">
      <input type="email" placeholder="Email Address" name="email_address" required">
      <input type="password" placeholder="Password" name="password" required">
       <button type="submit">Login Now</button>
       <a href="/register">New Registration</a>
  </div>
</form>
</div>

</body>
</html>

2. Create Login Route

To create a login route, you have to configure the following steps –

  • Include database connection file database.js
  • Create /login route with get method to display login form in the web browser
  • Also, Create /login route with post method to login with email address & password. This route will be called when you submit the login form.

Path – routes/login.js

var express = require('express');
var router = express.Router();
var db=require('../database');
/* GET users listing. */
router.get('/login', function(req, res, next) {
  res.render('login-form');
});

router.post('/login', function(req, res){
    var emailAddress = req.body.email_address;
    var password = req.body.password;

    var sql='SELECT * FROM registration WHERE email_address =? AND password =?';
    db.query(sql, [emailAddress, password], function (err, data, fields) {
        if(err) throw err
        if(data.length>0){
            req.session.loggedinUser= true;
            req.session.emailAddress= emailAddress;
            res.redirect('/dashboard');
        }else{
            res.render('login-form',{alertMsg:"Your Email Address or password is wrong"});
        }
    })

})

module.exports = router;

3. Load Login Route

Load the following login route just below the require('./routes/registration') in root file app.js

var loginRouter = require('./routes/login');

 

Also, use the registration route just below app.use('/', registrationRouter) in app.js

app.use('/', loginRouter);

4. Open Login Form

After completing the previous login steps, open the login form in your web browser by entering the following URL

http://localhost:3000/login

After that, log in with the registered email address & password. Then you will be logged in successfully and redirected to the dashboard page.

Create a Dashboard in Node.js & Express

Now, you have to set up a dashboard page through the following steps that are very simple.

1. Create a Dashboard Page

Here, I have created just a simple dashboard. but you can create it according to your project requirement.

You should implement the following steps on the dashboard page –

  • Display the email address of the logged-in user using <%=email %> that is coming from a session. Don’t worry It is explained in the next step.
  • Create a logout link with the route  /logout that will be explained in the logout configuration steps

Path – views/dashboard.ejs

<!DOCTYPE html>
<html>
    <head>
        <title>Dashboard</title>
    </head>
    <body>
        <h2>Welcome to Dashboard</h2>
        <p><b>Login Email</b> - <%=email %></p>
        <p><a href="/logout">Logout</a></p>
    </body>
</html>

2. Create Dashboard Route

To create a dashboard route, you have to configure the following steps –

  • Create /dashboard route with get method to display dashboard page in the web browser
  • Also, the Dashboard page will open when you log in successfully otherwise It will redirect to the login page.

Path – routes/dashboard.js

var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/dashboard', function(req, res, next) {
    if(req.session.loggedinUser){
        res.render('dashboard',{email:req.session.emailAddress})
    }else{
        res.redirect('/login');
    }
});

module.exports = router;

3. Load Dashboard Route

Load the following login route just below the require('./routes/login') in root file app.js

var dashboardRouter = require('./routes/dashboard');

 

Also, use the registration route just below app.use('/', loginRouter) in app.js

app.use('/', dashboardRouter);

Create Logout in Node.js & Express

Now, you have to set up a dashboard page through the following steps

2. Create Logout Route

To create a logout route, you have to configure the following steps –

  • Create /logout route with get method to logout
  • When you click the logout link, the session will be destroyed then you will be redirected to the login page.

Path – routes/logout.js

var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/logout', function(req, res) {
  req.session.destroy();
  res.redirect('/login');
});

module.exports = router;

3. Load Logout Route

Load the following login route just below the require('./routes/dashboard') in root file app.js

var logoutRouter = require('./routes/logout');

 

Also, use the registration route just below app.use('/', dashboardRouter) in app.js

app.use('/', logoutRouter);

 

 

Filed Under: Node.js

You may like also

  1. Simple Login Form in PHP and MySQL
  2. Simple Way to Integrate Facebook Login in PHP
  3. Login With Google Account on Website Using PHP MySQL
  4. PHP Registration Form – Create Registration Form Using PHP

Hey there, Welcome to CodingStatus. My Name is Noor Khan from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Follow us

  • facebook
  • twitter
  • linkedin
  • pinterest

Recent Posts

  • How to Learn Web Development Step by Step
  • How to Learn Web Designing From Basics
  • How to Become a Programmer Step By Step
  • 10 Best Google Chrome Extensions for Web Developers
  • Top 10 Web Designing Languages for Beginners

Latest Node.js Tutorials

  • Fetch data from MongoDB Using Mongoose and Node.js Express
  • Node.js Form Validation with an Example
  • Upload Multiple Files Using Multer in Node.js and Express
  • Node.js File Upload Using Express Multer
  • How to Display Image From MySQL Database in Node.js
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2021 CodingStatus - All Rights Reserved