Building a Simple Login Form with Node.js

Getting Started

Before we begin, make sure you have Node.js and npm installed on your local development machine. If you’re not sure, run the following commands to check:

node -v
npm -v

You’ll also need a MySQL server installed and running. You can use a standalone MySQL installer or a server distribution with MySQL built-in, such as WAMP or XAMP.

Setting Up the Node.js Application

Create a new folder for your app and navigate to it in the command line using the cd directive. Then, run the following command to install the necessary dependencies:

npm install express mysql dotenv hbs bcryptjs

Here’s what each library is for:

  • Express.js: 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 shouldn’t be exposed in the app source code
  • HBS: For rendering HTML on the server
  • Bcryptjs: For hashing passwords

Connecting to the MySQL Database

Create a new database in your MySQL environment named login-db. Then, build a users table with the following columns:

  • id (INT, AUTOINCREMENT)
  • name (VARCHAR)
  • email (VARCHAR)
  • password (VARCHAR)

Create an .env file in your app’s root folder and add your database name, host domain, username, and password values to their corresponding variable names.

Creating the Login and Register Forms

Create a new file called index.hbs in the views folder and add the following markup:


<h1>Login</h1>
<form action="/login" method="post">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  <br>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password">
  <br>
  <input type="submit" value="Login">
</form>

Create a new file called register.hbs in the views folder and add the following markup:


<h1>Register</h1>
<form action="/register" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  <br>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password">
  <br>
  <label for="confirm_password">Confirm Password:</label>
  <input type="password" id="confirm_password" name="confirm_password">
  <br>
  <input type="submit" value="Register">
</form>

Registering the User

Create a new route for the register form and add the following code:


app.post('/register', (req, res) => {
  const { name, email, password, confirm_password } = req.body;
  // Check if the email is already in use
  db.query('SELECT * FROM users WHERE email = ?', [email], (err, results) => {
    if (err) {
      console.error(err);
      res.status(500).send({ message: 'Error registering user' });
    } else if (results.length > 0) {
      res.send({ message: 'Email already in use' });
    } else {
      // Hash the password and insert the user into the database
      const hashedPassword = bcrypt.hashSync(password, 10);
      db.query('INSERT INTO users SET ?', { name, email, password: hashedPassword }, (err, results) => {
        if (err) {
          console.error(err);
          res.status(500).send({ message: 'Error registering user' });
        } else {
          res.send({ message: 'User registered successfully' });
        }
      });
    }
  });
});

This code checks if the email is already in use, hashes the password, and inserts the user into the database.

Leave a Reply

Your email address will not be published. Required fields are marked *