Bcrypt Password Hash With Salt Rounds

Hash and verify passwords with bcrypt using configurable salt rounds for adaptive cost hashing.

TypescriptAuth Jwt

Code

typescriptsnippet
1 line
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: bcrypt is 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

FAQ

Does this require external packages?
Yes — `bcrypt`. Add it to your project before running the snippet.