Hash Passwords Before Storing Them

Passwords must never be stored as plain text.

If a database is compromised, plain-text passwords expose user accounts immediately.

Password hashing transforms a password into a one-way hash.

We will use bcryptjs to hash passwords before saving users.

bcrypt uses a configurable work factor to make password guessing more expensive.

For this tutorial, we will use a cost factor of 12.

The password should be hashed inside the registration service, not in the controller.

Never Store Plain-Text Passwords

Only store password hashes. Never log passwords, include them in API responses, or send them to analytics systems.

Hash a Password
import bcrypt from 'bcryptjs';

const password = 'SecurePassword123!';

const passwordHash = await bcrypt.hash(password, 12);

console.log(passwordHash);

Generates a bcrypt password hash using a cost factor of 12. The same plaintext password produces different hashes because bcrypt uses a salt.

Key Takeaways
  • Hash passwords before database storage.

  • bcrypt includes a salt in the hashing process.

  • Password hashes should never be returned to clients.