Bcrypt Password Hash With Salt Rounds
Hash and verify passwords with bcrypt using configurable salt rounds for adaptive cost hashing.
Code
import bcrypt from'bcrypt';export async function hashPassword(password:string,saltRounds=12):Promise<string>{return bcrypt.hash(password,saltRounds);}export async function verifyPassword(hash:string,password:string):Promise<boolean>{try{return await bcrypt.compare(password,hash);}catch{return false;}}export function needsRehash(hash:string,targetRounds=12):boolean{const rounds=hash.split('$')[2];return Number(rounds)!==targetRounds;}export async function hashWithPepper(password:string,pepper:string,saltRounds=12):Promise<string>{return hashPassword(password+pepper,saltRounds);}How it works
The moving parts are the functions hashPassword, verifyPassword, needsRehash and hashWithPepper.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- Plan for an install step:
bcryptis a real dependency, resolved by the package manager.
Putting it to use
Entry signature: export async function hashPassword(password:string,saltRounds=12)
hashPassword is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.
FAQ
- Does this require external packages?
- Yes — `bcrypt`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.