Right now, DevTinder stores passwords exactly as users type them. Anyone who sees the database (a curious employee, a leaked backup, a hacker) sees every password, and people reuse passwords across sites. In this chapter you'll fix that with password hashing, then build a login API that checks passwords safely.
In this chapter you'll learn
- why passwords must be hashed, not encrypted (and the difference)
- how bcrypt works: salt, cost factor, and the hash string format
- a
validateSignupDatahelper that checks input before anything else happens - a complete signup with hashing, and a login that compares hashes
- safe login error messages
Before you start: read Chapter S2 08: Data Sanitization & Schema Validations (validation). The course calls this "encrypting passwords"; you'll see why "hashing" is the correct word.
Hashing vs encryption
These two are often mixed up, and the difference matters a lot:
| Encryption | Hashing | |
|---|---|---|
| Direction | two-way: encrypt, then decrypt with a key | one-way: there is no "un-hash" |
| Output | can be turned back into the original | can't be turned back |
| If the database leaks | an attacker who also gets the key can read every password | the attacker has to guess each password, one by one |
| Used for | data you need back: messages, files, card numbers | checking something without storing it: passwords |
A hash function turns any input into a fixed-looking string. The same input always gives the same output, but you can't go backwards:
"Akshay@123" ──hash──▶ "$2b$10$6QPtCraexGD/39D6NMVkj.1RPfoW...""Akshay@123" ──hash──▶ "$2b$10$6QPtCraexGD/39D6NMVkj.1RPfoW..."So how does login work if you can't get the password back? You hash what the user types at login and compare it with the stored hash. If they match, the password was right.
Passwords should always be hashed, never encrypted. The course and many tutorials say "encrypting passwords"; the code really does hashing, which is correct. Only the word is wrong.
Why ordinary hash functions aren't enough
Functions like MD5 or SHA-256 are designed to be fast. That's great for checking file downloads, and terrible for passwords: a modern graphics card can compute billions of SHA-256 hashes per second, so an attacker with your leaked database can try every common password in minutes.
Two more problems with plain hashing:
- Same password, same hash. If 500 users have the password
"123456", they all have the same hash: crack one, crack all. - Rainbow tables: huge precomputed lists of "password → hash" for common passwords.
Password-hashing algorithms like bcrypt (and argon2, scrypt) fix all of this.
How bcrypt works
1. A random salt
A salt is a random value generated for each password and mixed in before hashing. Because every user gets a different salt, the same password gives a different hash every time:
await bcrypt.hash("Akshay@123", 10); // $2b$10$6QPtCraexGD/39D6NMVkj.1RPfoW...
await bcrypt.hash("Akshay@123", 10); // $2b$10$f.ioGS.DoLfw0gB1W7RvnOnxQYd... (different!)await bcrypt.hash("Akshay@123", 10); // $2b$10$6QPtCraexGD/39D6NMVkj.1RPfoW...
await bcrypt.hash("Akshay@123", 10); // $2b$10$f.ioGS.DoLfw0gB1W7RvnOnxQYd... (different!)This defeats rainbow tables, and a cracked password reveals nothing about other users with the same password.
2. A cost factor (deliberately slow)
The second argument (10) is the cost factor, often called "salt rounds". bcrypt repeats its work 2^cost times: cost 10 means 2¹⁰ = 1,024 rounds. Each +1 doubles the time.
We measured it with bcryptjs:
| Cost | Time per hash (measured) |
|---|---|
| 10 | ~56 ms |
| 12 | ~255 ms (about 4× slower, as expected) |
56 ms is unnoticeable for one login, but it means an attacker can try only around 20 guesses per second per CPU core, instead of billions. The slowness is the security. As computers get faster, you raise the cost. A value of 10–12 is the common choice today.
3. Everything lives in one string
The salt and the cost are stored inside the hash, so you never store them separately:
$2b$10$6QPtCraexGD/39D6NMVkj.1RPfoWSmF4T1mfKFPx5rUnQwWoIfIN2$2b$10$6QPtCraexGD/39D6NMVkj.1RPfoWSmF4T1mfKFPx5rUnQwWoIfIN2$2b$: the bcrypt version10$: the cost factor- the next 22 characters: the salt
- the last 31 characters: the actual hash
The whole string is 60 characters. When you call bcrypt.compare, bcrypt reads the salt and cost from this string, hashes the typed password the same way, and compares the results.
bcrypt vs bcryptjs
bcryptjsis written in pure JavaScript: no compilation step, so it installs everywhere. The course uses it.bcryptuses native C++ code: noticeably faster, so you can afford a higher cost.
They produce compatible hashes, so you can switch later. Note that native bcrypt's async functions run on libuv's thread pool (Chapter 10: Thread Pool in libuv), like crypto.pbkdf2.
npm install bcryptjsnpm install bcryptjsStep 1: Validate signup data first
Put the checks in a small helper, so the route stays readable:
// src/utils/validation.js
const validator = require("validator");
const validateSignupData = (req) => {
const { firstName, lastName, emailId, password } = req.body;
if (!firstName || !lastName) {
throw new Error("Name is not valid");
} else if (!validator.isEmail(emailId)) {
throw new Error("Email is not valid");
} else if (!validator.isStrongPassword(password)) {
throw new Error("Please enter a strong password");
}
};
module.exports = { validateSignupData };// src/utils/validation.js
const validator = require("validator");
const validateSignupData = (req) => {
const { firstName, lastName, emailId, password } = req.body;
if (!firstName || !lastName) {
throw new Error("Name is not valid");
} else if (!validator.isEmail(emailId)) {
throw new Error("Email is not valid");
} else if (!validator.isStrongPassword(password)) {
throw new Error("Please enter a strong password");
}
};
module.exports = { validateSignupData };validator.isEmail and isStrongPassword are covered in Chapter S2 08: Data Sanitization & Schema Validations. These functions also reject non-string values (they throw a TypeError for objects), which blocks the injection trick from Chapter S2 07: Diving into APIs.
Step 2: Signup with hashing
// src/app.js (later moved into routes/auth.js, see S2 11)
const bcrypt = require("bcryptjs");
const { validateSignupData } = require("./utils/validation");
app.post("/signup", async (req, res) => {
try {
// 1. validate the input
validateSignupData(req);
// 2. hash the password
const { firstName, lastName, emailId, password } = req.body;
const passwordHash = await bcrypt.hash(password, 10);
// 3. save the user with the HASH, never the plain password
const user = new User({
firstName,
lastName,
emailId,
password: passwordHash,
});
await user.save();
res.status(201).send("User added successfully");
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});// src/app.js (later moved into routes/auth.js, see S2 11)
const bcrypt = require("bcryptjs");
const { validateSignupData } = require("./utils/validation");
app.post("/signup", async (req, res) => {
try {
// 1. validate the input
validateSignupData(req);
// 2. hash the password
const { firstName, lastName, emailId, password } = req.body;
const passwordHash = await bcrypt.hash(password, 10);
// 3. save the user with the HASH, never the plain password
const user = new User({
firstName,
lastName,
emailId,
password: passwordHash,
});
await user.save();
res.status(201).send("User added successfully");
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});Notice the order: validate → hash → save. Validation is cheap; hashing is deliberately slow. There's no point spending 60 ms hashing a password you're about to reject.
Open Compass after signing up: the password field now holds a $2b$10$... string.
Step 3: Login
app.post("/login", async (req, res) => {
try {
const { emailId, password } = req.body;
// 1. find the user by email
const user = await User.findOne({ emailId: emailId });
if (!user) {
throw new Error("Invalid credentials");
}
// 2. compare the typed password with the stored hash
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
throw new Error("Invalid credentials");
}
// 3. success (in S2 10 this is where the JWT cookie is created)
res.send("Login successful!");
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});app.post("/login", async (req, res) => {
try {
const { emailId, password } = req.body;
// 1. find the user by email
const user = await User.findOne({ emailId: emailId });
if (!user) {
throw new Error("Invalid credentials");
}
// 2. compare the typed password with the stored hash
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
throw new Error("Invalid credentials");
}
// 3. success (in S2 10 this is where the JWT cookie is created)
res.send("Login successful!");
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});bcrypt.compare(plainPassword, storedHash)returnstrueorfalse. It's case-sensitive:akshay@123doesn't matchAkshay@123.- Never compare with
===: because of the salt, hashing the typed password yourself would give a different string. - A wrong login is a client problem, so many APIs answer
401 Unauthorized(the course uses 400).
Use the same message for "no such email" and "wrong password". If the API says "Email not found" for one and "Wrong password" for the other, an attacker can use your login form to discover which emails are registered (this is called user enumeration). Always say "Invalid credentials".
What hashing does and doesn't protect
✅ A leaked database doesn't directly reveal passwords; each one must be cracked separately, slowly.
❌ Weak passwords like "password1" are still guessed quickly, because attackers try common passwords first. That's why isStrongPassword matters.
❌ Hashing doesn't protect passwords in transit. That's HTTPS's job (Chapter S3 03: Adding a custom Domain name).
❌ It doesn't stop someone trying passwords through your login form. That needs rate limiting (for example the express-rate-limit package).
Common mistakes
- Storing plain-text passwords "just for now".
- Using MD5/SHA-256 for passwords: far too fast.
- Comparing hashes with
===instead ofbcrypt.compare. - Forgetting
awaitonbcrypt.hashorbcrypt.compare: you get a Promise, which is always truthy, so every password "matches". - Different error messages for unknown email vs wrong password.
- Logging
req.bodyon signup or login: the plain password ends up in your logs.
Key takeaways
- Hash passwords (one-way); never encrypt them (two-way).
- bcrypt adds a random salt (same password → different hashes) and a cost factor (deliberately slow: 2^cost rounds).
- The 60-character hash string contains the version, cost, salt and hash, so you store just that one field.
- Signup: validate → hash → save. Login: find user →
bcrypt.compare→ respond. - Answer "Invalid credentials" for both unknown email and wrong password.
- Cost 10–12 is the usual choice; raise it as hardware gets faster.
Interview questions
Q1. What is the difference between hashing and encryption?
Encryption is reversible: data encrypted with a key can be decrypted with the (same or a paired) key. Hashing is one-way: you can't get the input back from the hash. Passwords are hashed, so even the server can't recover them; login works by hashing the attempt and comparing.
Q2. What is bcrypt, and why is it used for passwords?
bcrypt is a password-hashing algorithm. It automatically generates a random salt for each password, defeating rainbow tables and hiding identical passwords, and it has an adjustable cost factor that makes each hash deliberately slow (2^cost rounds), which makes brute-forcing leaked hashes expensive. The salt and cost are stored inside the hash string.
Q3. What is a salt?
A random value, unique per password, combined with the password before hashing. It makes identical passwords produce different hashes and makes precomputed lookup (rainbow) tables useless. The salt isn't secret; bcrypt stores it inside the hash.
Q4. What are salt rounds / the cost factor?
It's the work factor: bcrypt performs 2^cost iterations. Cost 10 = 1,024 rounds; each +1 doubles the time. Higher is slower for attackers and for your server, so choose the highest value that keeps login acceptably fast (commonly 10–12) and increase it over time.
Q5. How does bcrypt.compare work if the hash can't be reversed?
It extracts the salt and cost from the stored hash, hashes the plain-text password attempt with those same parameters, and checks whether the result equals the stored hash. Nothing is ever decrypted.
Q6. Why not use SHA-256 to hash passwords?
SHA-256 is designed to be fast: attackers can compute billions of hashes per second on GPUs. Without a per-user salt, identical passwords also share hashes. Password hashing needs a slow, salted algorithm with a tunable cost: bcrypt, scrypt or argon2.
Q7. What is user enumeration, and how do you prevent it on a login form?
User enumeration is learning which accounts exist from differences in the app's responses, like "email not found" vs "wrong password", or different response times. Prevent it by returning the same message and status ("Invalid credentials") in both cases, and by rate-limiting login attempts.
What's next
Login works, but the server forgets the user immediately; the next request has no idea who they are. In Chapter S2 10: Authentication, JWT & Cookies you'll fix that with JWT tokens stored in cookies, and protect routes with an auth middleware.