Using bcryptjs with Node.js

Shreyas chaliha
3 min readFeb 6, 2023

--

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.

Before using bcrypt. (It is a really bad way to store passwords unencrypted)
After using bcrypt. We can see the password has been hashed.

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
With a cost of 18, it took 18.13 seconds

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

Happy hacking!

--

--

Shreyas chaliha
0 Followers

I love to code, cook and read books from time to time.