← Back to all snippets
JAVASCRIPT

Securely Hash Passwords with Bcrypt in Node.js

Learn to securely hash user passwords using the Bcrypt algorithm in Node.js, protecting against brute-force attacks and rainbow tables effectively.

const bcrypt = require('bcrypt');

const saltRounds = 10; // Recommended minimum for production

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

async function comparePassword(password, hashedPassword) {
  try {
    const match = await bcrypt.compare(password, hashedPassword);
    return match;
  } catch (error) {
    console.error('Error comparing password:', error);
    throw error;
  }
}

// Example Usage (for demonstration)
(async () => {
  const userPassword = 'mySecretPassword123!';
  const hashed = await hashPassword(userPassword);
  console.log('Hashed Password:', hashed);

  const isMatch = await comparePassword(userPassword, hashed);
  console.log('Password Match:', isMatch); // Should be true

  const wrongPasswordMatch = await comparePassword('wrongPassword', hashed);
  console.log('Wrong Password Match:', wrongPasswordMatch); // Should be false
})();
How it works: This snippet demonstrates how to use the `bcrypt` library in Node.js to securely hash and verify user passwords. Bcrypt is a computationally intensive hashing algorithm that incorporates a salt automatically, making it highly resistant to brute-force and rainbow table attacks. The `saltRounds` parameter determines the complexity of the hash, with higher values providing greater security at the cost of increased 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