API Reference

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
1import { createApp } from '@morojs/moro';
2
3// Simple configuration (actual implementation)
4const app = await 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
1// Environment-specific configuration
2const app = await 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
1import {
2  createApp, getConfig, getEnvVar, getEnvJson, requireEnvVars
3} from '@morojs/moro';
4
5// createApp() loads moro.config.js/ts and merges it with environment
6// variables, explicit options and defaults — that is why it is async.
7const app = await createApp({
8  server: { port: 3000 }
9});
10
11// Fail fast on anything mandatory
12requireEnvVars(['DATABASE_URL', 'JWT_SECRET']);
13
14// Typed environment access with defaults
15const port = getEnvVar('PORT', 3000, Number);
16const logLevel = getEnvVar('LOG_LEVEL', 'info');
17const featureFlags = getEnvJson('FEATURE_FLAGS', {});
18
19// The resolved, locked configuration
20const config = getConfig();

Runtime Configuration

Reading Configuration
1import {
2  createApp, getConfigValue, isConfigInitialized, resetConfig
3} from '@morojs/moro';
4
5const app = await createApp();
6
7// The whole resolved configuration
8const config = app.getConfig();
9const dbUrl = config.database?.url;
10
11// Or read a single value by dotted path, with a fallback
12const poolMax = getConfigValue('database.pool.max', 10);
13
14// Useful in tests
15isConfigInitialized(); // true once createApp() has run
16resetConfig();         // clears the locked config between test cases

Configuration is resolved once, then locked

  • createApp() merges moro.config.js/ts, environment variables, explicit options and defaults, then locks the result
  • There is no runtime reconfiguration — pass what you need to createApp() up front
  • There is no config file watcher; restart the process to pick up changes
  • getConfig() takes no arguments and returns the whole object — reach into it, or use getConfigValue() for a dotted path
Multi-Runtime Configuration
1// Node.js configuration
2const nodeApp = await 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
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}

MoroJS validates configuration at startup and provides helpful error messages:

Configuration Validation

  • Type checking for all configuration values
  • Required field validation
  • Range and format validation (ports, URLs, etc.)
  • Environment variable resolution
  • Circular dependency detection

Next Steps