Mehdi Faraji
Mehdi Faraji

Reputation: 3816

How to hash password with bcryptjs in node?

I recieve password through req.body and hash it like this :

    const { name, email, password, number } = req.body;

    let userExist;
    userExist = await User.find({ email: email });

    if (userExist.length) {
        const err = new Error('User already exists');
        return next(err);
    }

    let hashedPass;
    try {
        hashedPass = await bcrypt(req.body.password, 12);
    } catch (e) {
        console.log('error here bro');
        return next(e);
    }

    const createdUser = new User({
        name,
        email,
        password: hashedPass,
        number,
        ads: []
    });

It console logs 'error here bro' and I dont know why .

How can I hash password coming from user with bcrypt js ?

Upvotes: 0

Views: 538

Answers (2)

atilio-ts
atilio-ts

Reputation: 112

You can also add salt to your password in the following way:

const salt = await bcrypt.genSalt(7);
const hashPassword = await bcrypt.hash(req.body.secret, salt);

Upvotes: 1

Mehdi Faraji
Mehdi Faraji

Reputation: 3816

Solved the problem by adding hash after bcrypt

bcrypt.hash(....)

Upvotes: 0

Related Questions