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.
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.
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. |
4. Install bcrypt in Node.js
We will use the bcrypt package to hash and verify
passwords in our Node.js application.
npm install bcrypt
Import the package into your JavaScript file.
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.
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.
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.
MyPassword123!
Generates a salt and computes the 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.
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.
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.
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.
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 submits a password
Generate the password hash
Store the password hash
Retrieve the stored hash
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.