comparing two same string hashing in bcrypt returns undefined comparing two same string hashing in bcrypt returns undefined express express

comparing two same string hashing in bcrypt returns undefined


Because bcrypt.hash is the async function, when you compare it both bcrypt.hash may not finish yet, therefore it prints undefined for akbar and akbar2. You also cannot compare akbar and akbar2 since it will always return false. You should only compare either 'salam' with akbar or 'salam' with akbar2.

bcrypt.hash('salam', 10, (err, hash) => {    const akbar = hash;    bcrypt.compare('salam', akbar, (err, isMatch) => {        console.log(isMatch);    });});


hash and compare functions work asynchronously.

There are sync counterparts of hash and compare:

var bcrypt = require('bcrypt');const saltRounds = 10;const myPlaintextPassword = 's0/\/\P4$$w0rD';const someOtherPlaintextPassword = 'not_bacon';var salt = bcrypt.genSaltSync(saltRounds);var hash = bcrypt.hashSync(myPlaintextPassword, salt);bcrypt.compareSync(myPlaintextPassword, hash); // true

Async is always recommended.

Hope this helps