How to check if an email address already exists with Node.js & MySQL

As the popularity of web applications continues to grow, it has become increasingly important to implement robust authentication systems tha...

As the popularity of web applications continues to grow, it has become increasingly important to implement robust authentication systems that can verify user identities. One critical aspect of user authentication is ensuring that users do not create multiple accounts using the same email address. In this blog, we will explore how to use Node.js and MySQL to check if an email address already exists in a database.

Create Working Directory


First we have to make Node.js working envrionment, so first we have goes to directory from where we have to run node.js application. So in command prompt we have to run following command.


f:
cd node
mkdir email_exists_or_not


So this command will first goes to F: drive and then after it will goes into node directory and after this it will create email_exists_or_not directory in which we will make node.js application for check email address exists or not in MySQL database.

Next we want to download Node.js Express module, so in command prompt we have to run following command.


npm install express


So this command will download Node.js Express module under this email_exists_or_not directory. Now we can open this email_exists_or_not directory in text editor for create Node.js Email Exists or not with MySQL Database.


How to check if an email address already exists with Node.js & MySQL


MySQL database Structure


Below you can find MySQL database structure for create Node.js Email Exists or not Application with MySQL database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'John Smith', 'john_smith@gmail.com', '$2y$10$8am2/JEN1ARvndVsgl.YvegRpbrPZuhG0nA79k8sYNk5RdDNKNcS2', 'ksxo8HGQLFpUenlAFKfTfWMqk2cJuDhqrnoBa6ogZBf1ZbRwkNzAxE4AFn7o', '2018-03-05 00:29:44', '2018-03-05 00:29:44');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;


After this under email_exists_or_not directory, we have to create index.html file and under this file we have to create one HTML form for get email address details from user and after this we have to write JavaScript for send Ajax request to node.js application for check email exists or not in MySQL Database.

index.html - (Client-side (HTML with AJAX))

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Email Availability Checker</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h3>How to check if email address is already in use or not in Node.js ?</h3>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Enter your eMail</div>
                <div class="card-body">
                    <form id="email-form">
                        <div class="mb-3">
                            <label for="email-input">Enmail Address</label>
                            <input type="email" id="email-input" class="form-control" />
                            <span id="email-message"></span>
                        </div>
                        <button type="submit" class="btn btn-primary" id="submit-btn">Check Email</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script>

const form = document.querySelector('#email-form');

const message = document.querySelector('#email-message');

form.addEventListener('submit', (event) => {

    event.preventDefault();

    const email = document.querySelector('#email-input').value;

    if(email != '')
    {
        const xhr = new XMLHttpRequest();

        xhr.open('POST', 'http://localhost:3000/check-email', true);

        xhr.setRequestHeader('Content-Type', 'application/json');
        
        xhr.onload = () => {

            if(xhr.status === 200)
            {
                const response = JSON.parse(xhr.responseText);

                if(response.emailExists)
                {
                    message.innerHTML = '<span class="badge bg-danger">Email is already in use</span>';
                }
                else
                {
                    message.innerHTML = '<span class="badge bg-success">Email is available</span>';
                }
            }
            else
            {
                message.innerHTML = '<span class="badge bg-info">Error checking email availability</span>';
            }
        };

        xhr.onerror = () => {
            message.innerHTML = '<span class="badge bg-info">Error checking email availability</span>';
        };

        xhr.send(JSON.stringify({ email }));
    }
    else
    {
        message.innerHTML = '<span class="badge bg-info">Please Enter Email</span>';
    }

});

</script>





Below you can find description of JavaScript Code part.


const form = document.querySelector('#email-form');

This line of code selects the HTML form element with an id of email-form and stores it in the form variable.


const message = document.querySelector('#email-message');

This line of code selects the HTML element with an id of email-message and stores it in the message variable.


form.addEventListener('submit', (event) => {

});

This line of code adds a listener to the submit event of the form element. When the form is submitted, the anonymous function inside the parentheses will be executed.


event.preventDefault();

This line of code prevents the default behavior of the form when it is submitted. By default, the form would submit the data to a server and reload the page. This code prevents that behavior so that we can use AJAX to check if the email is already in use without reloading the page.


const email = document.querySelector('#email-input').value;

This line of code selects the HTML input element with an id of email-input, gets its value (the email entered by the user), and stores it in the email variable.


if(email != '')

This line of code checks if the email variable is not an empty string.


const xhr = new XMLHttpRequest();

This line of code creates a new instance of the XMLHttpRequest object, which allows us to make HTTP requests from the browser.


xhr.open('POST', 'http://localhost:3000/check-email', true);

This line of code initializes the AJAX request. We are sending a POST request to the URL http://localhost:3000/check-email, which is the endpoint that will check if the email is already in use. The true parameter specifies that the request should be asynchronous.


xhr.setRequestHeader('Content-Type', 'application/json');

This line of code sets the Content-Type header of the request to application/json, which tells the server that we are sending JSON data in the request body.


xhr.onload = () => {

This line of code sets the onload event handler for the AJAX request. When the request is complete and a response has been received, the anonymous function inside the parentheses will be executed.


if (xhr.status === 200) {

This line of code checks if the response status code is 200, which means that the request was successful.


const response = JSON.parse(xhr.responseText);

This line of code parses the response text from JSON format into a JavaScript object and stores it in the response variable.


if (response.emailExists) {

This line of code checks if the emailExists property of the response object is true, which means that the email is already in use.


xhr.send(JSON.stringify({ email }));

This lines of code will send send data to http://localhost:3000/check-email this url.

After this, we have to create app.js file and under this file, we have to write Node JS Code for check Email Already exists or not in MySQL database.

app.js (Server-side (Node.js with Express and MySQL)))

const express = require('express');

const mysql = require('mysql');

const cors = require('cors');

const app = express();

const port = 3000;

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error)
	{
		console.log('Error connecting to MySQL database:', error);
		return;
	}
	console.log('Connected to MySQL database');
});

app.use(cors());

app.use(express.json());

app.post('/check-email', (request, response) => {

	const email = request.body.email;

	const sql = 'SELECT COUNT(*) AS count FROM users WHERE email = ?';

	connection.query(sql, [email], (error, results) => {

		const count = results[0].count;

		const emailExists = count === 1;

		response.json({ emailExists });

	});
});

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


In this code, we create an Express app, set up a connection to a MySQL database, and define a route to check the email availability. The route expects a POST request with a JSON payload containing an email property. We use the mysql library to query the database and check if the email already exists in the users table. We then send a JSON response with a emailExists property that indicates whether the email is already in use or not.

Now for run above application, first we have to run app.js file. So we have goes to command prompt and run following command.


node app.js

This command will start Node.js server and for check output in the browser, we have to open index.html file in the browser.


file:///F:/node/email_exist_or_not/index.html

So now you can check email address has been exists or not in MySQL database by entering email address in textbox by using Node.js with MySQL database.

Conclusion


In this blog, we explored how to use Node.js and MySQL to check if an email address already exists in a database. We discussed the steps involved in setting up a MySQL database, installing the mysql module for Node.js, connecting to the MySQL database, and checking if an email address exists in the database. With these tools and techniques, you can implement a robust user authentication system that ensures each user has a unique email address.

COMMENTS

Nama

Add,1,Ajax,2,ajax tutorial,1,Ajax with javascript,1,Ajax with node.js,1,application,2,array,1,array to string,1,array to string conversion nodejs,1,array to string in node js,1,array to string nodejs,1,Asynchronous JavaScript,1,authentication,1,authentication node js,1,authorization,1,availability,1,backend,1,bootstrap offcanvas dynamic content,1,bootstrap offcanvas dynamic content node.js,1,bootstrap offcanvas dynamic data,1,bootstrap offcanvas remote dynamic content,1,cart,1,centos 7,1,centos7,1,check,1,contact form node js,1,contact form nodemailer,1,contact us form node,1,conversion,1,create,1,crud,4,crud application,1,crud operation in node js,1,crud operation in node js with mysql,1,CSS,1,data,1,database,1,databases,1,datatables,1,DataTables integration in React.js,1,date range,1,delete,2,download,1,drag &amp; drop,1,drag and drop,1,drag and drop files,1,drag and drop multiple file,1,drag n drop,1,dynamic dropdown in react js,1,dynamic dropdown in react.js,1,ecommerce,2,edit,1,educational project,1,email address,1,email verification,1,email verification using jwt,1,express,3,expressjs,1,fetch,1,file upload,1,file upload in node js,1,files,1,filter,1,Front-end development tutorial,1,Frontend,1,GET,1,how to send email using node js,1,how to send emails in node js,1,html,1,html 2 pdf,1,html to pdf,1,html to pdf node,1,insert,2,insert data in mysql node js,1,Javascript,3,JavaScript tutorial,1,join array nodejs,1,js,1,json,1,jwt,3,jwt authentication,2,jwt authentication node js,1,jwt authentication php,1,jwt email verification,1,jwt login,1,jwt login php,1,jwt php example,1,jwt token,1,jwt token email verification,1,laravel 10,1,laravel 10 tutorial,1,laravel datatables,1,laravel datatables date range filter,1,laravel date filter,1,laravel date range filter,1,last insert id in node,1,learn reactjs,1,linux,1,live,2,live check email address availability,1,live search,1,load more data on click,1,load more data on click javascript,1,load more javscript node.js,1,load more nodejs,1,load more results,1,load more results with node js and ajax,1,login,1,merge 2 arrays in node js,1,merge array in nodejs,1,merge array node,1,merge two array in node js,1,MongoDB,1,mongodb crud,1,mongodb crud operations,1,multer,1,multiple file upload,1,mysql,7,mysql 8,1,mysql tutorial,1,mysql8,1,node,3,node js,8,node js array merge,1,node js array to string,1,node js crud,2,node js crud mysql,1,node js crud operation with mysql,1,node js load more pagination,1,node js mongodb crud,1,node js mysql last insert id,1,node js tutorial,2,node mongodb crud,1,node mysql get last insert id,1,node pdf,1,node.js,8,node.js array,1,node.js crud,1,node.js mysql,1,node.js tutorial,2,nodejs,9,nodejs array,1,nodejs array merge,1,nodejs create pdf,1,nodejs crud,1,nodejs pdf,1,nodejs pdf create,1,nodejs programming,1,offcanvas,1,open source,1,Optimizing web application performance,1,parking management system,1,parking management system in php,1,parking management system project,1,password,1,pdf-creator-node,1,php,3,php jwt authentication example,1,php jwt login,1,php login jwt,1,php parking management system,1,php project,1,PHP server-side processing,1,populate dropdown from database,1,programming tutorial,1,project,1,Puppeteer,1,Puppeteer HTML to PDF,1,React,1,react file upload,1,react js,2,react js dynamic dropdown,1,react js file upload validation,1,react js tutorial,1,react php myql,1,React.js,1,react.js dependent select,1,react.js file upload,1,Reactjs,4,reactJS CRUD,1,reactjs file upload,1,reactjs file upload app,1,reactjs file upload sample code,1,reactjs tutorial,1,read,1,register,1,registration,2,remove,1,request form node,1,reset,1,search,1,select,1,send activation email php,1,sending email using node js,1,server,1,Server-side data processing,1,shopping cart,1,shopping cart in node js,1,shopping cart javascript,1,shopping cart project in javascript,1,shopping cart using node js,1,shopping-cart,1,society management system in php,1,society management system php,1,society management system php source code,1,society management system project in php,1,society management system project php,1,source code,1,string,1,token,2,tutorial,8,update,2,using jwt for email verification,1,vanilla,1,vite,1,vitejs,1,vitejs crud app,1,web development,7,Web development guide,1,webslesson,2,what is jwt authentication,1,
ltr
item
kumpulan driver: How to check if an email address already exists with Node.js & MySQL
How to check if an email address already exists with Node.js & MySQL
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSxrobVVPBnpstJ_-3rbQ6u8LQTXIOjU9nY4b7KdcWlcc_MiIB3EYsV71yTZE0Ma2dxTCgojHqlNIlo715ToMWQBqprZAXQPdZSXwnXjZrx8bc7ltEJIedhcdGiJ8Mt_Gz799TXmEp1G1QAhl_KaS7Y7BMk15Zc_gpXXtGy_3grtSkXSucME5yzyzFNA/s16000/how-to-check-email-already-exists-in-mysql-using-nodejs-blog.jpg
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSxrobVVPBnpstJ_-3rbQ6u8LQTXIOjU9nY4b7KdcWlcc_MiIB3EYsV71yTZE0Ma2dxTCgojHqlNIlo715ToMWQBqprZAXQPdZSXwnXjZrx8bc7ltEJIedhcdGiJ8Mt_Gz799TXmEp1G1QAhl_KaS7Y7BMk15Zc_gpXXtGy_3grtSkXSucME5yzyzFNA/s72-c/how-to-check-email-already-exists-in-mysql-using-nodejs-blog.jpg
kumpulan driver
https://kepsuk.blogspot.com/2023/03/how-to-check-if-email-address-already_12.html
https://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/2023/03/how-to-check-if-email-address-already_12.html
true
6399859916032798219
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content