Back to Courses

World's Best MERN Stack Course

MERN #11: Secure User Password using Bcrypt.js

Welcome, in this video we will see how to secure user regsiter password using bcrypt.js. Why we need to hash password?

Hashing passwords is crucial for security because it converts plaintext passwords into irreversible, unique codes, making it significantly harder for attackers to decipher and misuse sensitive user information. This adds a vital layer of protection, enhancing overall data security in applications.

How to secure the password?

  • To securely store passwords in a MongoDB database, it's essential to hash the passwords before saving them.

  • Choose a Password Hashing Library: Use a library like bcrypt or argon2 to hash passwords. bcrypt is a widely used and well-regarded library for this purpose.

// hash the password
const saltRound = 10;
const hash_password = await bcrypt.hash(password, saltRound);

await User.create({ username, email, password: hash_password });

Schema file:

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

// Define the User schema
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  phone: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  isAdmin: {
    type: Boolean,
    default: false,
  },
});

//? secure the password with the bcrypt
userSchema.pre("save", async function () {
  const user = this;
  console.log("actual data ", this);

  if (!user.isModified) {
    return next();
  }

  try {
    const saltRound = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(user.password, saltRound);
    user.password = hashedPassword;
  } catch (error) {
    return next(error);
  }
});

// define the model or the collection name
const User = new mongoose.model("USER", userSchema);

module.exports = User;