How To Build Node.js Authentication System With MySQL?
Last Updated :
21 Aug, 2024
Node.js is an open-source server-side JavaScript runtime environment established to develop server-side applications. The first task can be an implementation of an authentication system, this is one of the most frequently used processes in web development. In this article, we are going to learn how to create a basic authentication in Node.js using MySQL.
Prerequisites
Steps to Create Node.js Authentication System with MySQL
Step 1: Create the directory for the project.
mkdir geeksforgeeks
cd geeksforgeeks
Step 2: Initialize the application and install the required dependencies.
npm init -y
npm install express mysql2 bcrypt dotenv
Folder Structure
Folder StructureDependencies
"dependencies": {
"bcrypt": "^5.1.1",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"mysql2": "^3.11.0"
}
Step 3: Create and Configure the .env File
Create a .env file in the root directory of the project, it will contain environment-specific details like database access details.
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_password
DB_DATABASE=geeksforgeeks
Step 4: Create the MySQL database.
Make a new MySQL database and a table to store all the details of the users.
CREATE DATABASE geeksforgeeks;
USE geeksforgeeks;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE,
password VARCHAR(255)
);
Database Creation in MySQL workbenchStep 5: Create the Connection File
Create a db.js file to establish a connection to the MySQL database using the credentials from the .env file.
JavaScript
//db.js
require('dotenv').config();
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database!');
});
module.exports = connection;
Step 6: Implement User Registration
Create a new auth.js file that enables users to create an account. To enhance security, the bcrypt library will be used to hash password before storing in the database.
JavaScript
//auth.js
const express = require('express');
const bcrypt = require('bcrypt');
const db = require('./db');
const router = express.Router();
// Register a new user
router.post('/register', async (req, res) => {
const { name, email, password } = req.body;
try {
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert the new user into the database
const query = 'INSERT INTO users (name, email, password) VALUES (?, ?, ?)';
db.query(query, [name, email, hashedPassword], (err, result) => {
if (err) throw err;
res.status(201).send('User registered successfully');
});
} catch (error) {
res.status(500).send('Error registering user');
}
});
module.exports = router;
Step 7: Implement User Login
handle user login, checking whether the submitted email and password are correct.
JavaScript
// User login
router.post('/login', (req, res) => {
const { email, password } = req.body;
// Find the user by email
const query = 'SELECT * FROM users WHERE email = ?';
db.query(query, [email], async (err, results) => {
if (err) throw err;
if (results.length > 0) {
const user = results[0];
// Compare the hashed password
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
res.status(200).send('Login successful');
} else {
res.status(401).send('Invalid credentials');
}
} else {
res.status(404).send('User not found');
}
});
});
module.exports = router;
Step 8: Create the Server
Create a server.js file to set up the Express server and use the routes.
JavaScript
//server.js
const express = require("express");
const bcrypt = require("bcrypt");
const db = require("./db");
const router = express.Router();
// Register a new user
router.post("/register", async (req, res) => {
const { name, email, password } = req.body;
try {
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert the new user into the database
const query = "INSERT INTO users (name, email, password) VALUES (?, ?, ?)";
db.query(query, [name, email, hashedPassword], (err, result) => {
if (err) throw err;
res.status(201).send("User registered successfully");
});
} catch (error) {
res.status(500).send("Error registering user");
}
});
// User login
router.post('/login', (req, res) => {
const { email, password } = req.body;
// Find the user by email
const query = 'SELECT * FROM users WHERE email = ?';
db.query(query, [email], async (err, results) => {
if (err) throw err;
if (results.length > 0) {
const user = results[0];
// Compare the hashed password
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
res.status(200).send('Login successful');
} else {
res.status(401).send('Invalid credentials');
}
} else {
res.status(404).send('User not found');
}
});
});
module.exports = router;
Step 9: Test the authentication system in the context of security objectives.
When testing the authentication system you can use postman or any other API testing tool.
- Test the http://localhost:3000/user/register endpoint by sending a POST request with the following body:
{
"name": "GeeksForGeeks",
"email": "[email protected]",
"password": "password"
}
Ouput
Post request for register user- After Register User, the users table looks like this:
registered user data in tableAs we can see that password is stored in encrypted format.
- Test the http://localhost:3000/user/login endpoint by sending a POST request with the following body:
{
"email": "[email protected]",
"password": "your_password"
}
- Login using Wrong Password:
Post request for login with wrong password- Login using Correct Password:
Post request for login
Similar Reads
How to Connect Node.js Application to MySQL ?
To connect the Node App to the MySQL database we can utilize the mysql package from Node Package Manager. This module provides pre-defined methods to create connections, query execution and perform other database related operations. Approach to Connect Node App to MySQLFirst, initialize the node.js
2 min read
How to Hash String with md5 Function in Node.js ?
Hashing means taking any string as a key and generating some other string for it as a value. It's like key-value pair in maps or dictionaries. md5 hash is an encryption algorithm that takes the various bits of a file and outputs a unique text string. md5 is a one-way encryption algorithm, i.e. there
2 min read
How to Connect Mongodb Authentication by Node.js?
MongoDB is a popular NoSQL database that provides high performance, high availability, and easy scalability. In many applications, you need to connect to a MongoDB database with authentication to ensure data security. This article will guide you through the process of connecting to a MongoDB databas
3 min read
How to Create and Use Functions in MySQL with NodeJS?
We will learn how to create and use functions in MySQL with Node.js. MySQL functions allow encapsulating complex calculations and business logic within the database, which can then be called from Node.js applications. This method is particularly useful for reusing SQL code and maintaining a clean ap
3 min read
How to add authentication in file uploads using Node.js ?
There are multiple ways to upload files and apply authentications to them. The easiest way to do so is to use a node module called multer. We can add authentication by restricting users on file uploads such as they can upload only pdf and the file size should be less than 1 Mb. There are many module
3 min read
How to Enable Authentication on MongoDB ?
Authentication is enforced when access control is enabled on a MongoDB deployment, requiring users to identify themselves. Users can only conduct activities that are defined by their roles when visiting a MongoDB deployment with access control enabled. In this article, We will utilize the default au
4 min read
How to Use Connection Pooling with MySQL in Node.js?
MySQL is one of the most preferred relational databases, While Node.js is another name for JavaScript runtime environment. While assessing a large number of connections in the database in a Node. In this regard, effectiveness in managing them is also a significant determinant when developing and mai
3 min read
How to Create and Use Stored Procedures in MySQL with Node.js?
Stored procedures in MySQL are very useful in the following ways Regarding the encapsulation of business logic within a database. They can be run multiple times and do not cause a large load on the client-server connection. In this tutorial, we will learn how to create and use stored procedures in M
3 min read
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
Building an OTP Verification System with Node.js and MongoDB
In the present digital world, Securing your website or internet could be very crucial. One manner to increase protection is by using One Time Password (OTP) for the verification system. This will help you to steady your software and defend your website from unauthorized get entry. With increasing co
9 min read