Bcrypt uses a salt and salt rounds to secure a password.

  • A salt is a value that is concatenated to a password before hashing in order to make it less vulnerable to rainbow table and brute-force attacks.
  • A salt round can be described as the amount of time needed to calculate a single bcrypt hash. The higher the salt rounds, the more time is necessary to crack a password.

In this asychronous implementation, we’ll generate a salt and hash in the same function call. This involves 3 steps:

  1. Generate a salt
  2. Hash the password
  3. Return null if there’s an error

We’ll make use of async/await and try/catch blocks to create an asynchronous function. We’ll pass in a password string and salt rounds:

const passwordHash = async (password, saltRounds) => { try { } catch (err) { } };

The built-in genSalt() function automatically generates a salt for us. Since we’re using an asynchronous function we can await this function call:

const salt = await bcrypt.genSalt(saltRounds);

Once we have a salt generated, we make a call to bcrypt.hash(). bcrypt.hash() takes in a password string and a salt. We await and return this function call since it will return the hashed password. Now, our try block looks like:

try { // Generate salt: const salt = await bcrypt.genSalt(saltRounds); // Hash password using generated salt: return await bcrypt.hash(password, salt); }

We also want to handle potential errors. In the catch block, we can print out the error with console.log(). Lastly, we return null if there’s an error with bcrypt and we’re unable to hash a password. The final code might look like:

const passwordHash = async (password, saltRounds) => { try { const salt = await bcrypt.genSalt(saltRounds); return await bcrypt.hash(password, salt); } catch (err) { console.log(err); } return null; };



Create an asynchronous function with password and saltRounds for its parameters and store it in a const variable called passwordHash.

Include a try/catch block, using err as the parameter for the catch block.


Use bcrypt‘s built-in function to generate a salt and store it in a const variable called salt.


Use bcrypt‘s built-in function to hash the plaintext password and store it in a const variable called hash.

Return the variable on the following line.


Print out an error if the code is unable to hash a password and return null outside of the try/catch block.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?