Using bcryptjs with Node.js

Shreyas ChalihaShreyas Chaliha
2 min read

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!

0
Subscribe to my newsletter

Read articles from Shreyas Chaliha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shreyas Chaliha
Shreyas Chaliha

I am a full-stack developer with a passion for coding and a love of cooking, I'm always discovering the perfect recipe for success. With a keen eye for detail and a knack for problem-solving, I can create beautiful, fully functional web applications and when I'm not behind the computer, you can find me in the kitchen, working on my latest culinary creation I find the kitchen to be a great creative outlet that complements my work as a developer. In my free time, I also enjoy going for long walks, reading, swimming, or playing Tennis.