A Login form is used on the front end of a website, web app, or mobile app to collect information needed to verify whether a user has been registered in a system’s database.
The authentication process is simple. First, the user submits some credentials — typically an email and password — to the backend through a login form. Then, the backend application checks if the email and password are in the database. From there, the backend app will either grant users access or require them to register.
In this tutorial, we’ll learn how to build a simple login form with Node.js. The form will require a user to register an account. Then, we’ll use the entered information and store it in a Mysql database before signing the user in.
Now that we have an overview of the project, let’s start building!
Prerequisites
You’ll need Node.js and npm installed on your local development machine to follow this tutorial. If you’re not sure if you have them installed, run the following commands to check their availability:
# To check if Node is installed, run:
node -v
# To check if Node is installed, run:
npm -v
Besides Node.js, you’ll need a MySQL server installed and running. You can use the standalone MySQL installer or server distributions with MySQL built-in, such as WAMP and XAMP.
Building a Node.js login form
Let’s create a new folder for the app and navigate to the folder using the command line with the cd
directive:
cd path/to/your/folder
Then, run the following command to install the dependencies required for this tutorial:
npm i express mysql dotenv hbs bcryptjs
Let me explain what each library is for:
- Express: for creating API and web routes and setting up the app backend
- MySQL: for connecting to our local MySQL server
- dotenv: for storing environmental variables that should not be exposed in the app source code
- hbs: for rendering HTML on the server
- Bcryptjs: for hashing passwords
In addition, I recommend installing nodemon, which automatically restarts the server when file changes are detected, saving you precious time in development. Install it with the following command:
npm i nodemon --save
Finally, open your app’s package.json
file with a code editor and add the following field inside the scripts
object:
"start": "nodemon app.js"
Now, we’re finished with the project setup. Next, we’ll connect to our MySQL database and create a table to store user login information.
Setting up a database connection in Node.js
Start by creating a new database in your MySQL environment named login-db
. After that, build a users
table with the ID, name, email, and password. Set the ID to INT
and AUTOINCREMENT
, and the name, email, and password to VARCHAR
.
In the end, the database in phpMyAdmin
will look like this:
Then, create an .env
file in your app’s root folder. Inside .env
, add your database name, host domain, username, and password values to their corresponding variable names. These are the default values for MySQL:
DATABASE = login-db
DATABASE_HOST = localhost
DATABASE_ROOT = root
DATABASE_PASSWORD =
Once you’ve set the variables, create app.js
in the root folder. Open it with your text editor and import the following dependencies:
const express = require('express');
const mysql = require("mysql")
const dotenv = require('dotenv')
Then, create an Express app:
const app = express();
After that, specify the path to the environmental variables:
dotenv.config({ path: './.env'})
Here, we’re telling the server to find .env
inside the same directory as app.js
.
Next, access the variables from process.env
and pass them to their respective connection properties:
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
})
Now that you have configured the connection with your database credentials, connect the database:
db.connect((error) => {
if(error) {
console.log(error)
} else {
console.log("MySQL connected!")
}
})
The connection will either succeed or fail. If it fails, we’ll see error
in the callback, and we’ll print it on the console. Otherwise, we output the "MySQL connected!"
string.
Finally, start the server by running the following command on your terminal:
npm start
If everything goes well, you’ll see MySQL is connected
. Let’s create the homepage.
Setting up the homepage
Inside your project’s root folder, create the views
folder. Then, in views
, create index.hbs
, register.hbs
, and login.hbs
. As you may have guessed, these are the Handlebars files for the home, login, and register pages.
Now, for each of them, include the base HTML markup:
html lang="en">
head>
link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
head>
head>
body>
{{!-- Navigation links --}}
nav>
h4>Node MySQL Loginh4>
ul>
li>a href="/">Homea>li>
li>a href="/login">Logina>li>
li>a href="/register">Registera>li>
ul>
nav>
{{!-- Body of each page will go here --}}
body>
html>
Here, we linked the two elements to our custom
style sheet
and the Bootstrap CSS library. We also created a navigation menu that will be reused across all pages to include links to the login and register pages.
Next, inside index.hbs
, use the following markup within the tags to add a jumbotron to your website’s homepage:
{{!-- Body --}}
div class="container mt-4">
div class="mt-4 p-5 bg-primary text-white rounded">
h1>My Login Projecth1>
p>This project demonstrates how to implement login and register functionalities with Node.js and MySQL p>
div>