How to Node JS- Password Encryption using Bcrypt

In this guide, we are going to learn about Node JS password encryption with Bcrypt module. Bcrypt is a password hashing function or algorithm which secure user passwords on the database. Let’s get started with Bcrypt.

Install Bcrypt Module

To Install the Bcrypt module, open the Node Js terminal and execute the following npm command

Install Bcrypt
      npm install bcrypt


Hash the password

Once you finish the installation of Bcrypt module, you can start hash coding. You can hash the passwords using two different methods:

Sync Hashing method
Async Hashing method


Sync Hashing

To hash the password using Bcrypt module, create a salt using the hashSync method. The following code will create the password hash with the hashSync method.

Sync Hashing
 	// Load the bcrypt package module
	var bcrypt = require('bcrypt');
	// Generate a password salt
	var salt = bcrypt.genSaltSync(10);
	// Hash the password with salt
	var passwordHash = bcrypt.hashSync(passwordFromUser, salt)


To pull back a hashed password from the database and to authenticate a user, you have to use the hashSync again. Let’s use the following code to check the incoming password string against the hash.

Check the password with hash
	// pull user data from the database 
	connection.query("SELECT * FROM users WHERE username = [username]",
		function(err, rows) {
			if (err) {
				return done(err);
	                //to check the incoming password string against the hash
			if (bcrypt.hashSync(password_entered_by_user, salt) === rows[0].password) {
			  // hashing code worked


Async Hashing

The Bcrypt also support Asynchronous hashing method. The following code will generate password hash using Async hashing.

Async Hashing
	var bcrypt = require('bcrypt');
	bcrypt.genSalt(10, function(err, salt) {
                //Synchronous hashing method
		bcrypt.hash("password", salt, function(err, hash) {
		      //Query to store password hash to your DB.


The Bcrypt hashing method allows you to store and retrieve passwords in a safe way. Even if your databases are compromised, the attackers would only get access to the salted and hashed passwords.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...