Password Hashing with bcrypt
Passwords must NEVER be stored in plaintext or with reversible encryption. bcrypt is the industry standard for password hashing: it's computationally expensive (slow by design to resist brute force), incorporates a random salt (prevents rainbow table attacks), and includes the salt in the output hash.
bcrypt Best Practices
import bcrypt from 'bcrypt';
// npm install bcrypt
// npm install -D @types/bcrypt
// ━━ Cost factor (work factor) ━━
// Each +1 doubles the computation time
// Cost 10: ~65ms — minimum for production
// Cost 12: ~250ms — recommended (2024)
// Cost 14: ~1s — for high-security apps (banking)
const BCRYPT_ROUNDS = 12;
// ━━ Hash password ━━
async function hashPassword(plaintext: string): Promise<string> {
// bcrypt.hash auto-generates a random salt and includes it in the output
return bcrypt.hash(plaintext, BCRYPT_ROUNDS);
// Output: "$2b$12$SomeSaltHereSomeHashHere..." (60 chars)
}
// ━━ Verify password ━━
async function verifyPassword(plaintext: string, hash: string): Promise<boolean> {
// Extracts the salt from the hash, re-computes, and compares
return bcrypt.compare(plaintext, hash); // returns true/false
// Uses timing-safe comparison internally — no timing attacks
}
// ━━ Usage in auth service ━━
const hashed = await hashPassword('MyPassword123!');
const isValid = await verifyPassword('MyPassword123!', hashed); // true
const isWrong = await verifyPassword('wrong', hashed); // false
// ━━ Common mistakes ━━
// ❌ hashSync() in request handlers — blocks the event loop for 250ms
// bcrypt.hashSync('password', 12); — NEVER in production request handlers
// ❌ Cost factor too low (< 10) — trivially brute-forced
// bcrypt.hash(pw, 6); // 6 is too fast
// ❌ Re-hashing already-hashed passwords
// Always check if value is already a hash before rehashingTip
Tip
Practice Password Hashing with bcrypt in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Technical diagram.
Practice Task
Note
Practice Task — (1) Write a working example of Password Hashing with bcrypt from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Password Hashing with bcrypt is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready node code.