Node.js › Authentication & Authorization
How should passwords be securely stored in a Node.js application's database, and why is bcrypt commonly used?
BeginnerAnswer
Passwords should never be stored in plain text or with a fast, general-purpose hash like SHA-256 alone -- they should be hashed with a purpose-built, deliberately slow password-hashing algorithm like bcrypt (or argon2/scrypt), which incorporates a random per-password salt automatically and can be tuned to be computationally expensive enough to make brute-force and rainbow-table attacks impractical, even if the password database is ever leaked.
const bcrypt = require('bcrypt');
// Hashing during registration
const hashedPassword = await bcrypt.hash(plainTextPassword, 12); // 12 = cost factor
await User.create({ username, password: hashedPassword });
// Verifying during login
const isMatch = await bcrypt.compare(submittedPassword, user.password);Real-world example A company's user database is leaked in a breach, but because passwords were hashed with bcrypt at a cost factor of 12 rather than stored as plain SHA-256 hashes, attackers are unable to feasibly crack the vast majority of passwords even with significant computing resources, buying users critical time to change their passwords.