NodeJS login form allows users to log in to the website after they have created their account using the signup form.
We will be using the following technologies:
- NodeJS & Express: Backend server and routing
- MongoDB: NoSQL database for user data
- Mongoose: Object Data Modeling (ODM) library for MongoDB and NodeJS.
- EJS: Templating engine for views
- Passport.js: Authentication middleware for NodeJS applications.
Steps to Create Project and Install Modules
Step 1: Start the project using the following command in your project folder
npm init -yStep 2: Install the required modules using the following command
npm i express ejs mongoose express-session
npm i passport passport-local
npm i passport-local-mongoose Step 3: Create two folders inside the project directory using the following command
mkdir model
mkdir viewsStep 4: Create another file named app.js inside project directory
touch app.jsStep 5: Navigate inside model folder and create a file User.js which will contain our Schema
cd model
touch User.jsStep 6: Navigate inside views folder and create the following ejs files
cd views
touch home.ejs
touch login.ejs
touch secret.ejs
touch register.ejsStep 7: Run the following command to ensure all modules are loadedÂ
npm iProject Structure

The updated dependencies in package.json file.
"dependencies": {
"cors": "^2.8.5",
"ejs": "^3.1.10",
"express": "^5.1.0",
"express-session": "^1.18.1",
"mongodb": "^6.15.0",
"mongoose": "^8.13.2",
"passport": "^0.7.0",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^8.0.0",
}Add the following code in App.js and User.js file
// Filename - App.js
const express = require("express"),
mongoose = require("mongoose"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
passportLocalMongoose =
require("passport-local-mongoose");
const User = require("./model/User");
let app = express();
mongoose.connect("mongodb://localhost/27017");
app.set("view engine", "ejs");
app.use(express.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());
// 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", async (req, res) => {
const user = await User.create({
username: req.body.username,
password: req.body.password
});
return res.status(200).json(user);
});
// Showing login form
app.get("/login", function (req, res) {
res.render("login");
});
// Handling user login
app.post("/login", async function (req, res) {
try {
const user = await User.findOne({ username: req.body.username });
if (user) {
const result = req.body.password === user.password;
if (result) {
res.render("secret");
} else {
res.status(400).json({ error: "password doesn't match" });
}
} else {
res.status(400).json({ error: "User doesn't exist" });
}
} catch (error) {
res.status(400).json({ error });
}
});
app.get("/logout", function (req, res) {
req.logout(function (err) {
if (err) { return next(err); }
res.redirect('/');
});
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect("/login");
}
let port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Server Has Started!");
});
// Filename - model/User.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: {
type: String
},
password: {
type: String
}
})
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', User)
Add the following codes in the folder of viewsÂ
// Filename - views/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 - views/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 - views/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 - views/secret.ejs
<h1>This is secret page</h1>
<img src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png">
<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 application
Step 1: To run the above code you should first have the MongoDB server running
If you do not have the mongoose folder setup follow the article- How to Install MongoDB on Windows.
After setting up MongoDB start the server using following command
mongodStep 2: Type the following command in terminal of your project directory
node app.jsStep 3: Open your web browser and type the following address in the URL bar
http://localhost:3000/Output