Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Password Hashing Implementation in JavaScript

14 min readintermediate
Website QA and SEO audits

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 stores a login credential as a deliberately slow, salted, one-way derivation instead of the password itself. You verify by re-deriving with the stored salt and parameters and comparing in constant time. The cost parameters (iterations, memory, parallelism) exist to make offline cracking of a stolen table expensive. The modern choices are Argon2id, scrypt, bcrypt and PBKDF2 with a high iteration count. A plain SHA-256 or MD5 digest is not password hashing: a GPU computes billions of those per second. You reach for this the moment you own a users table with a password column, and again every few years when you raise the cost and rehash on next login.

Password Hashing in JavaScript: what you actually reach for

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.

JavaScript implementation

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. String comparison of hashes and a hand-rolled loop over characters both get flagged. Normalising the input with String.prototype.normalize('NFKC') before hashing is expected once you accept non-ASCII passwords.
javascript
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 Free

The JavaScript-specific 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. 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.

Performance in JavaScript, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Password Hashing between languages.

Real-World Applications

Password Hashing is used extensively in production software: authentication systems, payment processing, encrypted communications, and data protection mechanisms depend on this technique. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Password Hashing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Password Hashing appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Password Hashing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Password Hashing to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.