WAll passwords should be hashed before entering a database because you have to consider the scenario where some malicious user attempts to gain entry into your data. Passwords are sensitive pieces of information that you don't want people to see.

Now, let's not confuse encryption with hashing. Encrypting something assumes it can later be decrypted. Although this is better than leaving as plain text, what we really want is something that cannot be decrypted. This is what hashing offers us.

Hashing With Bcrypt

For this example, we're going to use the more popular bcryptjs library for Node.js. However, it follows the same rules as other standard Bcrypt libraries. You pass in a string to be hashed and usually a salt as well.

For the example of bcryptjs you would do something like this, per the documentation:

The above two lines were pretty much taken from the documentation. In the first line, the comparison will fail and return false back to the user. In this event you know the values are wrong without even knowing what the hashed password really is. In the event of the second line, the passwords match and you'll get a true response back.

A Working Example

Let's make a working example from what we've learned above. Create a new directory somewhere and in it create a new package.json file with the following JSON:

You should swap out the server and bucket with whatever you plan to use.

Now for the fun stuff! Create a file called app.js as this is where all our code is going to go. Keep in mind that this is an example, so functionality will be limited. Add the following JavaScript code to the app.js file:

We're essentially just creating a JSON document with a hashed password and inserting it into Couchbase Server. After inserting is complete, we get the document and compare passwords.

Conclusion

You should never store plain text passwords in your database. It doesn't matter how secure your database is or what type of database you're using. By using the Bcrypt hashing algorithm on your passwords you can add a tremendous amount of security for your users.

The bcryptjs library for Node.js is just one of many suitable libraries that can accomplish this job.