Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

User Registration in Node.js

Learn how to register new users, validate their information, hash passwords, and save user accounts in a MySQL database using Node.js and Express.js.

User registration allows new users to create accounts in an application. During registration, the server receives user information, validates the submitted data, hashes the password, and saves the account in the database.

In this tutorial, we will create a registration API using Express.js, bcrypt, and mysql2. We will also learn how to handle duplicate email addresses and return appropriate HTTP responses.

1. What Is User Registration?

User registration is the process through which a new user creates an account by providing information such as a name, email address, and password.

The server validates the submitted information and stores the user's account details in a database. The password should never be stored as plain text.

Example: A student visits a training institute website, enters their name, email address, and password, and clicks the Register button. The application validates the details and creates the student's account.

2. How User Registration Works

A typical registration workflow follows these steps:

1. User Submits Registration Form

Name, email, and password

↓
2. Express.js Server

Receives the request and validates the input

↓
3. Check Existing Account

Check whether the email is already registered

↓
4. Hash Password

Generate a secure password hash using bcrypt

↓
5. Save User

Insert the account into the database

↓
6. Send Response

Return a registration success message

3. Install Required Packages

Create a Node.js project if you do not already have one. Install Express.js, bcrypt, and mysql2.

Terminal
npm init -y
npm install express bcrypt mysql2 dotenv

These packages provide the following functionality:

Package Purpose
express Creates the API and handles HTTP requests.
bcrypt Hashes passwords and verifies submitted passwords.
mysql2 Connects Node.js to MySQL.
dotenv Loads configuration from environment variables.

4. Create the Users Table

Before registering users, create a database table to store their names, email addresses, and password hashes.

SQL
CREATE DATABASE auth_demo;

USE auth_demo;

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

The email column has a UNIQUE constraint. This prevents two accounts from being created with the same email address, even if two registration requests arrive at nearly the same time.

Important: The password_hash column stores the bcrypt hash, not the original password.

5. Configure the Database Connection

Create a file named db.js and configure a MySQL connection pool.

JavaScript
require("dotenv").config();

const mysql = require("mysql2/promise");

const pool = mysql.createPool({
    host: process.env.DB_HOST || "localhost",
    user: process.env.DB_USER || "root",
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME || "auth_demo",
    waitForConnections: true,
    connectionLimit: 10
});

module.exports = pool;

Create a .env file for local development:

Environment Variables
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=YOUR_MYSQL_PASSWORD
DB_NAME=auth_demo
PORT=3000

Replace the placeholder with your MySQL password. Keep the .env file out of source control and never commit actual credentials.

6. Create the User Registration API

Create a file named server.js. The following endpoint validates the submitted details, checks for an existing email, hashes the password, and inserts the new account.

JavaScript
require("dotenv").config();

const express = require("express");
const bcrypt = require("bcrypt");
const pool = require("./db");

const app = express();

app.use(express.json());

app.post("/api/auth/register", async (req, res) => {
    try {
        const { name, email, password } = req.body;

        if (
            typeof name !== "string" ||
            typeof email !== "string" ||
            typeof password !== "string"
        ) {
            return res.status(400).json({
                message: "Name, email, and password are required."
            });
        }

        const normalizedName = name.trim();
        const normalizedEmail = email.trim().toLowerCase();

        if (
            normalizedName.length < 2 ||
            normalizedName.length > 100
        ) {
            return res.status(400).json({
                message: "Name must contain between 2 and 100 characters."
            });
        }

        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (
            normalizedEmail.length > 255 ||
            !emailPattern.test(normalizedEmail)
        ) {
            return res.status(400).json({
                message: "Please provide a valid email address."
            });
        }

        if (
            password.length < 12 ||
            Buffer.byteLength(password, "utf8") > 72
        ) {
            return res.status(400).json({
                message:
                    "Password must be at least 12 characters and no more than 72 UTF-8 bytes."
            });
        }

        const [existingUsers] = await pool.execute(
            "SELECT id FROM users WHERE email = ?",
            [normalizedEmail]
        );

        if (existingUsers.length > 0) {
            return res.status(409).json({
                message: "An account with this email already exists."
            });
        }

        const passwordHash = await bcrypt.hash(password, 12);

        await pool.execute(
            `INSERT INTO users (name, email, password_hash)
             VALUES (?, ?, ?)`,
            [normalizedName, normalizedEmail, passwordHash]
        );

        return res.status(201).json({
            message: "User registered successfully."
        });
    } catch (error) {
        if (error.code === "ER_DUP_ENTRY") {
            return res.status(409).json({
                message: "An account with this email already exists."
            });
        }

        console.error("Registration failed:", error.message);

        return res.status(500).json({
            message: "Unable to register user."
        });
    }
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

The code checks for an existing email before inserting the account. The database's UNIQUE constraint provides the final protection against duplicate email addresses.

Why the password length limit? bcrypt has a 72-byte input limit. This example explicitly rejects longer UTF-8 passwords instead of silently accepting a truncated password. A production application should also use an appropriate password policy and test the chosen hashing configuration.

7. Test User Registration Using Postman

Start the server and send a POST request to the registration endpoint.

Terminal
node server.js

Request method: POST

URL
http://localhost:3000/api/auth/register

In Postman, select Body → raw → JSON and send the following data.

JSON
{
    "name": "Rahul Sharma",
    "email": "rahul@example.com",
    "password": "MyStrongPassword123!"
}

Successful response:

JSON
{
    "message": "User registered successfully."
}

The server returns HTTP status 201 Created when the user is successfully registered.

8. Handle Duplicate Email Addresses

If the user submits an email address that already exists, the API should not create a second account using that address.

For example, if rahul@example.com has already been registered, another registration request using the same email should receive a conflict response.

JSON
{
    "message": "An account with this email already exists."
}

The response uses HTTP status 409 Conflict. In some public-facing systems, a generic response may be preferable to avoid revealing whether a particular email address is registered.

9. Common Registration Errors

Status Code Meaning Example
201 Created User registered successfully.
400 Bad Request Missing or invalid input.
409 Conflict Email address already exists.
500 Internal Server Error Unexpected database or server error.

10. User Registration Flow

Registration Form

Collect name, email, and password

↓
Input Validation

Check required fields and input formats

↓
Email Check

Check existing accounts and enforce uniqueness

↓
Password Hashing

Generate a bcrypt password hash

↓
Database Insert

Save the new account with its password hash

↓
HTTP 201 Response

Confirm that registration succeeded

Important Points to Remember

  • User registration creates a new account.
  • Validate all user input on the server.
  • Normalize email addresses consistently.
  • Use a UNIQUE database constraint for email addresses.
  • Never store passwords as plain text.
  • Hash passwords using bcrypt or another suitable password-hashing algorithm.
  • Use parameterized SQL queries.
  • Return appropriate HTTP status codes.
  • Keep database credentials in environment variables.
  • Never return password hashes in API responses.

Summary

User registration allows new users to create accounts in an application. We created a registration API using Express.js, bcrypt, and MySQL, including input validation, duplicate email handling, password hashing, and database insertion.

In the next tutorial, we will learn how to authenticate registered users through a secure login process.