September 10, 2025

When we store passwords in a database, we never store them as plain text. Instead, we hash them. But even hashing alone is not enough to keep passwords secure. Thatโs where salt comes in.
Hashing: A one-way function that converts plain text into a fixed-length string. Example:
Problem without salt: Attackers can use rainbow tables (precomputed hashes of common passwords) to quickly guess the original password.
Salt: A random string added to the password before hashing. This ensures that even if two users have the same password, their hashes will be different.
๐ Example:
So, salt makes the hash unique and much harder for attackers to crack.
Weโll use the "bcrypt" library in Node.js. It automatically handles salt generation and password hashing for us.
npm install bcrypt
import bcrypt from "bcrypt";
// Number of salt rounds (higher = more secure, but slower)
const saltRounds = 10;
async function hashPassword(password) {
const hashedPassword = await bcrypt.hash(password, saltRounds);
console.log("Hashed Password:", hashedPassword);
return hashedPassword;
}
hashPassword("mypassword123");
๐ Output will look like:
$2b$10$CwTycUXWue0Thq9StjUM0uZBZrYdOV9YtQ0eFh6XuhhUIa0G1PZby
When a user logs in, we need to compare their entered password with the hashed one in the database.
async function verifyPassword(password, hashedPassword) {
const match = await bcrypt.compare(password, hashedPassword);
if (match) {
console.log("โ
Password is correct!");
} else {
console.log("โ Password is incorrect!");
}
}
async function demo() {
const hashed = await hashPassword("mypassword123");
await verifyPassword("mypassword123", hashed); // โ
Correct
await verifyPassword("wrongpassword", hashed); // โ Incorrect
}
demo();
npm install bcryptbcrypt.hash(password, saltRounds)Salt in hashing is like adding extra spice to your password security ๐ฒ. It makes each password hash unique and protects against attacks.
By using 'bcrypt' in Node.js, you donโt need to manage salt yourselfโbcrypt does it all for you.