Create Registration and Login Form in Node.js and MySQL

In this tutorial, you will learn how to create login and registration authentication forms in node express js with mysql database.

How to Build Login and Registration Form in Node js Express and MySQL

Here are steps:

Step 1: Create Node Js Application

Open your cmd or terminal window and run the express --view=ejs my-app command into it to create node express js application:

express --view=ejs my-app
cd my-app

And open your node express js setup in any text editor.

Step 2: Install Some Required Modules

To install some required module in application, Simply run the following commands on cmd or terminal window for that:

 npm install
 npm install express-flash --save
 npm install express-session --save
 npm install [email protected]
 npm install method-override --save
 npm install mysql --save
express-flash

Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
In this node js mysql crud tutorial express flash is used to display a warning, error and information message

express-session

Express-session is used to made a session as like in PHP. In this node js mysql crud tutorial, session is needed as the express requirement of express-flash.

express-validator

Express validator is used to validate form data it is easy to use. express-validator highly effective and efficient way to accelerate the creation of applications.

method-override

NPM is used to run a DELETE and PUT method from an HTML form. In several web browsers only support GET and POST methods.

MySQL

Driver to connect node.js with MySQL

Step 3: Connect Node js Express with Mysql Database

To use the following sql query to create database and table:

CREATE DATABASE IF NOT EXISTS `myapp` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `my_app`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

To create one folder named lib and inside it create a new file name db.js, and add the following code into it to connect MySQL database with the application:

 var mysql=require('mysql');
 var connection=mysql.createConnection({
   host:'localhost',
   user:'root',
   password:'your password',
   database:'my_app'
 });
connection.connect(function(error){
   if(!!error){
     console.log(error);
   }else{
     console.log('Connected!:)');
   }
 });
module.exports = connection; 

Step 4: Import Modules in app.js

Open your app.js file and import the following modules into it:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection  = require('./lib/db');
var authRouter = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    secret: '123456cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))
app.use(flash());
app.use(expressValidator());
app.use('/', authRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

Step 5: Create Login & Registration Route

Navigate to the routes directory and create an auth.js file, and create and add a root like the following:

var express = require('express');
var router = express.Router();
var connection  = require('../lib/db');
//display login page
router.get('/', function(req, res, next){
    res.render('auth/login', {
        title: 'Login',
        email: '',
        password: ''
    })
})
//display login page
router.get('/login', function(req, res, next){
    res.render('auth/login', {
        title: 'Login',
        email: '',
        password: ''
    })
})
//authenticate user
router.post('/authentication', function(req, res, next) {

    var email = req.body.email;
    var password = req.body.password;
        connection.query('SELECT * FROM users WHERE email = ? AND password = ?', [email, password], function(err, rows, fields) {
            if(err) throw err

            // if user not found
            if (rows.length <= 0) {
                req.flash('error', 'Please correct enter email and Password!')
                res.redirect('/login')
            }
            else { // if user found
                // render to views/user/edit.ejs template file
                req.session.loggedin = true;
                req.session.name = rows[0].name;
                res.redirect('/home');
            }
        })

})
//display login page
router.get('/register', function(req, res, next){
    res.render('auth/register', {
        title: 'Registration Page',
        name: '',
        email: '',
        password: ''
    })
})
// user registration
router.post('/post-register', function(req, res, next){
    req.assert('name', 'Name is required').notEmpty()           //Validate name
    req.assert('password', 'Password is required').notEmpty()   //Validate password
    req.assert('email', 'A valid email is required').isEmail()  //Validate email

    var errors = req.validationErrors()

    if( !errors ) {   //No errors were found.  Passed Validation!


        var user = {
            name: req.sanitize('name').escape().trim(),
            email: req.sanitize('email').escape().trim(),
            password: req.sanitize('password').escape().trim()
        }

            connection.query('INSERT INTO users SET ?', user, function(err, result) {
                //if(err) throw err
                if (err) {
                    req.flash('error', err)

                    res.render('auth/register', {
                        title: 'Registration Page',
                        name: '',
                        password: '',
                        email: ''
                    })
                } else {
                    req.flash('success', 'You have successfully signup!');
                    res.redirect('/login');
                }
            })
    }
    else {   //Display errors to user
        var error_msg = ''
        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })
        req.flash('error', error_msg)

        /**
         * Using req.body.name
         * because req.param('name') is deprecated
         */
        res.render('auth/register', {
            title: 'Registration Page',
            name: req.body.name,
            email: req.body.email,
            password: ''
        })
    }
})
//display home page
router.get('/home', function(req, res, next) {
    if (req.session.loggedin) {

        res.render('auth/home', {
            title:"Dashboard",
            name: req.session.name,
        });
    } else {
        req.flash('success', 'Please login first!');
        res.redirect('/login');
    }
});
// Logout user
router.get('/logout', function (req, res) {
  req.session.destroy();
  res.clearCookie('session');
  res.redirect('/login');
});
module.exports = router;

Step 6: Create Login and Registration Views

Navigate to the views directory and create the auth directory inside it, and then create some views in auth directory; Some of the views named are:

  • login.ejs
  • register.ejs
  • home.ejs

Open your login.ejs file and add the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
  <% if (messages.error) { %>
  <p style="color:red"><%- messages.error %></p>
  <% } %>

  <% if (messages.success) { %>
      <p style="color:green"><%- messages.success %></p>
  <% } %>
  <form action="/authentication" method="post" name="form1">
    <div class="form-group">
      <label for="exampleInputEmail1">Email</label>
      <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Password</label>
      <input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">
    </div>
    <input type="submit" class="btn btn-primary" value="Login">
    <a href="/register" class="btn btn-success ml-2">Register</a>
  </form>
</body>
</html>

To open register.ejs file and add the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
  <% if (messages.error) { %>
  <p style="color:red"><%- messages.error %></p>
  <% } %>

  <% if (messages.success) { %>
      <p style="color:green"><%- messages.success %></p>
  <% } %>
  <form action="/post-register" method="post" name="form1">
    <div class="form-group">
      <label for="exampleInputEmail1">Name</label>
      <input type="name" name="name" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter name" value="">
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Email</label>
      <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Password</label>
      <input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">
    </div>
    <input type="submit" class="btn btn-primary" value="Submit">
    <a href="/login" class="btn btn-success ml-2">Login</a>
  </form>
</body>
</html>

Open home.ejs file and add the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
  <div class="container">

  <% if (messages.error) { %>
  <p style="color:red"><%- messages.error %></p>
  <% } %>

  <% if (messages.success) { %>
      <p style="color:green"><%- messages.success %></p>
  <% } %>
  <div class="card">
    <div class="card-header">
     Dashboard <b><%= name %></b>
    </div>
    <div class="card-body">
      <h5 class="card-title">Welcome</h5>
      <p class="card-text">You have successfully login</p>
      <a href="/logout" class="btn btn-primary">Logout</a>
    </div>
  </div>
  </div>
</body>
</html>

Step 7: Run Development Server

Run npm start command on cmd or terminal window to start application development server:

//run the below command

npm start

Now, open browser and use the following urls to test login and registration application:

http://127.0.0.1:4000/
OR
http://127.0.0.1:4000/login

Conclusion

That’s it; You have learned how to create login system in node js using express js framework with MySQL db.

Recommended Node JS Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Create Registration and Login Form in Node.js and MySQL

  1. Thanks for one more wonderful informative post, I’m a regular reader of your blog Because You provide valuable data. I genuinely appreciate all of the hard function you put into this wonderful blog.

Leave a Reply

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