bcrypt (Password Hashing) (Node.js)

bcrypt is a library for securely hashing passwords in Node.js. It turns a password into a salted, slow-to-compute hash you store instead of the plaintext, and compares a login attempt against that hash.

Node.js

You must never store passwords in plaintext. bcrypt hashes a password with a built-in random salt so identical passwords produce different hashes, and it is deliberately slow (configurable via a 'cost' or salt-rounds factor) to make brute-force guessing expensive even if your database leaks.

The API is small: bcrypt.hash(password, rounds) produces the hash you save at signup, and bcrypt.compare(attempt, storedHash) returns true/false at login — it extracts the salt from the stored hash internally, so you never manage salts yourself. Both have async (Promise) and sync forms; prefer async so hashing does not block the event loop.

The cost factor (often 10-12 rounds) trades security for speed; higher is safer but slower. bcrypt is purpose-built for passwords, unlike fast general hashes (SHA-256) which are unsuitable because they are too quick to brute-force. It pairs naturally with JWT auth: bcrypt verifies the password, then you issue a token.

Syntax

await bcrypt.hash(pw, 12); await bcrypt.compare(pw, hash)

Examples

JavaScript

const bcrypt = require("bcrypt");

// at signup
const hash = await bcrypt.hash("s3cret", 12);

// at login
const ok = await bcrypt.compare("s3cret", hash);
console.log(ok); // true

Output:

true

Learn it in a lesson

See also

Back to the Dictionary