DEV Community

Murtaja Ziad
Murtaja Ziad

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

1

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!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay