Hash progress and callbacks in bcryptjs
Expensive hashes take a noticeable time. The callback API can report progress while the hash runs, for example to drive a progress bar.
How it works
- Callback style.
bcrypt.genSalt(12, (err, salt) => …)andbcrypt.hash(password, salt, callback, progressCallback)pass their result to a callback instead of returning a promise. [1] - Track progress. The fourth argument receives a number from 0 to 1. The example prints it as a percentage with a small text bar. [1]
- Work in chunks. Between progress calls the async API gives control back, so the page stays responsive. The last line checks the result with the callback form of
bcrypt.compare. [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 = 'long-and-unique-passphrase'
const started = performance.now()
const bar = (p) => '#'.repeat(Math.round(p * 20)).padEnd(20, '.')
bcrypt.genSalt(12, (err, salt) => {
if (err) return console.log('genSalt error:', err.message)
console.log('Salt ready:', salt)
bcrypt.hash(
password,
salt,
(err, hash) => {
if (err) return console.log('hash error:', err.message)
console.log('Done in', (performance.now() - started).toFixed(0), 'ms')
console.log('Hash:', hash)
bcrypt.compare(password, hash, (err, res) => console.log('compare ->', res))
},
(p) => console.log(`progress [${bar(p)}] ${(p * 100).toFixed(0)}%`)
)
})
Raise the round count to 13 and you will see more progress lines before the hash prints. Code written by AgentGid [1].
Raise the round count to 13 and you will see more progress lines before the hash prints. 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
Hashing and checking a password with bcryptjs Synchronous hashing in bcryptjs Salt rounds and cost in bcryptjs Checking the 72-byte limit with 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.