Using bcryptjs with Node.js

This article describes how we can use the bcryptjs library with node.js to hash a password. It is a way to implement security measures in Node.js

What is bcryptjs?
Bcryptjs is a password-hashing javascript library that uses a slow hash function for added security against brute-force attacks. Hashing is a more secure way to save passwords because it creates a distinctive representation of the original password that is difficult to reverse.

Before getting started let’s look at the difference between before and after using the library. In the first picture, it is the outcome before using bcrypt. (It is a really bad way to store passwords unencrypted). In the second picture, it is the outcome after using bcrypt. We can see the password has been hashed.

Outcome before using bcrypt. (It is a really bad way to store passwords unencrypted)

Now let’s get started,

To install we can use the following npm command on our terminal,
npm install bcryptjs

Once the package has been added, we can confirm by going to our package.json file and checking on the dependencies.

We are good to take the next step now. I will be using it in my userModel.js file where I have defined my user schema.

First, we got to import it. We import it by calling it our userModel.js file as
const bcrypt = require(‘bcryptjs’);

In our userSchema, we have the field for ‘password’ and ‘passwordConfirm’.

Now for the encryption, we will be using Mongoose middleware, pre-save middleware. We will use pre-save middleware because encryption will happen between when we receive the data and when it is persisted in the database. Our pre-save middleware is where we use bcryptjs to hash the password with a cost of 12.

We use a cost of 12, the higher the cost the more CPU intensive it is and also more time-consuming. Currently, it is suggested to use a number above 10.
Below is a comparison between the time to hash with a cost of 12 and 18. With a cost of 12, it took 525 ms while with a cost of 18, it took 18.13 seconds. Snaps from postman after making the call.

I hope this article helped you in case you had any doubts.

Happy hacking!