~/ How to Use bcryptjs to Hash Passwords in Node.js

Learn how to securely hash and compare passwords in Node.js using bcryptjs. Ideal for login systems, authentication, and user data protection.

June 5, 2025

|

5 min read

Node.js
bcryptjs
Authentication
Security
JavaScript

If you're building any kind of authentication system in Node.js, securely storing user passwords is non-negotiable. That's where bcryptjs comes in.

In this guide, you'll learn how to:

  • Hash passwords using bcryptjs
  • Store them safely (e.g., in a database)
  • Compare hashed passwords during login

bcryptjs is a pure JavaScript implementation of the popular bcrypt hashing algorithm. It:

  • Is simple and fast to implement
  • Adds salt automatically (for security)
  • Works well in environments where native bcrypt is tricky to install
  • Once a password is hashed, it cannot be decrypted back to the original password. Instead, passwords are verified by comparing a plain-text password with the hashed value using a secure comparison method.

In your Node.js project:

Bash

npm install bcryptjs

When a user signs up, you'll hash their password before storing it in your database.

JavaScript

const bcrypt = require("bcryptjs"); const password = "MySecureP@ssw0rd"; // Hash the password bcrypt.hash(password, 10, (err, hash) => { if (err) throw err; console.log("Hashed Password:", hash); // Save hash to your database });
  • 10 is the number of salt rounds. Higher = more secure but slower.

When a user logs in, compare the plain password with the hashed one stored in your DB:

JavaScript

const enteredPassword = "MySecureP@ssw0rd"; const storedHash = "$2a$10$gE9gZiM3T..."; // from DB bcrypt.compare(enteredPassword, storedHash, (err, isMatch) => { if (err) throw err; if (isMatch) { console.log("Password is correct!"); } else { console.log("Invalid password."); } });

This ensures you never store or transmit the real password-only compare it securely.


TipWhy It Matters
Always hash passwordsNever store plain-text passwords
Use at least 10 salt roundsBalances security and performance
Compare with bcrypt.compare()It handles hashing + salting automatically
Use HTTPSProtect passwords during transmission
Avoid reusing hashed passwordsGenerate a new hash even if the password is the same

bcrypt uses native bindings (C++) and may require build tools to install. bcryptjs is easier to use and install but slightly slower. Both are secure-pick what fits your project needs.


For scripts or command-line tools:

JavaScript

const hash = bcrypt.hashSync("password123", 10); const isMatch = bcrypt.compareSync("password123", hash); console.log("Match:", isMatch);

Using bcryptjs in Node.js is one of the fastest ways to implement secure password hashing and verification. It's a must-have in any login or authentication system.

If you're serious about protecting user data, hashing isn't optional-it's foundational.