Configuration API Reference
Complete reference for MoroJS configuration system. Learn about app configuration, environment management, and runtime settings.
Application Configuration
Configure your MoroJS application with type-safe options for server, security, database, and feature settings.
Actual Configuration Object
typescript
1import { createApp } from '@morojs/moro';
2
3// Simple configuration (actual implementation)
4const app = createApp({
5 cors: true, // Enable CORS with defaults
6 compression: true, // Enable gzip compression
7 helmet: true // Enable security headers
8});
9
10// Example from feature-showcase showing configuration access
11app.get('/config', (req, res) => {
12 const config = app.getConfig();
13 return {
14 success: true,
15 data: {
16 environment: config.server.environment,
17 server: {
18 port: config.server.port,
19 host: config.server.host,
20 maxConnections: config.server.maxConnections
21 },
22 modules: {
23 cache: {
24 enabled: config.modules.cache.enabled,
25 defaultTtl: config.modules.cache.defaultTtl,
26 maxSize: config.modules.cache.maxSize,
27 strategy: config.modules.cache.strategy
28 },
29 rateLimit: {
30 enabled: config.modules.rateLimit.enabled,
31 defaultRequests: config.modules.rateLimit.defaultRequests,
32 defaultWindow: config.modules.rateLimit.defaultWindow
33 }
34 },
35 security: {
36 cors: config.security.cors,
37 helmet: config.security.helmet
38 },
39 logging: {
40 level: config.logging.level,
41 format: config.logging.format,
42 enableColors: config.logging.enableColors
43 }
44 }
45 };
46});
47
48// Configuration-driven features
49app.post('/users-config')
50 .rateLimit({
51 requests: app.getConfig().modules.rateLimit.defaultRequests,
52 window: app.getConfig().modules.rateLimit.defaultWindow
53 })
54 .cache({ ttl: app.getConfig().modules.cache.defaultTtl })
55 .handler((req, res) => {
56 const config = app.getConfig();
57 return {
58 success: true,
59 environment: config.server.environment,
60 message: 'Created with configuration-driven settings'
61 };
62 });
Type Safety
All configuration options are fully typed with TypeScript, providing autocomplete and compile-time validation.
Environment Support
Configuration automatically adapts to different environments (development, staging, production).
Environment Management
Environment Configuration
typescript
1// Environment-specific configuration
2const app = createApp({
3 server: {
4 port: process.env.PORT || 3000,
5 environment: process.env.NODE_ENV || 'development'
6 },
7
8 // Environment-based database config
9 database: {
10 default: {
11 url: process.env.NODE_ENV === 'production'
12 ? process.env.DATABASE_URL
13 : 'postgresql://localhost:5432/myapp_dev',
14 pool: {
15 min: process.env.NODE_ENV === 'production' ? 5 : 2,
16 max: process.env.NODE_ENV === 'production' ? 20 : 5
17 }
18 }
19 },
20
21 // Environment-based logging
22 logging: {
23 level: process.env.NODE_ENV === 'production' ? 'warn' : 'debug',
24 format: process.env.NODE_ENV === 'production' ? 'json' : 'pretty'
25 }
26});
27
28// Environment variable validation
29app.env({
30 // Required variables
31 DATABASE_URL: { required: true },
32 JWT_SECRET: { required: true, minLength: 32 },
33
34 // Optional with defaults
35 REDIS_URL: { default: 'redis://localhost:6379' },
36 LOG_LEVEL: { default: 'info', enum: ['debug', 'info', 'warn', 'error'] },
37
38 // Type validation
39 MAX_UPLOAD_SIZE: { type: 'number', default: 10485760 }, // 10MB
40 ENABLE_WEBSOCKETS: { type: 'boolean', default: true }
41});
Configuration Loading
typescript
1// Load from .env files
2import { loadConfig } from '@morojs/moro/config';
3
4const config = loadConfig({
5 // Load order (later files override earlier ones)
6 files: [
7 '.env',
8 '.env.local',
9 `.env.${process.env.NODE_ENV}`,
10 `.env.${process.env.NODE_ENV}.local`
11 ],
12
13 // Schema validation
14 schema: {
15 PORT: { type: 'number', default: 3000 },
16 DATABASE_URL: { required: true },
17 JWT_SECRET: { required: true, minLength: 32 }
18 }
19});
20
21const app = createApp(config);
22
23// Access environment variables
24const dbUrl = app.env('DATABASE_URL');
25const jwtSecret = app.env('JWT_SECRET');
26
27// Type-safe environment access
28interface AppEnv {
29 DATABASE_URL: string;
30 JWT_SECRET: string;
31 REDIS_URL?: string;
32 LOG_LEVEL?: 'debug' | 'info' | 'warn' | 'error';
33}
34
35const typedEnv = app.env<AppEnv>();
Runtime Configuration
Dynamic Configuration Methods
typescript
1const app = createApp();
2
3// Get current configuration
4const currentConfig = app.getConfig();
5
6// Update configuration at runtime
7app.configure({
8 rateLimit: {
9 max: 500,
10 window: '10m'
11 }
12});
13
14// Merge with existing configuration
15app.configure({
16 database: {
17 pool: {
18 max: 15 // Only updates pool.max, keeps other database settings
19 }
20 }
21}, { merge: true });
22
23// Get specific configuration section
24const dbConfig = app.getConfig('database');
25const securityConfig = app.getConfig('security');
26
27// Configuration validation
28app.validateConfig({
29 required: ['database.url', 'security.cors.origin'],
30 optional: ['logging.level', 'features.websockets']
31});
32
33// Configuration watchers (for config file changes)
34app.watchConfig('./config.json', (newConfig) => {
35 console.log('Configuration updated:', newConfig);
36 app.configure(newConfig);
37});
Multi-Runtime Configuration
typescript
1// Node.js configuration
2const nodeApp = createApp({
3 server: {
4 port: 3000,
5 host: '0.0.0.0',
6 keepAlive: true,
7 bodyLimit: '50MB'
8 },
9 features: {
10 fileSystem: true,
11 clustering: true
12 }
13});
14
15// Vercel Edge configuration
16const edgeApp = moroEdge({
17 runtime: 'edge',
18 features: {
19 fileSystem: false,
20 streaming: true
21 },
22 limits: {
23 memory: '128MB',
24 duration: '30s'
25 }
26});
27
28// AWS Lambda configuration
29const lambdaApp = moroLambda({
30 runtime: 'lambda',
31 timeout: 30000,
32 memorySize: 512,
33 features: {
34 coldStart: true,
35 streaming: false
36 }
37});
38
39// Cloudflare Workers configuration
40const workerApp = moroWorker({
41 runtime: 'worker',
42 features: {
43 kv: true,
44 durable: true
45 },
46 limits: {
47 cpu: '10ms',
48 memory: '128MB'
49 }
50});
Configuration Schema
TypeScript Configuration Interface
typescript
1interface MoroConfig {
2 server?: {
3 port?: number;
4 host?: string;
5 environment?: 'development' | 'staging' | 'production';
6 gracefulShutdown?: {
7 timeout?: number;
8 signals?: string[];
9 };
10 };
11
12 security?: {
13 cors?: {
14 origin?: string | string[];
15 credentials?: boolean;
16 methods?: string[];
17 headers?: string[];
18 };
19 helmet?: {
20 contentSecurityPolicy?: any;
21 hsts?: any;
22 };
23 rateLimit?: {
24 global?: { max: number; window: string };
25 api?: { max: number; window: string };
26 };
27 };
28
29 database?: {
30 default?: {
31 type?: 'postgresql' | 'mysql' | 'sqlite' | 'mongodb';
32 url?: string;
33 pool?: {
34 min?: number;
35 max?: number;
36 acquireTimeoutMillis?: number;
37 idleTimeoutMillis?: number;
38 };
39 migrations?: {
40 directory?: string;
41 autoRun?: boolean;
42 };
43 };
44 cache?: {
45 type?: 'redis' | 'memory' | 'file';
46 url?: string;
47 ttl?: string;
48 prefix?: string;
49 };
50 };
51
52 logging?: {
53 level?: 'debug' | 'info' | 'warn' | 'error';
54 format?: 'json' | 'pretty';
55 destinations?: Array<{
56 type: 'console' | 'file' | 'http';
57 path?: string;
58 url?: string;
59 }>;
60 };
61
62 features?: {
63 websockets?: boolean;
64 fileUploads?: {
65 enabled?: boolean;
66 maxSize?: string;
67 allowedTypes?: string[];
68 };
69 apiDocs?: {
70 enabled?: boolean;
71 path?: string;
72 title?: string;
73 };
74 };
75}
Configuration Validation
MoroJS validates configuration at startup and provides helpful error messages:
- • Type checking for all configuration values
- • Required field validation
- • Range and format validation (ports, URLs, etc.)
- • Environment variable resolution
- • Circular dependency detection