Skip to content

NestJS Authentication

Authentication proves who a user is before authorization decides what they can do. This lesson outlines NestJS auth architecture and the pieces you will combine in later lessons.

Authentication Building Blocks in Nest

A Nest auth system usually includes: credential verification (login), token or session issuance, an auth guard that protects routes, and optionally Passport strategies for JWT, local login, or OAuth providers.

Keep auth logic in an AuthModule with an AuthService for login/register and guards/strategies as providers, rather than scattering checks across controllers.

@Module({
  imports: [UsersModule, PassportModule, JwtModule.register({ secret: process.env.JWT_SECRET })],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  controllers: [AuthController],
})
export class AuthModule {}

This module shape is the standard Nest Passport + JWT setup you will flesh out in the next lessons.

Login Flow Overview

POST /auth/login
  -> validate email/password
  -> issue access token (and optionally refresh token)
  -> client sends Authorization: Bearer <token>
  -> JwtAuthGuard verifies token on protected routes
  • Hash passwords with bcrypt (or argon2); never store plaintext.
  • Separate authentication (identity) from authorization (roles/permissions).
  • Prefer short-lived access tokens plus refresh tokens for SPA/mobile clients.
  • Keep secrets in environment variables via ConfigModule.

Auth Concepts Cheatsheet

Core ideas before you implement Passport/JWT.

Concept Meaning
Authentication Prove identity (login / token verification)
Authorization Allow or deny actions (roles / permissions)
Strategy Passport plug-in that validates credentials
Guard Nest layer that blocks unauthenticated requests
Session auth Server stores session; cookie identifies user
Token auth Client stores token; server verifies signature

Sessions vs JWT

Cookie sessions excel for first-party browser apps with server-rendered pages. JWTs excel for SPAs, mobile clients, and microservices that need stateless verification. Many Nest APIs use JWT; many Nest web apps still use sessions or hybrid approaches.

Register and Login Responsibilities

Registration creates a user with a hashed password. Login verifies credentials and returns tokens or sets a session. Never return password hashes in API responses.

  • Validate email uniqueness before insert.
  • Return 401 for bad credentials without revealing which field failed.
  • Rate-limit login endpoints to slow brute force attacks.

Common Mistakes

  • Storing JWTs in localStorage without considering XSS risk (httpOnly cookies are often safer for browsers).
  • Using the same secret across environments or committing secrets to git.
  • Putting authorization role checks inside login instead of a dedicated RolesGuard.
  • Skipping password hashing "just for the prototype" and never fixing it.

Key Takeaways

  • Nest auth centers on AuthModule, strategies, guards, and secure credential storage.
  • Authentication and authorization are separate concerns.
  • JWT and sessions are both valid; pick based on client architecture.
  • Keep secrets and token lifetimes under configuration control.

Pro Tip

Design your AuthController endpoints (/login, /register, /refresh, /logout) first as a contract, then implement strategies behind them so frontend and backend can progress in parallel.