DEV Community

Murtaja Ziad
Murtaja Ziad

Posted on • Originally published at blog.murtajaziad.xyz on

Should you store the passwords in the database?

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 — Pexels

Installing bcrypt:

Using Node, install bcrypt :

npm install bcrypt
# or
yarn add bcrypt
Enter fullscreen mode Exit fullscreen mode

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

const bcrypt = require("bcrypt");
const saltRounds = 10;
Enter fullscreen mode Exit fullscreen mode

Creating the password hash:

If you prefer using async/await :

let hash = await bcrypt.hash("password", saltRounds);
Enter fullscreen mode Exit fullscreen mode

Or, if you prefer using callbacks :

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

});
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Or, if you prefer using callbacks :

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

});
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter, and subscribe to my YouTube channel!

Discussion (0)