node.jsauthenticationbcrypt

BCrypt error Illegal arguments: string, object


I am developing a NodeJS and ReactJS based web application in which I am trying to hash the passwords in multiple routes, one for registration and other for changing password.

For this purpose, I am generating the salt outside both routes so they both utilize the same salt like this:

const salt = bcrypt.genSalt(10);

Now inside the routes, the has is being generated like this:

user.password = await bcrypt.hash(newPassword, salt);

But when I run this, it gives the following console error:

Illegal arguments: string, object

The hashing operation was working fine when I was generating the salt inside the individual routes. What could be the reason?


Solution

  • In case anyone else runs into this.

    Don't forget to await the genSalt function like so:

    const salt = await bcrypt.genSalt(10);
    

    The error: Illegal arguments: string, object tries to explain that one of the arguments passed to the hash function is invalid, since it's type is invalid.

    In this case it's the second argument (salt) which expects a string/number but receives an object (the promise object that's returned if you don't await).

    Hope that helps 🙂