0
0
NestjsHow-ToBeginner ยท 4 min read

How to Use bcrypt in NestJS for Password Hashing

In NestJS, use the bcrypt library to hash passwords by calling bcrypt.hash() and verify them with bcrypt.compare(). Import bcrypt, then create async functions to hash and check passwords safely within your services.
๐Ÿ“

Syntax

To use bcrypt in NestJS, import the library and use these main functions:

  • bcrypt.hash(password, saltRounds): hashes a password with a given number of salt rounds.
  • bcrypt.compare(password, hash): compares a plain password with a hashed password to verify a match.

Both functions return promises, so use async/await for clean code.

typescript
import * as bcrypt from 'bcrypt';

async function hashPassword(password: string): Promise<string> {
  const saltRounds = 10;
  return await bcrypt.hash(password, saltRounds);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return await bcrypt.compare(password, hash);
}
๐Ÿ’ป

Example

This example shows a simple NestJS service that hashes a password and then verifies it.

typescript
import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
  private readonly saltRounds = 10;

  async hashPassword(password: string): Promise<string> {
    return await bcrypt.hash(password, this.saltRounds);
  }

  async verifyPassword(password: string, hash: string): Promise<boolean> {
    return await bcrypt.compare(password, hash);
  }
}

// Usage example (outside NestJS context):
async function demo() {
  const authService = new AuthService();
  const password = 'mySecret123';
  const hashed = await authService.hashPassword(password);
  console.log('Hashed password:', hashed);

  const isMatch = await authService.verifyPassword('mySecret123', hashed);
  console.log('Password match:', isMatch);

  const isWrong = await authService.verifyPassword('wrongPass', hashed);
  console.log('Wrong password match:', isWrong);
}

demo();
Output
Hashed password: $2b$10$... (a bcrypt hash string) Password match: true Wrong password match: false
โš ๏ธ

Common Pitfalls

Common mistakes when using bcrypt in NestJS include:

  • Using synchronous bcrypt functions which block the event loop instead of async ones.
  • Not awaiting the hash or compare promises, causing unexpected behavior.
  • Using too few salt rounds, which weakens security (10 or more is recommended).
  • Storing plain passwords instead of hashed ones.

Always use async/await with bcrypt and never store raw passwords.

typescript
/* Wrong way (blocking and insecure): */
import * as bcrypt from 'bcrypt';

const hash = bcrypt.hashSync('password', 5); // sync and low salt rounds

/* Right way: */
async function secureHash() {
  const hash = await bcrypt.hash('password', 10); // async and recommended salt rounds
  return hash;
}
๐Ÿ“Š

Quick Reference

FunctionPurposeNotes
bcrypt.hash(password, saltRounds)Hashes a passwordReturns a promise with the hashed string; use saltRounds โ‰ฅ 10
bcrypt.compare(password, hash)Verifies password against hashReturns a promise with true/false
saltRoundsNumber of hashing roundsHigher means more secure but slower; 10 is a good default
โœ…

Key Takeaways

Always use async bcrypt functions with await to avoid blocking NestJS.
Hash passwords with at least 10 salt rounds for good security.
Never store plain text passwords; always store hashed versions.
Use bcrypt.compare to verify passwords safely.
Wrap bcrypt logic inside NestJS services for clean code organization.