Back to home

What is Salt in Hashing? (with Node.js + bcrypt Example)

Sep 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.


🔑 What is Salt in Hashing?

  • Hashing: A one-way function that converts plain text into a fixed-length string. Example:
    • "mypassword" → "5f4dcc3b5aa765d61d8327deb882cf99"
  • 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:

  • Without salt: "mypassword" → "hash123"
  • With salt: "mypassword+randomSalt123" → "hashXYZ"

So, salt makes the hash unique and much harder for attackers to crack.


🛠️ Implementing Salt + Hashing in Node.js using "bcrypt"

We’ll use the "bcrypt" library in Node.js. It automatically handles salt generation and password hashing for us.

Step 1: Install bcrypt

npm install bcrypt

Step 2: Hash a Password

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

Step 3: Verify a Password

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();

📖 Step-by-Step Guide

  1. Install bcrypt npm install bcrypt
  2. Choose salt rounds Start with '10' (balance of speed & security)
  3. Hash password before saving bcrypt.hash(password, saltRounds)
  4. Store only the hashed password in your database
  5. Verify with bcrypt.compare() when logging in

🚀 Why Use bcrypt?

  • It handles salt automatically (no need to store/manage it separately).
  • Resistant to rainbow table attacks.
  • Adjustable cost factor ('saltRounds') for better security.

✅ Conclusion

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.