How To Create Login Page In Node.js Using Mysql

In this article, I will guide you through the process of creating a login page in Node.js using MySQL. As a developer with experience in backend development, I find this topic quite interesting and useful in building secure web applications. So, let’s dive into the details and explore the steps involved in creating a login page with MySQL as the database.

Getting Started

Before we begin, make sure you have Node.js and MySQL installed on your machine. If you don’t have them installed, you can download and install them from their official websites.

Once you have everything set up, let’s create a new directory for our project and navigate into it using the terminal or command prompt.

$ mkdir login-page
$ cd login-page

Next, initialize a new Node.js project by running the following command:

$ npm init -y

This will create a package.json file, which is used to manage your project’s dependencies and configurations.

Now, let’s install the necessary dependencies for our project. We will be using the express framework for handling HTTP requests, mysql for connecting to the MySQL database, and bcrypt for encrypting passwords.

$ npm install express mysql bcrypt

Setting up the Database

Before we can create the login page, we need to set up the MySQL database. Open your preferred MySQL client and create a new database. Let’s name it login_db.

Once the database is created, let’s create a table named users to store user information. The table should have the following columns:

  • id – Numeric ID for each user, set as the primary key.
  • username – The unique username for each user.
  • password – The hashed password for each user.

With the database and table set up, let’s move on to the implementation of the login page.

Implementing the Login Page

First, let’s create a new file named index.js in the root of our project directory. This file will act as the entry point of our application.

Inside index.js, let’s start by requiring the necessary modules:

const express = require('express');
const mysql = require('mysql');
const bcrypt = require('bcrypt');

Next, let’s set up the MySQL connection by creating a new pool:

const db = mysql.createPool({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'login_db'
});

Note: Replace your_username and your_password with your actual MySQL credentials.

Now, let’s create the Express application and set up the necessary middleware:

const app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

Let’s create a POST route for handling the login form submission:

app.post('/login', (req, res) => {
const { username, password } = req.body;

// Validate the input
if (!username || !password) {
return res.status(400).json({ message: 'Please provide both username and password' });
}

// Check if the user exists in the database
db.query('SELECT * FROM users WHERE username = ?', [username], (error, results) => {
if (error) {
console.log(error);
return res.status(500).json({ message: 'Internal server error' });
}

if (results.length === 0) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const user = results[0];

// Compare the provided password with the hashed password in the database
bcrypt.compare(password, user.password, (error, isMatch) => {
if (error) {
console.log(error);
return res.status(500).json({ message: 'Internal server error' });
}

if (!isMatch) {
return res.status(401).json({ message: 'Invalid credentials' });
}

// Successful login
return res.status(200).json({ message: 'Login successful' });
});
});
});

Finally, let’s start the server and listen on a specified port:

const port = 3000;

app.listen(port, () => {
console.log(`Server started on port ${port}`);
});

Now you can run the server by executing the following command:

$ node index.js

With the server running, you can open your web browser and navigate to http://localhost:3000 to access the login page.

Conclusion

In this article, we explored the process of creating a login page in Node.js using MySQL. We covered the steps from setting up the project and database to implementing the login functionality. By following this guide, you should now have a better understanding of how to create a secure login page in Node.js using MySQL as the database.

Remember, building secure web applications is crucial, and it’s important to implement proper security measures, such as password hashing and input validation, to protect user data.