zxcvbn-typescript
The `zxcvbn-typescript` library offers a realistic and robust approach to password strength estimation, ported to TypeScript from Dan Wheeler's original zxcvbn project. It evaluates password quality by analyzing various patterns, including common words, names, dates, sequences, keyboard patterns, and leetspeak, providing a numerical score and targeted verbal feedback to guide users. The current stable version is 5.0.1. With its v5.0.0 release, the library was fully converted to TypeScript, enhancing type safety and maintainability for modern development environments. While a strict release cadence isn't defined, updates typically align with algorithm refinements or significant refactors. Its key differentiator remains its comprehensive pattern-matching capabilities, which often provide more nuanced security assessments than simpler entropy-based methods.
Common errors
-
TypeError: zxcvbn is not a function
cause This typically occurs due to an incorrect import statement (e.g., attempting a named import when the library provides a default export) or CommonJS/ESM module interop issues in your build or runtime environment.fixIf using ESM, ensure you use `import zxcvbn from 'zxcvbn-typescript';`. If using CommonJS, use `const zxcvbn = require('zxcvbn-typescript');`. Also, check your `tsconfig.json`'s `moduleResolution` and `module` options for compatibility. -
TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
cause Passing a potentially `undefined` or `null` value as the password or an element within `userInputs` without proper type narrowing, which is enforced more strictly by TypeScript, especially in v5.0.0 and later.fixEnsure that the `password` argument and all elements within the `userInputs` array are explicitly of type `string`. Use conditional checks (`if (password) { ... }`) or non-null assertion operators (`password!`) after confirming values are present. -
Error: Cannot find module 'zxcvbn-typescript'
cause The package has not been installed, or there is a module resolution conflict within your build tool (e.g., Webpack, Rollup) or Node.js runtime environment.fixRun `npm install zxcvbn-typescript` or `yarn add zxcvbn-typescript`. Confirm your `tsconfig.json` `compilerOptions.moduleResolution` (e.g., 'NodeNext' for modern Node.js or 'bundler' for bundlers) and ensure your package manager can correctly resolve the module.
Warnings
- breaking Version 5.0.0 introduced a complete port to TypeScript. This transition may lead to stricter type checks and potential build issues in existing JavaScript projects without proper TypeScript configuration or type declarations. For projects previously relying on `@types/zxcvbn` for type definitions, these are now natively bundled with `zxcvbn-typescript` v5.x.
- gotcha Performance can be affected when evaluating extremely long passwords (e.g., hundreds of characters) or performing frequent checks in performance-critical sections of an application. The algorithm is optimized for interactive, user-facing feedback, not high-throughput batch processing of arbitrary length strings.
- gotcha While `zxcvbn-typescript` generally bundles its dictionary data, some modular `zxcvbn` implementations (such as `@zxcvbn-ts/core`) split language and dictionary data into separate packages to reduce initial bundle size. If you encounter unexpected 'Top 10 common password' warnings or notice less effective pattern matching, confirm that all necessary dictionary and language data is being loaded and configured correctly.
Install
-
npm install zxcvbn-typescript -
yarn add zxcvbn-typescript -
pnpm add zxcvbn-typescript
Imports
- zxcvbn
import { zxcvbn } from 'zxcvbn-typescript';import zxcvbn from 'zxcvbn-typescript';
- ZXCVBNResult
import type { ZXCVBNResult } from 'zxcvbn-typescript'; - zxcvbn (CommonJS)
const zxcvbn = require('zxcvbn-typescript');
Quickstart
import zxcvbn from 'zxcvbn-typescript';
import type { ZXCVBNResult } from 'zxcvbn-typescript';
/**
* Evaluates a password's strength and logs detailed feedback.
* @param password The password string to evaluate.
* @param userInputs Optional array of strings (e.g., username, email) to penalize if found in the password.
* @returns The detailed `ZXCVBNResult` object.
*/
function evaluatePassword(password: string, userInputs: string[] = []): ZXCVBNResult {
const result = zxcvbn(password, userInputs);
console.log(`Password: "${password}"`);
console.log(`Score (0-4): ${result.score}`);
console.log(`Estimated guesses: ${result.guesses.toLocaleString()}`);
console.log(`Feedback: ${result.feedback.warning || 'Looks good!'}`);
result.feedback.suggestions.forEach(suggestion => {
console.log(`- Suggestion: ${suggestion}`);
});
// Accessing various crack time estimations
console.log(`\nCrack Times:`);
console.log(` Online (throttled): ${result.crack_times_display.online_throttling_100_per_hour}`);
console.log(` Offline (slow hash): ${result.crack_times_display.offline_slow_hashing_1e4_per_second}`);
return result;
}
// Example usage with different password strengths and user inputs
const weakPassword = 'password123';
const moderatePassword = 'MySecretPassword1!';
const strongPassword = 'correct horse battery staple';
const userEmail = 'test@example.com';
const userName = 'JohnDoe';
console.log('--- Evaluating Weak Password ---');
evaluatePassword(weakPassword, [userEmail, userName]);
console.log('\n--- Evaluating Moderate Password ---');
evaluatePassword(moderatePassword, ['mysecret', 'password']);
console.log('\n--- Evaluating Strong Password ---');
evaluatePassword(strongPassword, ['correcthorse']);