0
0
NodejsHow-ToBeginner · 3 min read

How to Hash Password in Node.js Securely with bcrypt

To hash a password in Node.js, use the bcrypt library which provides secure hashing with salt. You call bcrypt.hash(password, saltRounds) to generate a hashed password that you can safely store.
📐

Syntax

The main function to hash a password is bcrypt.hash(password, saltRounds).

  • password: The plain text password string you want to hash.
  • saltRounds: Number of times the hashing algorithm runs to increase security (usually 10 or more).
  • The function returns a Promise that resolves to the hashed password string.
javascript
import bcrypt from 'bcrypt';

const password = 'userPassword123';
const saltRounds = 10;

bcrypt.hash(password, saltRounds).then(hashedPassword => {
  console.log(hashedPassword);
});
Output
$2b$10$...hashedpasswordstring...
💻

Example

This example shows how to hash a password and then verify it by comparing with the original password.

javascript
import bcrypt from 'bcrypt';

async function run() {
  const password = 'mySecret123';
  const saltRounds = 12;

  // Hash the password
  const hashedPassword = await bcrypt.hash(password, saltRounds);
  console.log('Hashed password:', hashedPassword);

  // Verify password
  const isMatch = await bcrypt.compare(password, hashedPassword);
  console.log('Password match:', isMatch);
}

run();
Output
Hashed password: $2b$12$...hashedpasswordstring... Password match: true
⚠️

Common Pitfalls

  • Using a low saltRounds value reduces security; 10 or higher is recommended.
  • Never store plain text passwords; always store the hashed version.
  • Do not reuse the same salt manually; let bcrypt generate it automatically.
  • Always use asynchronous hash and compare methods to avoid blocking the event loop.
javascript
import bcrypt from 'bcrypt';

// Wrong: synchronous hashing blocks event loop
const hashedSync = bcrypt.hashSync('password', 10);
console.log('Sync hash:', hashedSync);

// Right: asynchronous hashing
bcrypt.hash('password', 10).then(hash => {
  console.log('Async hash:', hash);
});
Output
Sync hash: $2b$10$...hashedpasswordstring... Async hash: $2b$10$...hashedpasswordstring...
📊

Quick Reference

Remember these key points when hashing passwords in Node.js:

  • Use bcrypt for secure hashing.
  • Set saltRounds to 10 or more.
  • Always use async methods hash and compare.
  • Never store or log plain passwords.

Key Takeaways

Use bcrypt's async hash function with at least 10 salt rounds for secure password hashing.
Never store plain text passwords; always store the hashed result.
Use bcrypt.compare to verify passwords safely without exposing the original password.
Avoid synchronous bcrypt methods to keep Node.js responsive.
Let bcrypt generate salts automatically instead of creating your own.