Hashing and checking a password with bcryptjs
Storing a bcrypt hash instead of the password means you never keep the plain text. At login you compare the typed password against the stored hash.
How it works
- Generate a salt.
await bcrypt.genSalt(10)creates a salt with 10 rounds. The example prints it so you can see it starts with the bcrypt version and cost. [1] - Hash the password.
await bcrypt.hash(password, salt)returns the hash string, which is what you would store. The example prints the hash and its length. [1] - Compare at login.
await bcrypt.compare(input, hash)resolves totruefor the right password andfalsefor a wrong one. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import bcrypt from 'bcryptjs'
const password = 'correct horse battery staple'
// 1. Generate a salt (10 rounds) and hash the password
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(password, salt)
console.log('Password: ', password)
console.log('Salt: ', salt)
console.log('Hash: ', hash)
console.log('Hash length:', hash.length)
// 2. Later, check login attempts against the stored hash
const attempts = ['correct horse battery staple', 'Tr0ub4dor&3', 'Correct horse battery staple']
for (const guess of attempts) {
const ok = await bcrypt.compare(guess, hash)
console.log(`compare("${guess}") ->`, ok)
}
Change the password or the guess and run again; the salt and hash are different on every run. Code written by AgentGid [1].
Change the password or the guess and run again; the salt and hash are different on every run. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with bcryptjs 3.0.3. Needs WebGL.
More bcryptjs examples
Synchronous hashing in bcryptjs Salt rounds and cost in bcryptjs Checking the 72-byte limit with bcryptjs Hash progress and callbacks in bcryptjs
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.