Authentication & Security
Node.js Password Hashing with bcrypt
bcrypt hashes passwords with a built-in salt and a configurable cost factor that makes brute-force attacks expensive. It is deliberately slow, which is exactly the property a password hash needs.
What is Password Hashing with bcrypt in Node.js?
bcrypt hashes passwords with a built-in salt and a configurable cost factor that makes brute-force attacks expensive. It is deliberately slow, which is exactly the property a password hash needs.
Password Hashing with bcrypt example
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12;
// signup
const hash = await bcrypt.hash(plainPassword, SALT_ROUNDS);
await User.create({ email, password: hash });
// login
const user = await User.findOne({ email }).select('+password');
const ok = user && await bcrypt.compare(plainPassword, user.password);
if (!ok) {
return res.status(401).json({ error: 'Invalid email or password' });
}How this works
The same generic message is returned whether the email or the password was wrong — otherwise the endpoint tells an attacker which email addresses are registered.
Key points to remember
- 10 to 12 rounds is the current sensible range; higher is slower for you as well as attackers.
- bcrypt embeds the salt in the hash, so no separate salt column is needed.
- Exclude the password field by default in the schema with select: false.
- Never log or return the hash.
Common mistakes with Password Hashing with bcrypt
- Comparing hashes with === instead of bcrypt.compare.
- Telling the client whether the email exists, enabling account enumeration.
- Using SHA-256 for passwords because it is fast — that is precisely the problem.
Node.js Password Hashing with bcrypt— Interview Questions & FAQs
How many bcrypt salt rounds should I use?+
Ten to twelve for most applications. Each extra round doubles the time; aim for roughly 100–250 ms per hash on your production hardware.
