How to hash passwords with bcrypt in Node.js
Secure password hashing is fundamental to application security, protecting user credentials even if database breaches occur. As the creator of CoreUI with extensive Node.js security experience since 2014, I’ve implemented bcrypt password hashing in countless production authentication systems. The most secure approach uses bcrypt’s adaptive hashing algorithm with appropriate salt rounds to balance security and performance. This method provides industry-standard password protection against rainbow table attacks and brute force attempts.
Use bcrypt to hash passwords during registration and verify them during login for secure authentication.
const bcrypt = require('bcrypt')
// Hash password during user registration
async function hashPassword(plainPassword) {
const saltRounds = 12
return await bcrypt.hash(plainPassword, saltRounds)
}
// Verify password during login
async function verifyPassword(plainPassword, hashedPassword) {
return await bcrypt.compare(plainPassword, hashedPassword)
}
// Example usage in registration endpoint
app.post('/register', async (req, res) => {
const { email, password } = req.body
const hashedPassword = await hashPassword(password)
// Save user with hashed password to database
const user = await User.create({
email,
password: hashedPassword
})
res.json({ message: 'User created successfully' })
})
// Example usage in login endpoint
app.post('/login', async (req, res) => {
const { email, password } = req.body
const user = await User.findOne({ email })
if (user && await verifyPassword(password, user.password)) {
// Generate JWT token
res.json({ message: 'Login successful' })
} else {
res.status(401).json({ error: 'Invalid credentials' })
}
})
This code demonstrates secure password hashing with 12 salt rounds, which provides excellent security while maintaining reasonable performance. The bcrypt.hash() function creates a unique salt and hash for each password, while bcrypt.compare() safely verifies passwords without exposing the original hash. Never store plain text passwords or use reversible encryption methods.
Best Practice Note:
This is the password security standard we implement in all CoreUI backend authentication systems. Use at least 12 salt rounds for production applications and consider increasing to 14-16 rounds for high-security environments with powerful servers.



