nest-common
@tsdevstack/nest-common is the shared NestJS library for tsdevstack projects. It provides authentication, secrets management, Redis, observability, rate limiting, notifications, background jobs, service-to-service communication, and database utilities — all configured to work across GCP, AWS, and Azure.
Pre-installed in all NestJS service templates — no separate setup needed.
Quick start
A typical AppModule imports the modules you need:
All modules are global — import once in AppModule and they're available everywhere.
Modules overview
Bootstrap
startApp()
Standard app entry point. Handles environment loading, global prefix, URL versioning, Helmet, compression, validation, and Swagger.
startApp reads service metadata from package.json, loads framework config, and starts the app on 0.0.0.0:{port}. Swagger docs are served at /api in non-production environments.
startWorker()
Worker entry point for background job processors. Creates a NestJS application context without an HTTP server.
Features:
- Health endpoint at
GET /healthon port 8080 (configurable) - Graceful shutdown with 9-second timeout
- SIGTERM/SIGINT signal handlers
Authentication
AuthModule provides gateway-integrated authentication. Kong validates tokens at the gateway level, and AuthGuard (registered globally with APP_GUARD in every generated service) verifies that the request came through Kong, then reads the identity Kong set.
Decorators
RolesGuard and ROLES_KEY (the metadata key @Roles() sets) are exported for custom decorators.
Requests are classified trust first: identity headers only count when the Kong trust token (X-Kong-Trust) is valid. Without it, the caller is an internal service with the service API_KEY, an anonymous caller on a @Public() handler, or rejected with 401. Details in Protected Routes.
Types
KongHeaders lists the header names AuthGuard reads. The X-JWT-Claim-* headers are no longer read, and KongHeaders.JWT_CLAIM_PREFIX was removed; read claims from req.user instead.
For deeper coverage, see Authentication Overview.
Secrets
SecretsModule provides unified secret access across all cloud providers. It auto-detects the provider from the SECRETS_PROVIDER environment variable.
Always use SecretsService — never process.env. The secrets system handles provider detection, caching, and service-scoped access automatically.
Providers
Methods
Services read secrets. They don't write them, and their cloud identities have read access only. Change local secrets in .secrets.user.json and run npx tsdevstack generate-secrets. Set cloud secrets with npx tsdevstack cloud-secrets:set.
For deeper coverage, see How Secrets Work.
Redis
RedisModule provides a global Redis client with automatic configuration from secrets.
Methods
onReady is useful for rebuilding data that a Redis restart wiped. A listener added after the first connect is not called for it, so check isReady() when you subscribe if the current state matters.
Configuration
Reads from secrets automatically:
Connection: 10s connect timeout, 30s keep-alive. After a lost connection the client reconnects forever, with exponential backoff capped at 5 seconds, so a Redis restart or failover of any length is survived without restarting the service. While disconnected, commands fail immediately instead of queueing; get returns null and the rate limit guards fail open.
API key index
The gateway checks partner API keys against records in Redis. The auth-service template writes them; projects that manage keys with their own tooling can use the same contract from code instead of re-implementing it:
The record format, key names and TTL rules are a public, versioned contract, documented in API Keys.
Background jobs
BullConfigModule
Configures BullMQ with Redis from SecretsService. Portable across all providers.
Default job options: 3 retries with exponential backoff, keep 100 completed / 500 failed jobs.
SchedulerGuard
Validates that requests to scheduled job endpoints come from the cloud scheduler (not arbitrary HTTP clients).
Validation is provider-aware:
Service-to-service communication
BaseServiceClient
Abstract base class for typed HTTP clients. Use with generated clients from generate-client.
A call gives up after 30 seconds (axios itself has no timeout). For a slower endpoint, pass your own: new Api({ baseURL: url, timeout: 120_000, ... }).
filterForwardHeaders()
Filters request headers for safe forwarding in service-to-service calls. Removes hop-by-hop headers (connection, keep-alive, transfer-encoding, host, content-length, content-encoding).
Rate limiting
General rate limiting
Redis-backed rate limiting with configurable key generators.
Each route has its own counter, keyed by service, controller and handler. A decorator on a controller class limits each of its routes separately. Windows are fixed: a window starts at a multiple of windowMs, not at the first request.
Options
Key generators:
ip: the client IP. Behind the gateway, this isX-Tsdevstack-Real-IP, which Kong sets to the client's address (or to the visitor's address for calls the Next.js frontend makes, see Client addresses). For direct calls to the service, it is the socket address.X-Forwarded-Foris never read.userId: the logged-in user's id. Partner API key requests on dual-access endpoints are limited per key id instead. Anything else gets 401.apiKey: partner key requests per key id, internal service calls per (hashed) service key, everyone else per IP.custom: the key yourcustomKeyGeneratorreturns, used as is. Routes that return the same key share one counter.
Fail-open: if Redis is unavailable, requests are allowed through.
Email rate limiting
Per-email address rate limiting for auth flows (signup, password reset, verification). Each route has its own counter and a fixed window, like the general limiter.
Notifications
NotificationModule provides email sending with automatic provider selection.
Email providers
Provider is selected by the EMAIL_PROVIDER secret. For production setup (account creation, domain verification, DNS records), see Resend setup.
Custom email provider
You can replace Resend with SendGrid, Mailgun, Postmark, or any other provider by implementing the EmailProvider interface and overriding the EMAIL_PROVIDER token. See Custom Email Provider for a full walkthrough.
Storage
StorageModule provides unified object storage across all cloud providers. The same code works on local RustFS, AWS S3, GCP Cloud Storage, and Azure Blob Storage.
Use @InjectStorage to get a StorageProvider for a specific bucket:
Methods
Provider selection
The adapter is selected automatically from the SECRETS_PROVIDER environment variable:
Never install @aws-sdk/client-s3, @google-cloud/storage, or @azure/storage-blob directly — StorageModule handles all provider SDKs internally.
For setup instructions, bucket naming, secrets, and cloud deployment details, see Object Storage.
Messaging
MessagingModule provides inter-service event broadcasting via Redis Streams. Services publish events to topics, and all subscribing services receive every message independently.
MessagingModule.forRoot() options
forRootAsync is available as an escape hatch for dynamic configuration.
Publishing-only services (no subscriptions) omit topics:
Publishing
publish() returns the Redis stream entry ID.
Subscribing — @OnMessage decorator
Handler contract:
- Handler returns (resolves) → message is XACK'd
- Handler throws → message stays pending, will be retried
- After
maxRetriesattempts → message moves to DLQ stream
IncomingMessage
Error handling
Graceful shutdown
On SIGTERM/SIGINT, the module stops accepting new messages, waits for in-flight handlers to complete (5s timeout), and disconnects. Pending messages are reclaimed by another instance or retried on next startup.
For topic management, naming conventions, and flow diagrams, see Async Messaging.
Observability
ObservabilityModule bundles structured logging, Prometheus metrics, distributed tracing, and health checks into a single import.
This enables:
- Logging: Structured JSON via Pino with PII redaction and trace context
- Metrics: Prometheus at
/metricswith automatic HTTP request tracking - Tracing: One OpenTelemetry trace per request, through generated clients, BullMQ jobs, messages and Prisma queries, sent by
@tsdevstack/telemetryto the cloud's trace service (Jaeger locally) - Health:
/healthendpoint with Redis and memory checks
For configuration and custom metrics, see Observability. For traces in the cloud and your own spans, see Traces and Dashboards.
Database
createPrismaConnection()
Creates a Prisma client with connection pooling optimized for containers.
The service templates use it in PrismaService:
Uses Prisma 7 with the pg adapter. In production (NODE_ENV=production) it stops at once when DATABASE_URL or DB_POOL_MAX is missing, so a service never tries a local address in the cloud. Each cloud deploy sets both.
waitForDatabase()
Waits until the database answers SELECT 1. It retries with backoff (0.5 s, doubling to 5 s) for up to 60 seconds; pass { timeoutMs } to change the limit. Called from onModuleInit, it holds the service back from listening until the database is ready, so the platform's startup probe passes only when the service can serve requests. Each failed attempt logs a warning. If the deadline passes, startup fails and the platform restarts the instance.
Only startup waits. /health never checks the database, so a database outage does not restart instances.
Existing services add the onModuleInit method above to their PrismaService.
Pool sizing
In local development, the pool defaults to 5 connections.
In cloud environments, the framework automatically calculates DB_POOL_MAX at deploy time based on:
- The database tier's connection limit (e.g.,
db-f1-micro= 25 connections on GCP) - 10% reserved for admin/migrations
- Remaining connections split evenly across all service + worker instances (using
maxInstancesfrominfrastructure.json)
You never set DB_POOL_MAX manually: it's injected as an environment variable during deployment. If the result is one connection per instance, the deploy warns; pick a larger database tier or a lower maxInstances.
The split counts the services and workers in the project's config. Adding or removing one, or changing a maxInstances, changes every share, and the running services get their new number at the next infra:deploy. After infra:remove-service, the other services keep the share that counted the removed one until remove-service and infra:deploy have run. That is safe: their pools are smaller than they could be, never larger.
Connection options
- SSL for AWS RDS (
rejectUnauthorized: false) - 10-second connection timeout
- Idle connections close after 10 minutes, but one stays open (
min: 1) - Connections are recycled after 30 minutes
- TCP keepalive from 30 seconds idle, so a dead connection is noticed
Health checks
The health system is included in ObservabilityModule. It exposes two endpoints:
Response format
Status values: ok, degraded, down. When Redis is disconnected, the Redis check reports down and the overall status is degraded; the endpoint still answers HTTP 200, so the service is not restarted over a Redis outage, but monitoring that reads the body will see it.
Health indicators
/health does not check the database. It is the liveness check, and platforms restart instances on it. Database readiness is handled at startup instead (see waitForDatabase()).
Health and metrics endpoints are @Public() and excluded from API docs. They bypass Kong's trust header so load balancers and monitoring systems can access them directly.