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)](https://cdn.hashnode.com/res/hashnode/image/upload/v1675695756473/72a261c0-dc78-4401-8e38-9ffa0896e06a.jpeg align="center")
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675695958855/90fe95dd-23d4-40bc-baa1-c04f80def0aa.jpeg align="center")
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.
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675696010655/ba3955cd-a6a1-4904-a3df-db10775835c8.jpeg align="center")
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.
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675696064830/79dd809a-d5b3-428f-aa15-6b6d29cfe765.jpeg align="center")
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.
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675696161135/0edf7be4-c8b1-4aa0-ba29-b9d0b261d4bb.jpeg align="center")
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675696179860/867a8360-3ba5-4224-8559-0c0c5f8a3c14.jpeg align="center")
I hope this article helped you in case you had any doubts.
Happy hacking!