← Back to all snippets
JAVASCRIPT

Secure Password Hashing with bcrypt.js

Learn to securely hash and verify user passwords in Node.js applications using the robust 'bcrypt.js' library to prevent credential theft and enhance security.

// Install: npm install bcryptjs
const bcrypt = require('bcryptjs');

const password = 'mySecretPassword123!';
const saltRounds = 10; // Recommended value, higher means slower, more secure

async function hashPassword(plainTextPassword) {
  try {
    const hashedPassword = await bcrypt.hash(plainTextPassword, saltRounds);
    console.log('Hashed Password:', hashedPassword);
    return hashedPassword;
  } catch (error) {
    console.error('Error hashing password:', error);
    throw error;
  }
}

async function verifyPassword(plainTextPassword, hashedPassword) {
  try {
    const isMatch = await bcrypt.compare(plainTextPassword, hashedPassword);
    console.log('Password Match:', isMatch);
    return isMatch;
  } catch (error) {
    console.error('Error verifying password:', error);
    throw error;
  }
}

// Usage example
(async () => {
  const hashedPassword = await hashPassword(password);
  await verifyPassword(password, hashedPassword);
  await verifyPassword('wrongPassword', hashedPassword);
})();
How it works: This snippet shows how to securely hash and verify passwords using the 'bcrypt.js' library in Node.js. Bcrypt is a widely recommended password hashing function because it's designed to be computationally intensive, making brute-force attacks difficult even with powerful hardware. It automatically handles salting (adding random data to the password before hashing) to prevent rainbow table attacks. The `saltRounds` parameter controls the work factor; a higher value increases security at the cost of more processing time.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs