Back to Node.js tutorials
Advanced19 min read

Authentication & Security

Implement password hashing, JWT sessions, HTTP hardening, and input validation for production APIs.

Password Hashing

Never store plaintext passwords. Use bcrypt, scrypt, or argon2 with per-user salts and work factors tuned to your hardware budget.

Compare passwords with constant-time functions provided by the library. Rate-limit login attempts to mitigate brute force.

Password reset flows should use single-use tokens with short expiry rather than emailing existing passwords.

  • Increase bcrypt rounds gradually as hardware improves
  • Require strong passwords or passkeys for sensitive apps
  • Log auth failures without storing submitted passwords
import bcrypt from 'bcrypt';
const hash = await bcrypt.hash(password, 12);
const ok = await bcrypt.compare(password, hash);

JWT and Session Security

JSON Web Tokens encode claims signed with a secret or private key. Use short-lived access tokens plus refresh tokens stored httpOnly when building SPAs.

Validate issuer, audience, and expiration on every request. Rotate signing keys periodically with kid headers for multi-key verification.

Prefer server-side sessions stored in Redis when immediate revocation matters more than statelessness.

  • Never store JWTs in localStorage if XSS is a risk surface
  • Use HTTPS everywhere tokens transit the network
  • Blacklist compromised tokens until expiry when using JWT
import jwt from 'jsonwebtoken';
const token = jwt.sign({ sub: user.id }, process.env.JWT_SECRET!, { expiresIn: '15m' });
const payload = jwt.verify(token, process.env.JWT_SECRET!);

HTTP Hardening and Validation

helmet sets security headers. cors configures cross-origin access explicitly. express-rate-limit protects expensive endpoints.

Validate and sanitize all inputs with schema libraries. Parameterized queries prevent SQL injection; encode output in HTML contexts to mitigate XSS in SSR apps.

Keep dependencies updated and run npm audit in CI. Subscribe to security advisories for frameworks you use.

  • Disable x-powered-by header leakage
  • Use CSRF protection for cookie-based session forms
  • Run periodic penetration tests on public APIs

Get In Touch


Ready to discuss your next project? Drop me a message.