Encrypt user password in nodejs

Today we are going to learn how to secure registered user password with encryption and salt in nodejs application.

Requirements

  • NodeJs
  • Bcryptjs

We are not going to cover the installation and defining the route, we assumed that you already installed and set up the route for the user registration process. We are going to use Bcryptjs package to encrypt the password.

npm i bcryptjs

Once the package successfully installed, load the package to our route. I have the users.js route that handles the registration, login, etc. functions.

const bcrypt = require('bcryptjs');
.....
.....

Now let’s jump to the user save model and the encryption process.

const newUser = new User({
    name: req.body.name, 
    email: req.body.email, 
    password: req.body.password, 
});

bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password, salt, (err, hash) => {
        if(err) throw err;

        // Set the hashed password and save the model
        newUser.password = hash;
        newUser.save()
        .then((user) => res.json(user))
        .catch(error => console.log(error));
    })
 });

Now when user register this program will automatically encrypt user password and save to our database. But this is not done yet, we have to compare the plain user password with this encrypted password to make the user login.

// Pass saved encrypted password as second parameter
bcrypt.compare(PlaintextPassword, user.password, function(err, res) {
    // res == true
});

Resources

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.