How To Create Login Page In Node.js Using Mongodb

Web Development Software

In this article, I will guide you through the process of creating a login page in Node.js using MongoDB. As a developer who has personally worked with this setup, I can assure you that it is a powerful combination that allows you to build robust and secure authentication systems.

Introduction

Before we dive into the technical details, let’s briefly discuss why creating a login page is an essential feature for web applications. When users visit your website, allowing them to create an account and log in not only provides a personalized experience but also enables you to implement role-based access control, protect sensitive information, and enhance data security.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine, which makes it an excellent choice for building server-side applications. MongoDB, on the other hand, is a NoSQL database that enables you to store and retrieve data in a flexible and scalable manner.

Setting up the Project

The first step is to set up a new Node.js project and install the necessary dependencies. You can use the following command to create a new project:

mkdir login-page

Once the project is created, navigate to the project directory and run the following command to initialize a new Node.js project:

npm init -y

Next, we need to install the required dependencies. Open your terminal or command prompt and run the following command:

npm install express mongoose bcrypt body-parser

Here, we are installing Express to create our server, Mongoose to interact with the MongoDB database, bcrypt to hash and compare passwords securely, and body-parser to parse incoming request bodies.

Creating the Login Page

Now that our project is set up, let’s start creating the login page. Create a new file named app.js in the project directory and add the following code:

“`javascript
const express = require(‘express’);
const mongoose = require(‘mongoose’);
const bcrypt = require(‘bcrypt’);
const bodyParser = require(‘body-parser’);

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

// Connect to MongoDB
mongoose.connect(‘mongodb://localhost/login-page’, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log(‘Connected to MongoDB’);
})
.catch((error) => {
console.error(‘Failed to connect to MongoDB’, error);
});

// Define user schema
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});

// Create User model
const User = mongoose.model(‘User’, userSchema);

// Login route
app.post(‘/login’, async (req, res) => {
const { username, password } = req.body;

try {
// Check if the user exists
const user = await User.findOne({ username });

if (!user) {
return res.status(404).send(‘User not found’);
}

// Compare the passwords
const isPasswordValid = await bcrypt.compare(password, user.password);

if (!isPasswordValid) {
return res.status(401).send(‘Invalid password’);
}

return res.send(‘Login successful’);
} catch (error) {
console.error(‘Failed to login’, error);
res.status(500).send(‘An error occurred’);
}
});

// Server listening
app.listen(3000, () => {
console.log(‘Server started on port 3000’);
});
“`

This code sets up an Express server, connects to the MongoDB database, defines a user schema, and creates the necessary routes for user login. When a user submits the login form, the server checks if the user exists and compares the hashed password with the input password using bcrypt.

Conclusion

In this tutorial, we walked through the process of creating a login page in Node.js using MongoDB. We learned how to set up the project, install the necessary dependencies, and implement the login functionality. By using Node.js and MongoDB together, we can create powerful and secure login systems for our web applications.

Feel free to explore further and add additional features like user registration, password reset, or OAuth-based login using third-party providers. Happy coding!