Password Hashing Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in JavaScript as in every other language.
- ✓node:crypto ships scrypt/scryptSync, pbkdf2/pbkdf2Sync, randomBytes and timingSafeEqual. There is no bcrypt or Argon2 in Node core: the ecosystem uses bcrypt (a native addon), bcryptjs (pure JS, no build step, roughly 30% slower per its own documentation, though the gap widens on some Node versions) and @node-rs/argon2 or argon2 for Argon2id.
- ✓Use the callback or promisified forms, never the *Sync ones, inside a request handler. Reviewers expect crypto.timingSafeEqual on Buffers rather than === on hex, randomBytes rather than Math.random for the salt, and the cost parameters serialised into the stored string so they can be raised later.
- ✓The JavaScript trap: Node is single-threaded for JavaScript, so scryptSync or pbkdf2Sync freezes every other in-flight request for the entire cost of the derivation: one 200 ms login stalls the whole process.
- ✓bcryptjs runs the Blowfish key schedule in interpreted JavaScript and is far slower per unit of work than the native bcrypt addon or the Rust-backed @node-rs/argon2, so people compensate by lowering the cost factor, which is the wrong direction.
What Password Hashing actually is
Password Hashing in JavaScript: what you actually reach for
JavaScript implementation
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
const scryptAsync = promisify(scrypt);
const PARAMS = { N: 32768, r: 8, p: 1, maxmem: 128 * 1024 * 1024 };
export async function hashPassword(password) {
const salt = randomBytes(16);
const dk = await scryptAsync(password.normalize("NFKC"), salt, 32, PARAMS);
return ["scrypt", PARAMS.N, PARAMS.r, PARAMS.p,
salt.toString("base64"), dk.toString("base64")].join("$");
}
export async function verifyPassword(password, stored) {
const parts = String(stored).split("$");
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
const [, n, r, p, saltB64, dkB64] = parts;
try {
const salt = Buffer.from(saltB64, "base64");
const expected = Buffer.from(dkB64, "base64");
const dk = await scryptAsync(password.normalize("NFKC"), salt, expected.length,
{ N: Number(n), r: Number(r), p: Number(p), maxmem: PARAMS.maxmem });
return dk.length === expected.length && timingSafeEqual(dk, expected);
} catch {
return false;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Password Hashing?
node:crypto ships scrypt/scryptSync, pbkdf2/pbkdf2Sync, randomBytes and timingSafeEqual. There is no bcrypt or Argon2 in Node core: the ecosystem uses bcrypt (a native addon), bcryptjs (pure JS, no build step, roughly 30% slower per its own documentation, though the gap widens on some Node versions) and @node-rs/argon2 or argon2 for Argon2id. In a browser, crypto.subtle can only derive from a password with PBKDF2 via importKey('raw', ...) plus deriveBits; WebCrypto has no scrypt, bcrypt or Argon2, which is one reason password hashing belongs on the server.
What is the most common JavaScript mistake when implementing Password Hashing?
Node is single-threaded for JavaScript, so scryptSync or pbkdf2Sync freezes every other in-flight request for the entire cost of the derivation: one 200 ms login stalls the whole process. The async forms move to the libuv threadpool, which defaults to four threads, so the fifth concurrent login queues behind the others unless UV_THREADPOOL_SIZE is raised. Two more Node-only edges: crypto.scrypt throws ERR_CRYPTO_INVALID_SCRYPT_PARAM once 128 * N * r crosses the default 32 MiB maxmem, and N=32768 with r=8 is already at that ceiling, so passing a larger maxmem is mandatory rather than optional; and timingSafeEqual throws a RangeError on a length mismatch, so a truncated stored hash returns a 500 instead of false.
How does Password Hashing actually perform in JavaScript?
bcryptjs runs the Blowfish key schedule in interpreted JavaScript and is far slower per unit of work than the native bcrypt addon or the Rust-backed @node-rs/argon2, so people compensate by lowering the cost factor, which is the wrong direction. The first few calls also run in the interpreter before the JIT warms up, so a benchmark used to pick a cost factor should discard early samples. Native addons release the event loop during the derivation; pure-JS ones do not. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.