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 page app.get("/", function (req, res) { res.render("home"); }); // Showing secret page app.get("/secret", isLoggedIn, function (req, res) { res.render("secret"); }); // Showing register form app.get("/register", function (req, res) { res.render("register"); }); // Handling user signup app.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 form app.get("/login", function (req, res) { res.render("login"); }); //Handling user login app.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%3AANd9GcQ5PdxXFw4u3BRG4166i7Nbk x0VyGGNt0hWc3loNeD7GIL4nbbo&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.
Recommended Posts:
- Signup Form Using Nodejs and MongoDB
- How to add a Login Form to an Image using HTML and CSS ?
- NodeJs CRUD Operations Using Mongoose and MongoDB Atlas
- Nodejs - Connect MongoDB with Node app using MongooseJS
- Nodejs | Automatic restart NodeJs server with nodemon
- HTML | Responsive Modal Login Form
- Login and Registration Project Using Flask and MySQL
- How to create admin login page using PHP ?
- How to use Selenium Web Driver and JavaScript to Login any website ?
- Automated Login For Captive Portals in Linux
- How to implement Facebook login in your Web app with Firebase ?
- How to implement Google Login in your Web app with Firebase ?
- Nodejs | authentication using Passportjs and passport-local-mongoose
- Cowsay in Nodejs using Requests library
- Nodejs | Web Crawling using Cheerio
- Generating Lighthouse Scores using NodeJS
- Upload and Retrieve Image on MongoDB using Mongoose
- 7 Famous Apps Built on NodeJS: Reasons and Benefits
- Which One is Most Demanding Back-End Web Framework between Laravel , NodeJS and Django ?
- Difference between Reactjs and Nodejs
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

