NestJS — Enterprise Node.js

Encryption, Hashing & Secrets

18 min Lesson 59 of 80

Encryption, Hashing & Secrets

NestJS does not hide Node.js cryptography behind unnecessary abstractions. You use the platform crypto module for encryption, established password-hashing libraries for credentials, and configuration modules or secret managers for key material.

Core idea

This feature is about controlling how the application is organized and how it behaves at runtime. These are the points a developer should understand before using it in a real project:

  • Hash passwords with Argon2 or bcrypt, never with fast general-purpose hashes such as SHA-256 alone.
  • Encryption is reversible and requires key management; hashing is one-way and used for verification.
  • Use random salts and modern parameters for password hashing.
  • Keep encryption keys outside the repository and rotate them through a planned process.
  • Use constant-time comparison for token hashes and signature checks.

Practical example

The following example shows the idea in a practical NestJS project. The goal is not to memorize the snippet, but to understand where it belongs in the architecture:

@Injectable() export class PasswordService { async hashPassword(password: string): Promise<string> { return argon2.hash(password, { type: argon2.argon2id }); } async verify(password: string, hash: string): Promise<boolean> { return argon2.verify(hash, password); } safeEquals(a: string, b: string): boolean { return timingSafeEqual(Buffer.from(a), Buffer.from(b)); } }
Design note: Most application security failures around cryptography are design failures: the wrong primitive, weak keys, accidental logging, or secrets committed to source control.

Production checklist

  • Use Argon2id or bcrypt for user passwords.
  • Do not log tokens, passwords, private keys, or decrypted payloads.
  • Validate required secret lengths during bootstrap.
  • Plan key rotation before the first production incident.
Rule of thumb: If the feature makes boundaries clearer and tests easier, it is probably the right choice. If it hides dependencies or makes tracing harder, redesign.

Summary

This lesson covers an advanced NestJS area that matters when building enterprise applications. Focus on clear boundaries, testable behavior, and choosing the right tool for the context instead of using every feature everywhere.