How To Build Node.js Authentication System With MySQL?
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

Dependencies
"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)
);

Step 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.
//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.
//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.
// 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.
//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": "geek@geeksforgeeks.com",
"password": "password"
}
Ouput

- After Register User, the users table looks like this:

As 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": "geek@geeksforgeeks.com",
"password": "your_password"
}
- Login using Wrong Password:

- Login using Correct Password:
