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?
Bcrypt is a password hashing 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.
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.
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.
I hope this article helped you in case you had any doubts.
Happy hacking!