Password Hashing
Learn to securely hash and verify passwords using bcrypt
40 min•By Priygop Team•Last updated: Feb 2026
Password security
Password hashing is a crucial security practice that converts plain text passwords into irreversible hash values. This prevents passwords from being stored in plain text and protects user accounts even if the database is compromised.
Password Hashing with bcrypt
Example
const bcrypt = require('bcryptjs');
// Hash password
const hashPassword = async (password) => {
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);
return hashedPassword;
};
// Verify password
const verifyPassword = async (password, hashedPassword) => {
const isValid = await bcrypt.compare(password, hashedPassword);
return isValid;
};
// Registration endpoint
app.post('/register', async (req, res) => {
try {
const { name, email, password } = req.body;
// Check if user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: 'User already exists' });
}
// Hash password
const hashedPassword = await hashPassword(password);
// Create new user
const user = new User({
name,
email,
password: hashedPassword
});
await user.save();
// Generate token
const token = generateToken(user._id);
res.status(201).json({
message: 'User created successfully',
token,
user: { id: user._id, email: user.email, name: user.name }
});
} catch (error) {
res.status(500).json({ error: 'Registration failed' });
}
});
// Change password endpoint
app.put('/change-password', authenticateToken, async (req, res) => {
try {
const { currentPassword, newPassword } = req.body;
// Get user
const user = await User.findById(req.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Verify current password
const isValidPassword = await verifyPassword(currentPassword, user.password);
if (!isValidPassword) {
return res.status(400).json({ error: 'Current password is incorrect' });
}
// Hash new password
const hashedNewPassword = await hashPassword(newPassword);
// Update password
user.password = hashedNewPassword;
await user.save();
res.json({ message: 'Password updated successfully' });
} catch (error) {
res.status(500).json({ error: 'Failed to update password' });
}
});