Password Hashing in NodeJS

Nodejs provides crypto modules to perform the encryption and hashing of sensitive information such as passwords. The Bcrypt node modules provides easy way to create and compare hashes.

Let’s learn how to use it.

Installation and usage

To use the library, simply install with NPM:

npm i --S bcrypt

Then include it in your project.

const bcrypt = require('bcrypt');

Creating and Verifying Hash

Bcrypt provides both synchronous and asynchronous methods. I recommend asynchronous method because hashing is CPU intensive, and the synchronous version will block the event loop and prevent your app from handling other requests until it finishes.

Here is the code for hashing using asynchronous method. First argument is the password and second argument is number of rounds for the salt generation.

asynchronous hash

To verify the hashed password you can use the following code:

compare hash

That’s it. Easy as cake.


You must always hash your password or any sensitive information that you don’t need in original form again. Hashing is one way that means you can’t get the original data back from the hash but regenerate same hash using the original data.

Further Study

How to Validate an Email Address in JavaScript
How to Remove a Particular Element from an Array in JavaScript
How to Use Session Storage API in JavaScript
How to Replace All Occurrences of a String in JavaScript


Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 290