bcrypt-ts

8.0.1 · active · verified Tue Apr 21

bcrypt-ts is a TypeScript-first, pure JavaScript implementation of the bcrypt password-hashing function, designed for both Node.js and browser environments. It provides cryptographic hashing for passwords, focusing on security features like salting and an adaptive iteration count to resist brute-force attacks. The current stable version is 8.0.1. The project appears to have a relatively active release cadence, with major versions (v6, v7, v8) released over time, often driven by Node.js version support or build system changes. Key differentiators from `bcrypt.js` include being fully written in TypeScript, providing separate ESM modules optimized for Node.js and browsers, offering better tree-shaking, and having a minified output. While compatible with the C++ `bcrypt` binding, it's inherently slower due to being a pure JavaScript implementation (approximately 30% slower according to the README, referencing `bcrypt.js` benchmarks), which means fewer iterations can be performed in the same timeframe, requiring careful consideration of the work factor.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to asynchronously generate a salt, hash a password, and then compare a candidate password against the stored hash using `bcrypt-ts`.

import { genSalt, hash, compare } from 'bcrypt-ts';

async function main() {
  // Generate a salt with a work factor of 10
  // A higher work factor increases security but also computation time
  const saltRounds = 10;
  console.log(`Generating salt with ${saltRounds} rounds...`);
  const salt = await genSalt(saltRounds);
  console.log('Salt generated:', salt);

  // Hash a password using the generated salt
  const password = process.env.USER_PASSWORD ?? 'mySecurePassword123!';
  console.log('Hashing password...');
  const hashedPassword = await hash(password, salt);
  console.log('Hashed password:', hashedPassword);

  // To store in your database, ensure the column can hold 60 characters

  // Verify a password against the stored hash
  const candidatePassword = process.env.LOGIN_PASSWORD ?? 'mySecurePassword123!';
  console.log(`Comparing '${candidatePassword}' with hash...`);
  const isMatch = await compare(candidatePassword, hashedPassword);
  console.log('Password matches:', isMatch);

  const wrongPassword = 'notThePassword';
  console.log(`Comparing '${wrongPassword}' with hash...`);
  const isWrongMatch = await compare(wrongPassword, hashedPassword);
  console.log('Wrong password matches:', isWrongMatch);
}

main().catch(console.error);

view raw JSON →