How to hash passwords in Node.js
Securely hashing passwords is fundamental for any Node.js application that handles user authentication, protecting user credentials from data breaches and unauthorized access. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented password hashing in countless Node.js backend systems and enterprise applications. From my 25 years of experience in web development and 11 years with Node.js, the most secure and industry-standard approach is to use the bcrypt library with appropriate salt rounds. This method provides strong protection against rainbow table attacks and brute force attempts.
Use the bcrypt library with salt rounds to securely hash passwords before storing them in your database.
const bcrypt = require('bcrypt')
async function hashPassword(password) {
const saltRounds = 12
const hashedPassword = await bcrypt.hash(password, saltRounds)
return hashedPassword
}
async function verifyPassword(password, hashedPassword) {
const isValid = await bcrypt.compare(password, hashedPassword)
return isValid
}
// Usage example
const userPassword = 'userSecretPassword'
const hashed = await hashPassword(userPassword)
console.log(hashed) // $2b$12$...
const isValid = await verifyPassword(userPassword, hashed)
console.log(isValid) // true
The bcrypt.hash() function takes the plain text password and salt rounds as parameters, returning a hashed string that includes the salt. Salt rounds determine the computational cost - 12 rounds provide excellent security for most applications. The bcrypt.compare() function safely compares a plain text password with a hashed password, automatically handling the salt extraction and comparison. Always use async/await or promises since bcrypt operations are computationally intensive.
This is the same secure password hashing approach we use in CoreUI backend systems and admin panel authentication. Never store plain text passwords or use simple hashing algorithms like MD5 or SHA1 without proper salting for password storage.



