Setting up Bcrypt to your Express API

Setting up Bcrypt to your Express API

ยท

4 min read

Have you made any API using Express.js? If yes then you must have used something to hash your password and save it to your database. No, don't tell me that you saved the password as plain text. Dude, you are putting user's data at high risk. You must not save the user's password as plain text. And to hash passwords, you can use Bcrypt.

Save passwords in plain text and boom, you are unemployed.

Now you must be wondering, what should I do to secure user's data. For that save hashed passwords to your database. To hash your password use Bcrypt. Now I'll show you how to set up Bcrypt to your Express.js API.

Installation

Installing Bcrypt to your node.js app is as easy as installing express was. You just have to copy this below code and paste it into your terminal.

npm i bcrypt

or you can also do

npm install bcrypt

Add it to your app

Now after installation is completed, you need to add this to your app. You can add it the same way you added express to your app.

const express = require('express')
const bcrypt = require('bcrypt')

Add wherever you need it and not to the index page or app page.

Hashing Passwords

After you have added bcrypt to your login/signup or user page. You need to only hash the password and not the whole user that came from the request.

router.route('/signup').post(async (req, res) => {
const newUser = req.body
    try {
      // Here you generate salt in the above line ๐Ÿ‘‡
      const salt = await bcrypt.genSalt(10)
      verifyNewUser.password = await bcrypt.hash(verifyNewUser.password, salt) 
      // Here you hash the password and also add the salt โ˜๏ธ
      // Here we save the user ๐Ÿ‘‡
      const userSaved = await verifyNewUser.save()
      const token = jwt.sign({ userId: userSaved._id }, secretKey)
      const { password, __v, ...restUserData } = userSaved._doc
      res.json({ success: true, user: restUserData, token })
    } catch (error) {
      res.json({
        success: false,
        message: 'Unable to signup.',
        errorMessage: error.message,
      })
    }
})

Don't get confused by other code, I'm not trying to tell you how to build a signup route in your API, and here is only a demonstration of bcrypt.

Now when you hash your password you get a string that is not just plain text but a new hash that is not the same as others. So it makes it impossible to know someone's password.

Comparing hash to authenticate the user

You just don't need to hash and save it to the database, you also need the hashed password to authenticate users. For that look at this code.

router.route('/').post(async (req, res) => {
  const { email, password } = req.body
  try {
    const user = await User.findOne({ email: email })
    if (!user) {
      res.json({ success: false, message: 'No user found with this email.' })
    }
    // Here it is how you check for correct password ๐Ÿ‘‡
    const isPasswordCorrect = await bcrypt.compare(password, user.password)
    if (isPasswordCorrect) {
      const token = jwt.sign({ userId: user._id }, secretKey)
      const { password, __v, ...restUserData } = user._doc
      res.json({ success: true, user: restUserData, token })
    } else res.json({ success: false, message: 'Incorrect Password' })
  } catch (error) {
    res.json({ success: false, message: 'Unable to login', errorMessage: error.message })
  }
  res.json({ success: true })
})

Don't get confused by other code.

You use bcrypt.compare to check whether the password is correct or not. Make sure you place the password from the post request as the first argument and in the second one you put the password which came from the database. Now when you have the result that if the password is correct or not, do whatever you want with it or you can use it I've shown above, send user data as a response on correct else send Incorrect Password as a message.

Updating Password later

Now, this was how you make it work but now when you are updating the password through some route or anyhow, you better know about your app then there you must again use bcrypt to hash the password else it'll go to the database as plain text. This will not only reveal the user's password but also not let the user login as at the login we are comparing passwords through bcrypt. Compare will result in a false and a response will be sent with the message, Incorrect Password.

Thanks

Thank you for reading. If you found this helpful, consider sharing it with people who may found it helpful. I would love to read your comment, waiting for it. Hashnode will promote this article more if you like it.

Priyanshu

Did you find this article valuable?

Support Priyanshu by becoming a sponsor. Any amount is appreciated!

ย