Configuration Documentation
This documentation explains the features and usage of Config Module: Located at src/configs
Overview
This document provides a detailed explanation of how configuration works in the Complete NestJS Boilerplate project, including the configuration files structure and their interfaces.
The project uses a modular configuration approach through the NestJS ConfigModule. Configuration is split into multiple dedicated files for different aspects of the application, making it easier to maintain and understand.
Related Documents
- Environment Documentation - For detailed environment variable configuration and validation
- Database Documentation - For database configuration usage
- Cache Documentation - For Redis configuration usage
Table of Contents
- Overview
- Related Documents
- Configuration Principles
- Configuration Structure
- App Configuration
- Auth Configuration
- Database Configuration
- AWS Configuration
- Logger Configuration
- Request Configuration
- Redis Configuration
- User Configuration
- Documentation Configuration
- Message Configuration
- Email Configuration
- Verification Configuration
- Forgot Password Configuration
- Home Configuration
- Session Configuration
- Term Policy Configuration
- Feature Flag Configuration
- Response Configuration
- Conclusion
Configuration Structure
All configuration files are located in the src/configs directory. Each configuration module uses the registerAs function from @nestjs/config and provides a TypeScript interface for type safety.
The configuration modules are imported and registered in src/configs/index.ts as an array and this configuration array is then loaded in src/common/common.module.ts:
@Module({
imports: [
ConfigModule.forRoot({
load: configs,
isGlobal: true,
cache: true,
envFilePath: ['.env', `.env.${process.env.NODE_ENV ?? 'local'}`],
expandVariables: false,
}),
// ... other modules
],
})
export class CommonModule {}App Configuration
File: src/configs/app.config.ts
Interface: IConfigApp
This configuration handles the core application settings including environment details, versioning, and server configuration.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
name - Application name used throughout the system
name: stringenv - Current environment (development, production, staging, local)
env: EnumAppEnvironmenttimezone - Default timezone for date operations
timezone: stringversion - Application version from package.json
version: stringauthor - Author information from package.json
author: {
name: string; // Author name
email: string; // Author email
}url - Repository URL from package.json
url: stringglobalPrefix - Global API prefix (default: ‘/api’)
globalPrefix: stringhttp - HTTP server configuration
http: {
host: string; // Server host address
port: number; // Server port number
}urlVersion - API versioning configuration
urlVersion: {
enable: boolean; // Enable URL versioning
prefix: string; // Version prefix (default: 'v')
version: string; // Default API version
}Auth Configuration
File: src/configs/auth.config.ts
Interface: IConfigAuth
This configuration manages JWT authentication settings including token configuration, password policies, social authentication, dan two-factor authentication.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
jwt - JWT authentication configuration
jwt: {
accessToken: {
jwksUri: string; // JWKS URI for access token
kid: string; // Key ID for access token
algorithm: Algorithm; // JWT algorithm (ES256, ES512, etc.)
privateKey: string; // Private key for token signing
publicKey: string; // Public key for token verification
expirationTimeInSeconds: number; // Token expiration in seconds
};
refreshToken: {
jwksUri: string; // JWKS URI for refresh token
kid: string; // Key ID for refresh token
algorithm: Algorithm; // JWT algorithm
privateKey: string; // Private key for token signing
publicKey: string; // Public key for token verification
expirationTimeInSeconds: number; // Token expiration in seconds
};
audience: string; // JWT audience claim
issuer: string; // JWT issuer claim
header: string; // HTTP header for JWT (default: 'Authorization')
prefix: string; // Token prefix (default: 'Bearer')
}password - Password policy configuration
password: {
attempt: boolean; // Enable login attempt tracking
maxAttempt: number; // Maximum failed login attempts
saltLength: number; // Salt length for password hashing
expiredInSeconds: number; // Password expiration time
expiredTemporaryInSeconds: number; // Temporary password expiration
periodInSeconds: number; // Password renewal period
}twoFactor - Two-factor authentication configuration
twoFactor: {
issuer: string; // Issuer name for OTP (TOTP)
digits: number; // Number of digits in OTP
step: number; // Time step in seconds for OTP validity
window: number; // Allowed window for OTP validation
secretLength: number; // Length of OTP secret
challengeTtlInMs: number; // Challenge TTL in milliseconds
cachePrefixKey: string; // Cache prefix for two-factor data
backupCodes: {
count: number; // Number of backup codes
length: number; // Length of each backup code
};
encryption: {
key: string; // Encryption key for backup codes
};
}apple - Apple OAuth configuration
apple: {
header: string; // HTTP header for Apple auth
prefix: string; // Token prefix for Apple auth
clientId?: string; // Apple OAuth client ID
signInClientId?: string; // Apple Sign In client ID
}google - Google OAuth configuration
google: {
header: string; // HTTP header for Google auth
prefix: string; // Token prefix for Google auth
clientId?: string; // Google OAuth client ID
clientSecret?: string; // Google OAuth client secret
}xApiKey - API Key authentication configuration
xApiKey: {
header: string; // HTTP header for API key
cachePrefixKey: string; // Cache prefix for API keys
}Database Configuration
File: src/configs/database.config.ts
Interface: IConfigDatabase
This configuration manages database connection settings for MongoDB.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
url - Database connection string
url: string // MongoDB connection URLdebug - Database debug mode
debug: boolean // Enable/disable database query loggingAWS Configuration
File: src/configs/aws.config.ts
Interface: IConfigAws
This configuration handles AWS service integration including S3 and SES services with support for IAM role-based authentication.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
s3 - S3 service configuration
s3: {
multipartExpiredInDay: number; // Multipart upload expiration in days (default: 3)
presignExpired: number; // Presigned URL expiration time in seconds (default: 1800)
maxAttempts: number; // Maximum retry attempts for S3 operations (default: 3)
timeoutInMs: number; // Request timeout in milliseconds (default: 30000ms)
region?: string; // AWS region for S3
iam: {
key?: string; // AWS IAM access key ID
secret?: string; // AWS IAM secret access key
arn?: string; // AWS IAM Role ARN for role-based access
};
config: {
public: {
bucket?: string; // Public S3 bucket name
arn?: string; // Public S3 bucket ARN
baseUrl?: string; // S3 base URL (auto-generated)
cdnUrl?: string; // CDN URL if available
};
private: {
bucket?: string; // Private S3 bucket name
arn?: string; // Private S3 bucket ARN
baseUrl?: string; // S3 base URL (auto-generated)
cdnUrl?: string; // CDN URL if available
};
};
}IAM Configuration Notes:
- The
iam.keyandiam.secretare used for standard IAM user credentials- The
iam.arnis used for IAM role assumption (recommended for production)- When using IAM roles, temporary credentials are automatically rotated
- Bucket ARNs are auto-generated as
arn:aws:s3:::{bucket-name}- Base URLs are auto-generated as
https://{bucket}.s3.{region}.amazonaws.com
ses - Simple Email Service configuration
ses: {
iam: {
key?: string; // AWS IAM access key ID for SES
secret?: string; // AWS IAM secret access key for SES
arn?: string; // AWS IAM Role ARN for SES operations
};
region?: string; // AWS region for SES
}SES IAM Configuration:
- Similar to S3, SES supports both standard credentials and IAM role-based access
- Using IAM roles (
iam.arn) is recommended for better security- Credentials are used for sending emails and managing SES operations
Logger Configuration
File: src/configs/logger.config.ts
Interface: IConfigDebug
This configuration manages logging settings using Pino logger with customizable log levels and formatting.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
enable - Enable/disable logging
enable: boolean // Turn logging on/offlevel - Log level configuration
level: string // Log levels: silent, trace, debug, info, warn, error, fatalintoFile - File logging option
intoFile: boolean // Whether to write logs to filesfilePath - Log file directory
filePath: string // Directory path for log filesauto - Automatic logging features
auto: boolean // Enable automatic request/response loggingprettier - Log formatting option
prettier: boolean // Format logs for better readabilitysentry - Sentry integration configuration
sentry: {
dsn?: string; // Sentry DSN for error tracking
timeout: number; // Sentry timeout in milliseconds
}Request Configuration
File: src/configs/request.config.ts
Interface: IConfigRequest
This configuration handles HTTP request settings including body size limits, CORS, and rate limiting.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
body - Request body size limits
body: {
json: {
limitInBytes: number; // Maximum JSON request size (default: 500kb)
};
text: {
limitInBytes: number; // Maximum text request size (default: 1mb)
};
urlencoded: {
limitInBytes: number; // Maximum URL-encoded request size (default: 1mb)
};
applicationOctetStream: {
limitInBytes: number; // Maximum octet-stream size (from FileSizeInBytes constant)
};
}timeoutInMs - Request timeout setting
timeoutInMs: number // Request timeout in milliseconds (default: 30000ms)cors - CORS configuration
cors: {
allowedMethod: string[]; // Allowed HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)
allowedOrigin: string[]; // Allowed origins (from CORS_ALLOWED_ORIGIN env variable, supports subdomain wildcards)
allowedHeader: string[]; // Allowed headers for CORS requests
}CORS Configuration Notes:
allowedOriginis populated fromCORS_ALLOWED_ORIGINenvironment variable- Multiple origins can be specified using comma separation
- Subdomain wildcards are supported (e.g.,
*.example.com)- Default headers include standard headers plus custom headers like
x-api-key,x-timezone, etc.
throttle - Rate limiting configuration
throttle: {
ttlInMs: number; // Time window in milliseconds (default: 500ms)
limit: number; // Maximum requests per time window (default: 10)
}Redis Configuration
File: src/configs/redis.config.ts
Interface: IConfigRedis
This configuration manages Redis connection settings for caching and queue operations.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
cache - Cache Redis configuration
cache: {
url: string; // Redis URL for caching
namespace: string; // Cache namespace prefix
ttlInMs: number; // Cache TTL in milliseconds
}queue - Queue Redis configuration
queue: {
url: string; // Redis URL for queues
namespace: string; // Queue namespace prefix
}User Configuration
File: src/configs/user.config.ts
Interface: IUserConfig
This configuration handles user-related settings including username patterns and file upload paths.
Configuration Keys:
usernamePrefix - Username generation prefix
usernamePrefix: string // Prefix for auto-generated usernames (default: 'user')usernamePattern - Username validation pattern
usernamePattern: RegExp // Regex pattern for valid usernamesuploadPhotoProfilePath - User profile photo upload path template
uploadPhotoProfilePath: string // Path template for user profile photo uploadsDocumentation Configuration
File: src/configs/doc.config.ts
Interface: IConfigDoc
This configuration manages API documentation settings for Swagger/OpenAPI.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
name - Documentation title
name: string // API documentation titledescription - Documentation description
description: string // API documentation descriptionprefix - Documentation URL prefix
prefix: string // URL prefix for API documentation (default: '/docs')version - Static Swagger version
version: string // Static version for Swagger documentation (default: '3.1.0')Message Configuration
File: src/configs/message.config.ts
Interface: IConfigMessage
This configuration handles application messaging and internationalization settings.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
availableLanguage - Supported languages
availableLanguage: string[] // List of supported language codeslanguage - Default language
language: string // Default application languageEmail Configuration
File: src/configs/email.config.ts
Interface: IConfigEmail
This configuration manages default email addresses for system communications.
Configuration Keys:
noreply - No-reply email address
noreply: string // No-reply email address for system emailssupport - Support email address
support: string // Support/contact email addressadmin - Admin email address
admin: string // Administrator email addressVerification Configuration
File: src/configs/verification.config.ts
Interface: IConfigVerification
This configuration handles user verification processes including email verification.
Configuration Keys:
expiredInMinutes - Verification expiration time
expiredInMinutes: number // Verification expiration time in minutesotpLength - OTP code length
otpLength: number // Length of OTP verification codetokenLength - Verification token length
tokenLength: number // Length of verification tokenlinkBaseUrl - Verification link base URL
linkBaseUrl: string // Base URL for verification linksresendInMinutes - Resend cooldown period
resendInMinutes: number // Minimum time between resend attemptsreference - Verification reference configuration
reference: {
prefix: string; // Prefix for verification references
length: number; // Length of verification reference ID
}Forgot Password Configuration
File: src/configs/forgot-password.config.ts
Interface: IConfigForgotPassword
This configuration manages password reset functionality and security policies.
Configuration Keys:
expiredInMinutes - Reset link expiration
expiredInMinutes: number // Password reset expiration in minutestokenLength - Reset token length
tokenLength: number // Length of password reset tokenlinkBaseUrl - Reset link base URL
linkBaseUrl: string // Base URL for password reset linksresendInMinutes - Resend cooldown period
resendInMinutes: number // Minimum time between resend attemptsreference - Reset reference configuration
reference: {
prefix: string; // Prefix for reset references
length: number; // Length of reset reference ID
}Home Configuration
File: src/configs/home.config.ts
Interface: IConfigHome
This configuration handles home page and organization information.
Environment Variables: See Environment Documentation for detailed environment variable configuration.
Configuration Keys:
name - Organization/application name
name: string // Display name for organization/applicationurl - Organization/home URL
url: string // URL for organization/home pageSession Configuration
File: src/configs/session.config.ts
Interface: IConfigSession
This configuration manages user session key patterns for Redis storage.
Configuration Keys:
keyPattern - Session key pattern
keyPattern: string // Redis key pattern for user sessionsTerm Policy Configuration
File: src/configs/term-policy.config.ts
Interface: IConfigTermPolicy
This configuration handles terms of service and privacy policy file management.
Configuration Keys:
uploadContentPath - Upload path pattern for policy content
uploadContentPath: string // Path pattern for uploading policy content filescontentPublicPath - Public path for policy content
contentPublicPath: string // Public path for accessing policy contentfilenamePattern - Filename pattern for policy files
filenamePattern: string // Pattern for policy file namesFeature Flag Configuration
File: src/configs/feature-flag.config.ts
Interface: IConfigFeatureFlag
This configuration manages feature flag caching settings.
Configuration Keys:
cachePrefixKey - Cache prefix for feature flags
cachePrefixKey: string // Redis cache prefix for feature flag datacacheTtlMs - Cache TTL for feature flags
cacheTtlMs: number // Cache TTL in milliseconds for feature flag dataResponse Configuration
File: src/configs/response.config.ts
Interface: IConfigRequest (Note: Interface name appears to be incorrect in the source file)
This configuration handles API response caching settings.
Configuration Keys:
cachePrefix - Cache prefix for API responses
cachePrefix: string // Cache prefix for API response data