Comprehensive configuration system with type-safe interfaces, plugin management, and environment-specific settings for Egg.js applications.
Main configuration interface that defines all available configuration options for Egg.js applications.
/**
* Complete application configuration interface extending EggCore configuration
*/
interface EggAppConfig extends EggCoreAppConfig {
/** Worker startup timeout in milliseconds */
workerStartTimeout: number;
/** Application base directory */
baseDir: string;
/** Middleware execution order */
middleware: string[];
/** Core framework middleware */
coreMiddleware: string[];
/** Request body parser configuration */
bodyParser: BodyParserConfig;
/** Logger configuration */
logger: EggLoggerConfig;
/** Custom logger configurations */
customLogger: Record<string, EggLoggerOptions>;
/** HTTP client configuration */
httpclient: HttpClientConfig;
/** Configuration dump settings */
dump: DumpConfig;
/** Environment type */
env: EggEnvType;
/** Home directory */
HOME: string;
/** Host header name */
hostHeaders: string;
/** IP header name for proxy detection */
ipHeaders: string;
/** Protocol header name */
protocolHeaders: string;
/** Maximum proxy count */
maxProxyCount: number;
/** Maximum IPs count */
maxIpsCount: number;
/** Proxy mode enabled */
proxy: boolean;
/** Cookie configuration */
cookies: CookieConfig;
/** Cookie signing keys */
keys: string;
/** Application name */
name: string;
/** Package.json contents */
pkg: Record<string, any>;
/** Runtime directory */
rundir: string;
/** Site file middleware options */
siteFile: SiteFileMiddlewareOptions;
/** Meta middleware options */
meta: MetaMiddlewareOptions;
/** Not found middleware options */
notfound: NotFoundMiddlewareOptions;
/** Method override middleware options */
overrideMethod: OverrideMethodConfig;
/** Client error handler */
onClientError?(err: Error, socket: Socket, app: EggApplicationCore): ClientErrorResponse | Promise<ClientErrorResponse>;
/** Server timeout */
serverTimeout: number | null;
/** Cluster configuration */
cluster: ClusterConfig;
/** Cluster client configuration */
clusterClient: ClusterClientConfig;
/** Additional configuration properties */
[prop: string]: any;
}Usage Examples:
// config/config.default.ts
import { EggAppConfig, PowerPartial } from 'egg';
export default (): PowerPartial<EggAppConfig> => {
const config = {} as PowerPartial<EggAppConfig>;
// Basic application settings
config.name = 'my-egg-app';
config.keys = 'my-secret-key-for-cookie-signing';
// Worker configuration
config.workerStartTimeout = 10 * 60 * 1000; // 10 minutes
// Logger configuration
config.logger = {
level: 'INFO',
consoleLevel: 'INFO',
dir: path.join(appInfo.root, 'logs'),
allowDebugAtProd: false
};
// HTTP client configuration
config.httpclient = {
timeout: 60000,
request: {
headers: {
'User-Agent': 'MyApp/1.0.0'
}
}
};
return config;
};Configuration for request body parsing middleware.
interface BodyParserConfig {
/** Enable body parser */
enable: boolean;
/** Body encoding */
encoding: string;
/** Form data size limit */
formLimit: string;
/** JSON body size limit */
jsonLimit: string;
/** Text body size limit */
textLimit: string;
/** Strict JSON parsing */
strict: boolean;
/** Query string parsing options */
queryString: {
arrayLimit: number;
depth: number;
parameterLimit: number;
};
/** URL patterns to ignore */
ignore?: IgnoreOrMatch;
/** URL patterns to match */
match?: IgnoreOrMatch;
/** Enabled content types */
enableTypes?: string[];
/** Extended content type mappings */
extendTypes?: {
json: string[];
form: string[];
text: string[];
};
/** Prototype poisoning handling */
onProtoPoisoning: 'error' | 'remove' | 'ignore';
/** Error handler function */
onerror(err: any, ctx: Context): void;
}Usage Examples:
// Body parser configuration
config.bodyParser = {
enable: true,
encoding: 'utf8',
formLimit: '1mb',
jsonLimit: '1mb',
textLimit: '1mb',
strict: true,
queryString: {
arrayLimit: 100,
depth: 5,
parameterLimit: 1000
},
enableTypes: ['json', 'form', 'text'],
extendTypes: {
json: ['application/x-javascript'],
form: ['application/x-www-form-urlencoded'],
text: ['text/xml']
},
onProtoPoisoning: 'error',
onerror(err, ctx) {
ctx.throw(400, 'Body parse error: ' + err.message);
}
};Configuration for application and framework logging.
interface EggLoggerConfig extends Omit<EggLoggersOptions, 'type'> {
/** Custom core logger configuration */
coreLogger?: Partial<EggLoggerOptions>;
/** Allow debug logs in production */
allowDebugAtProd?: boolean;
/** Disable console output after app ready */
disableConsoleAfterReady?: boolean;
/** Enable performance timer logging */
enablePerformanceTimer?: boolean;
/** Use fast context logger implementation */
enableFastContextLogger?: boolean;
/** Log directory */
dir?: string;
/** Log encoding */
encoding?: string;
/** Log level */
level?: string;
/** Console log level */
consoleLevel?: string;
/** Output JSON format */
outputJSON?: boolean;
/** Buffer logs for performance */
buffer?: boolean;
/** Error log filename */
errorLogName?: string;
/** Core log filename */
coreLogName?: string;
/** Agent log filename */
agentLogName?: string;
}Usage Examples:
// Logger configuration
config.logger = {
level: 'INFO',
consoleLevel: 'INFO',
dir: path.join(appInfo.root, 'logs'),
encoding: 'utf8',
outputJSON: false,
buffer: true,
allowDebugAtProd: false,
disableConsoleAfterReady: true,
enableFastContextLogger: false,
coreLogger: {
level: 'WARN'
}
};
// Custom loggers
config.customLogger = {
apiLogger: {
file: path.join(appInfo.root, 'logs/api.log'),
level: 'INFO',
formatter: (meta) => `[${meta.date}] ${meta.level} ${meta.message}`
},
errorLogger: {
file: path.join(appInfo.root, 'logs/error.log'),
level: 'ERROR'
}
};Configuration system for managing Egg.js plugins.
interface EggPlugin {
/** Dynamic plugin configuration */
[key: string]: EggPluginItem | boolean | undefined;
/** Built-in plugins */
onerror?: EggPluginItem;
session?: EggPluginItem;
i18n?: EggPluginItem;
watcher?: EggPluginItem;
multipart?: EggPluginItem;
security?: EggPluginItem;
development?: EggPluginItem;
logrotator?: EggPluginItem;
schedule?: EggPluginItem;
static?: EggPluginItem;
jsonp?: EggPluginItem;
view?: EggPluginItem;
}
interface EggPluginItem {
/** Environments where plugin is enabled */
env?: EggEnvType[];
/** Plugin path (for local plugins) */
path?: string;
/** Plugin package name */
package?: string;
/** Enable/disable plugin */
enable?: boolean;
}Usage Examples:
// config/plugin.ts
import { EggPlugin } from 'egg';
const plugin: EggPlugin = {
// Built-in plugins
security: {
enable: true
},
session: {
enable: true
},
// Third-party plugins
mysql: {
enable: true,
package: 'egg-mysql'
},
redis: {
enable: true,
package: 'egg-redis',
env: ['prod', 'test'] // Only in specific environments
},
// Local plugin
customAuth: {
enable: true,
path: path.join(__dirname, '../lib/plugin/custom-auth')
},
// Disable built-in plugin
jsonp: {
enable: false
}
};
export default plugin;Environment-specific configuration management.
type EggEnvType = 'local' | 'unittest' | 'prod' | string;
interface EggAppInfo {
pkg: any;
name: string;
baseDir: string;
env: EggEnvType;
scope: string;
HOME: string;
root: string;
}Usage Examples:
// config/config.prod.ts - Production configuration
export default (): PowerPartial<EggAppConfig> => {
const config = {} as PowerPartial<EggAppConfig>;
config.logger = {
level: 'INFO',
consoleLevel: 'NONE', // No console output in production
disableConsoleAfterReady: true
};
config.httpclient = {
timeout: 30000 // Shorter timeout in production
};
return config;
};
// config/config.local.ts - Development configuration
export default (): PowerPartial<EggAppConfig> => {
const config = {} as PowerPartial<EggAppConfig>;
config.logger = {
level: 'DEBUG',
consoleLevel: 'DEBUG',
allowDebugAtProd: true
};
config.security = {
csrf: {
enable: false // Disable CSRF in development
}
};
return config;
};Helper types for configuration management.
/**
* Deep partial type for configuration overrides
*/
type PowerPartial<T> = {
[U in keyof T]?: T[U] extends object ? PowerPartial<T[U]> : T[U];
};
type IgnoreItem = string | RegExp | ((ctx: Context) => boolean);
type IgnoreOrMatch = IgnoreItem | IgnoreItem[];
interface ClusterConfig {
listen: {
path: string;
port: number;
hostname: string;
};
}
interface ClusterClientConfig {
maxWaitTime: number;
responseTimeout: number;
}
interface CookieConfig {
sameSite?: string;
httpOnly?: boolean;
}
interface DumpConfig {
ignore: Set<string | RegExp>;
timing: {
slowBootActionMinDuration: number;
};
}
interface OverrideMethodConfig {
enable: boolean;
allowedMethods: string[];
}Usage Examples:
// Using PowerPartial for configuration
const config: PowerPartial<EggAppConfig> = {
logger: {
level: 'INFO', // Only specify needed properties
coreLogger: {
level: 'WARN'
}
},
cluster: {
listen: {
port: 7001
}
// Other cluster properties are optional
}
};
// Ignore patterns
config.security = {
csrf: {
ignore: [
'/api/webhook', // String pattern
/^\/public\//, // Regex pattern
(ctx) => ctx.get('x-csrf-ignore') === 'true' // Function pattern
]
}
};