Should you store the passwords in the database?

May 24, 2020

Basically, NO you shouldn’t store the passwords in the database, you should store the password hash.


Silhouette of Mountain Under Cloudy Sky during Sunset


Installing bcrypt:

Using Node, install bcrypt :

npm install bcrypt
# or
yarn add bcrypt

In your code, require bcrypt and define the salt rounds,

const bcrypt = require("bcrypt");
const saltRounds = 10;

Creating the password hash:

If you prefer using async/await :

let hash = await bcrypt.hash("password", saltRounds);

Or, if you prefer using callbacks :

bcrypt.hash('password', saltRounds, (error, hash) => {

});

Then you can store the resulting hash in the database, note that password refers to the password string.


Verifying the password hash:

If you need the verify the password hash, you should compare it with the hash stored in the database using bcrypt.compare() :

If you prefer using async/await :

let comparisonResult = await bcrypt.compare("password", hash);

Or, if you prefer using callbacks :

bcrypt.compare('password', hash, (error, comparisonResult) => {
  
});

Written by Murtaja Ziad, a full-stack web developer.
My website - Follow me on Twitter