NestJS: designing REST API for SaaS

NestJS: designing REST API for SaaS

NestJS gives structure but won’t save you from god services or inconsistent APIs. These patterns scale from MVP to dozens of modules.

NestJS: designing REST API for SaaS
Иллюстрация к материалу

Module boundaries

One bounded context = one module (shop, auth, courses). Shared folder — utils only, no business logic.

  • Controller — HTTP; Service — use cases; Model — persistence
  • Cross-module via public service or events

DTO and validation

  • class-validator on all inputs
  • Unified error shape { statusCode, message, errors[] }
  • Whitelist + forbidNonWhitelisted

Auth and multi-tenant

  • JwtAuthGuard + RolesGuard + OptionalJwt for guest checkout
  • tenantId from JWT, never from body
  • Admin under /admin prefix
NestJS: designing REST API for SaaS
Workflow diagram

Pagination

Cursor pagination for feeds; offset only for small admin lists.

Checklist

  • OpenAPI up to date
  • Idempotency-Key on payments
  • Health/readiness probes
  • Version /api/v1 on breaking changes

Taming a god service

  • Draw module import graph — cycles show up fast
  • Extract shared logic behind a explicit public API
  • Split one module per sprint; keep controllers stable
  • Add one e2e per critical flow after each split