Follow these simple steps to learn how to create a login form using Node.js and MongoDB. Login form allows users to login to the website after they have created their account using the signup form.
Installation of modules:
$ npm install ejs
Embeded javaScript lets you generate HTML markup with plain JavaScript.
$ npm install express --save
Express is a module framework for Node that you can use for applications.
$ npm install mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
$ npm install body-parser --save
Body-parser allows express to read the body and then parse that into a JSON object that we can understand.
npm install express-session --save
Express.js uses a cookie to store a session id.
npm install passport passport-local --save npm install passport-local-mongoose --save
Passport is authentication middleware for Node. js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.
Filename: app.js
var express = require("express"), mongoose = require("mongoose"), passport = require("passport"), bodyParser = require("body-parser"), LocalStrategy = require("passport-local"), passportLocalMongoose = require("passport-local-mongoose"), User = require("./models/user"); mongoose.set('useNewUrlParser', true);mongoose.set('useFindAndModify', false);mongoose.set('useCreateIndex', true);mongoose.set('useUnifiedTopology', true); var app = express();app.set("view engine", "ejs");app.use(bodyParser.urlencoded({ extended: true })); app.use(require("express-session")({ secret: "Rusty is a dog", resave: false, saveUninitialized: false})); app.use(passport.initialize());app.use(passport.session()); passport.use(new LocalStrategy(User.authenticate()));passport.serializeUser(User.serializeUser());passport.deserializeUser(User.deserializeUser()); //=====================// ROUTES//===================== // Showing home pageapp.get("/", function (req, res) { res.render("home");}); // Showing secret pageapp.get("/secret", isLoggedIn, function (req, res) { res.render("secret");}); // Showing register formapp.get("/register", function (req, res) { res.render("register");}); // Handling user signupapp.post("/register", function (req, res) { var username = req.body.username var password = req.body.password User.register(new User({ username: username }), password, function (err, user) { if (err) { console.log(err); return res.render("register"); } passport.authenticate("local")( req, res, function () { res.render("secret"); }); });}); //Showing login formapp.get("/login", function (req, res) { res.render("login");}); //Handling user loginapp.post("/login", passport.authenticate("local", { successRedirect: "/secret", failureRedirect: "/login"}), function (req, res) {}); //Handling user logout app.get("/logout", function (req, res) { req.logout(); res.redirect("/");}); function isLoggedIn(req, res, next) { if (req.isAuthenticated()) return next(); res.redirect("/login");} var port = process.env.PORT || 3000;app.listen(port, function () { console.log("Server Has Started!");}); |
Filename: home.ejs
<h1>This is home page</h1> <li><a href="/register">Sign up!!</a></li><li><a href="/login">Login</a></li><li><a href="/logout">Logout</a></li> |
Filename: login.ejs
<h1>login</h1> <form action="/login" method="POST"> <input type="text" name="username" placeholder="username"> <input type="password" name="password" placeholder="password"> <button>login</button></form> <h1>This is home page</h1> <li><a href="/register">Sign up!!</a></li><li><a href="/login">Login</a></li><li><a href="/logout">Logout</a></li> |
Filename: register.ejs
<h1> Sign up form </h1> <form action="/register" method="POST"> <input type="text" name="username" placeholder="username"> <input type="password" name="password" placeholder="password"> <button>Submit</button></form> <h1>This is home page</h1> <li><a href="/register">Sign up!!</a></li><li><a href="/login">Login</a></li><li><a href="/logout">Logout</a></li> |
Filename: secret.ejs
<h1>This is secrect page</h1> images?q=tbn%3AANd9GcQ5PdxXFw4u3BRG4166i7Nbkx0VyGGNt0hWc3loNeD7GIL4nbbo&usqp=CAU"> <h1>This is home page</h1> <li><a href="/register">Sign up!!</a></li><li><a href="/login">Login</a></li><li><a href="/logout">Logout</a></li> |
Steps to run the program:
- The project structure will look like this:

And the content of views directory will look like this:
Rest files will be the created after you runnpm initfor initialiasing.jsonfile. - Run index.js file using below command:
nodemon app.js
OR If you don’t have
nodemoninstalled you can run:node app.js

- Now go to your browser and type the following URL:
http://localhost:3000/

- First you will need to signup then only you can login into the app.

- Now you have successfully signup, Now this is login form as shown below:

This login form will take you to the Secret page as shown below:
So this is how you can create login form using Node.js and MongoDB.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


