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.
Contents
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 withget
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 withget
method to display login form in the web browser - Also, Create
/login
route withpost
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 withget
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 withget
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);
Leave a Reply