DEV Community

JosephSam
JosephSam

Posted on

What is the best approach; hashing password in req.body.password or at the database user.password in express-mongoose web app

I am creating a user post route in which i'll be doing the password hashing. So what is the best approach for hashing password is it this;

let user = await User.findOne({email: req.body.email})
if (user) return res.status(400).send('The user already exists')

user = new User({
name : req.body.name,
email: req.body.email,
password: req.body.password
})

// hashing user passwords
const salting = await bcrypt.genSalt(10)
user.password = await bcrypt.hash(user.password, salting)
Hashing it on the database level or this;

let user = await User.findOne({email: req.body.email})
if (user) return res.status(400).send('The user already exists')

// hashing user passwords
const salting = await bcrypt.genSalt(10)
const hashedPassword = await bcrypt.hash(req.body.password, salting)

user = new User({
name : req.body.name,
email: req.body.email,
password: hashedPassword
})
hashing on the request level, or there is a better way of doing the hashing? Your opinions/recommendation will be much useful. Thanks in advance.

Top comments (0)