0
0
Node.jsframework~5 mins

Password hashing with bcrypt in Node.js

Choose your learning style9 modes available
Introduction

Password hashing keeps user passwords safe by turning them into secret codes that are hard to guess or reverse.

When storing user passwords in a database to protect them from theft.
When verifying a user's login password without saving the actual password.
When you want to add security to your app by making passwords unreadable.
When you need to compare a typed password with a stored hashed password.
When building any system that requires user authentication.
Syntax
Node.js
import bcrypt from 'bcrypt';

// To hash a password
const hashedPassword = await bcrypt.hash(password, saltRounds);

// To check a password
const isMatch = await bcrypt.compare(plainPassword, hashedPassword);

saltRounds controls how strong the hashing is; higher means safer but slower.

Always use await or handle promises because bcrypt functions are asynchronous.

Examples
This example hashes a password and prints the hashed result.
Node.js
const bcrypt = require('bcrypt');

const password = 'mySecret123';
const saltRounds = 10;

bcrypt.hash(password, saltRounds).then(hash => {
  console.log('Hashed password:', hash);
});
This example checks if the plain password matches the stored hashed password.
Node.js
const bcrypt = require('bcrypt');

const plainPassword = 'mySecret123';
const hashedPassword = '$2b$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36v1bq6j6q6q6q6q6q6q6q6';

bcrypt.compare(plainPassword, hashedPassword).then(result => {
  console.log('Password match:', result);
});
Sample Program

This program hashes a password, then checks if the correct and wrong passwords match the hash, printing the results.

Node.js
import bcrypt from 'bcrypt';

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

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

  // Verify the password
  const isValid = await bcrypt.compare('helloWorld!', hashed);
  console.log('Password is valid:', isValid);

  const isInvalid = await bcrypt.compare('wrongPassword', hashed);
  console.log('Wrong password is valid:', isInvalid);
}

run();
OutputSuccess
Important Notes

Never store plain passwords, always store hashed versions.

Use a saltRounds value of at least 10 for good security.

Hashing is one-way: you cannot get the original password back from the hash.

Summary

Password hashing protects user data by turning passwords into secret codes.

Use bcrypt's hash to create a hashed password and compare to check passwords.

Always handle bcrypt functions asynchronously with await or promises.