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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read