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

Password Hashing in Node.js

Learn how to securely hash user passwords and verify them using bcrypt in Node.js applications.

Passwords are sensitive information. If an application stores passwords as plain text, anyone who gains access to the password database may be able to read them directly.

Password hashing helps protect stored passwords. Instead of saving the original password, an application stores a password hash and verifies submitted passwords against that hash during login.

1. What Is Password Hashing?

Password hashing converts a password into a fixed-format hash using a one-way password-hashing algorithm. The original password is not stored in the database.

During login, the application uses a password verification function to check whether the entered password matches the stored hash.

Example: If a user registers with the password MyPassword123!, the application stores its password hash instead of storing the original password.
Plain-Text Password Stored Password
MyPassword123! A bcrypt hash generated from that password

The hash is not the original password. During verification, bcrypt checks the submitted password against the stored hash.

2. Why Should We Hash Passwords?

Password hashing reduces the damage that can occur if a database containing password hashes is exposed.

  • Prevents passwords from being stored directly as plain text.
  • Makes recovering passwords from a database dump more difficult.
  • Uses computationally expensive hashing to slow down password guessing.
  • Allows applications to verify passwords without storing the original values.
Important: Hashing does not make password storage completely risk-free. Use a suitable password-hashing algorithm, strong user passwords, secure database access, and appropriate application security controls.

3. Hashing vs Encryption

Hashing and encryption are different concepts. Encryption is designed to be reversible using the appropriate key, while password hashing is designed to make recovering the original password computationally difficult.

Hashing Encryption
Designed as a one-way transformation. Designed to be reversible with the appropriate key.
Used for password verification. Used when data must be recovered later.
Password hashes are verified using a password-hashing function. Encrypted data is decrypted using the appropriate key.
Example: bcrypt or Argon2. Example: AES encryption for suitable application data.
Never encrypt passwords with the intention of decrypting them during login. Store password hashes and verify them instead.

4. Install bcrypt in Node.js

We will use the bcrypt package to hash and verify passwords in our Node.js application.

Terminal
npm install bcrypt

Import the package into your JavaScript file.

JavaScript
const bcrypt = require("bcrypt");

5. Hash a Password Using bcrypt

The bcrypt.hash() function generates a password hash. It accepts the original password and a cost factor.

JavaScript
const bcrypt = require("bcrypt");

async function hashPassword() {
    const password = "MyPassword123!";

    const saltRounds = 12;

    const hashedPassword = await bcrypt.hash(
        password,
        saltRounds
    );

    console.log("Original password:", password);
    console.log("Hashed password:", hashedPassword);
}

hashPassword().catch(console.error);

The saltRounds value controls bcrypt's computational cost. A higher value generally makes hashing slower. Choose a value based on security requirements and performance testing.

Security tip: Never print real users' passwords or password hashes in production logs. The console output above is only for learning purposes.

6. Understand Salt in Password Hashing

A salt is a random value used by the password-hashing algorithm. bcrypt automatically generates and incorporates a salt when you use bcrypt.hash().

As a result, hashing the same password multiple times can produce different hashes. This helps prevent attackers from identifying users who have the same password simply by comparing stored hashes.

User Password

MyPassword123!

↓
bcrypt Algorithm

Generates a salt and computes the hash

↓
Stored Password Hash

Save the hash, not the original password

The bcrypt hash contains the information required to verify the password, including its salt and cost parameters. You do not need to store a separate salt when using the standard bcrypt hash format.

7. Verify a Password Using bcrypt

When a user logs in, the application compares the submitted password with the stored hash using bcrypt.compare(). Do not hash the submitted password and compare the strings directly.

JavaScript
const bcrypt = require("bcrypt");

async function verifyPassword() {
    const password = "MyPassword123!";

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

    const isMatch = await bcrypt.compare(
        "MyPassword123!",
        storedHash
    );

    if (isMatch) {
        console.log("Password is correct");
    } else {
        console.log("Invalid password");
    }
}

verifyPassword().catch(console.error);

bcrypt.compare() returns true when the submitted password matches the stored hash, and false otherwise.

Remember: In a real application, retrieve the user's stored password hash from the database. Do not generate a new hash during login and compare it directly with the stored hash.

8. Save a Password Hash in a Database

After registration, save the generated password hash in the database. A users table might contain an ID, email address, and password hash.

SQL
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL
);

The password_hash column stores the bcrypt hash. The example below assumes a MySQL connection pool named pool is already configured using mysql2/promise.

JavaScript
const bcrypt = require("bcrypt");

async function createUser(email, password) {
    const passwordHash = await bcrypt.hash(password, 12);

    await pool.execute(
        "INSERT INTO users (email, password_hash) VALUES (?, ?)",
        [email, passwordHash]
    );

    return {
        message: "User registered successfully."
    };
}

The query uses placeholders for the email and password hash. In a complete registration endpoint, validate the email and password before creating the account and handle duplicate emails and database errors.

9. Password Hashing Flow

User Registration

User submits a password

↓
bcrypt.hash()

Generate the password hash

↓
Database

Store the password hash

↓
User Login

Retrieve the stored hash

↓
bcrypt.compare()

Verify the submitted password

10. Common Password Hashing Mistakes

Mistake Correct Approach
Storing passwords as plain text. Store password hashes.
Using ordinary fast hashes such as MD5 for passwords. Use a password-hashing algorithm such as bcrypt or Argon2.
Comparing two independently generated bcrypt hashes as strings. Use bcrypt.compare().
Logging passwords. Never log plaintext passwords.
Using an unsuitable cost factor. Choose a cost factor through security and performance testing.
Saving the original password alongside the hash. Store only the password hash.

Important Points to Remember

  • Password hashing is designed to be one-way.
  • Never store plaintext passwords in the database.
  • bcrypt is a password-hashing library for Node.js.
  • bcrypt.hash() generates a password hash.
  • bcrypt.compare() verifies a submitted password.
  • bcrypt automatically generates a salt when hashing a password.
  • Choose the cost factor based on security and performance requirements.
  • Use parameterized queries when storing hashes in MySQL.
  • Handle registration and login errors safely.

Summary

Password hashing protects stored passwords by replacing the original values with password hashes. We learned how to use bcrypt to hash passwords, understand salts, verify submitted passwords, and store hashes in a MySQL database.

In the next tutorial, we will use password hashing to build a user registration workflow in Node.js.