← Back to all snippets
JAVASCRIPT

Secure Password Hashing with bcrypt in Node.js

Learn how to securely hash user passwords using the bcrypt library in Node.js, ensuring robust protection against brute-force attacks and rainbow tables.

const bcrypt = require('bcrypt');
const saltRounds = 10; // Recommended value

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:
// (async () => {
//     const myPassword = 'mySecretPassword123';
//     const hash = await hashPassword(myPassword);
//     console.log('Hashed Password:', hash);

//     const isMatch = await comparePassword('mySecretPassword123', hash);
//     console.log('Password Match:', isMatch); // true

//     const isMismatch = await comparePassword('wrongPassword', hash);
//     console.log('Password Mismatch:', isMismatch); // false
// })();
How it works: This snippet demonstrates secure password hashing using the `bcrypt` library in Node.js. `bcrypt.hash()` takes a plain-text password and a salt round count (cost factor) to generate a strong, one-way hash. The `saltRounds` parameter determines the computational cost, making brute-force attacks more difficult. `bcrypt.compare()` safely checks if a provided plain-text password matches a stored hash without exposing the original password.

Need help integrating this into your project?

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

Hire DigitalCodeLabs