DevAcademy
LearnNode.jsPassword Hashing
AdvancedNode.js

Password Hashing

Never store plain-text passwords — hash them properly with bcrypt.

Reading Time

12 min

Lesson

Lesson 31 of 34

Why Hash Passwords?

If a database is ever breached, plain-text passwords hand attackers immediate access to every account — and since people reuse passwords, often accounts on other sites too. Hashing stores an irreversible transformation of the password instead of the password itself.

Hashing on Signup

npm install bcrypt

Hashing and Comparing Passwords

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Using It in a Signup Route

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Why bcrypt (Not MD5 or SHA-256)

General-purpose hash functions like MD5 or SHA-256 are designed to be fast — exactly the wrong property for passwords, since it lets attackers try billions of guesses per second. bcrypt is deliberately slow and includes a "salt" automatically, making brute-force attacks impractical.

What a Salt Does

A salt is random data mixed into the password before hashing, unique per user. It ensures two users with the same password get completely different hashes, and prevents attackers from using precomputed "rainbow table" lookups.

Never Log or Return a Password (Hashed or Not)

Even a hashed password should never appear in API responses or application logs — exclude the passwordHash field explicitly whenever a user document is serialized, similar to the projection technique covered in the MongoDB course.

Best Practice

Always use a well-vetted library like bcrypt (or argon2) for password hashing — never invent your own hashing scheme, and never use a fast general-purpose hash function for passwords.

Interview Questions

Quick Quiz

1. Why is a fast hash function like plain SHA-256 a poor choice for passwords?

2. What does a salt do?

3. Should a hashed password ever be included in an API response?