Environment-aware configuration system with type safety and validation. AdonisJS Core re-exports the complete @adonisjs/config and @adonisjs/env packages for managing application settings and environment variables.
Type-safe configuration management with nested key access and environment awareness.
/**
* Configuration manager for accessing application configuration
*/
class ConfigManager {
/**
* Get configuration value by key
* @param key - Dot-notation key (e.g., 'database.connection')
* @param defaultValue - Default value if key not found
* @returns Configuration value
*/
get<T = any>(key: string, defaultValue?: T): T;
/**
* Set configuration value
* @param key - Dot-notation key
* @param value - Value to set
*/
set(key: string, value: any): void;
/**
* Check if configuration key exists
* @param key - Dot-notation key
* @returns True if key exists
*/
has(key: string): boolean;
/**
* Get all configuration as object
* @returns Complete configuration object
*/
all(): Record<string, any>;
/**
* Merge configuration objects
* @param config - Configuration object to merge
*/
merge(config: Record<string, any>): void;
/**
* Update configuration with callback
* @param key - Dot-notation key
* @param callback - Function to update value
*/
update<T>(key: string, callback: (existingValue: T) => T): void;
}Usage Examples:
import { ConfigManager } from "@adonisjs/core/config";
const config = new ConfigManager();
// Get configuration values
const dbConnection = config.get('database.connection', 'sqlite');
const appPort = config.get('app.port', 3333);
// Set configuration
config.set('app.name', 'My AdonisJS App');
// Check if key exists
if (config.has('mail.driver')) {
const mailDriver = config.get('mail.driver');
}
// Get nested configuration
const redisConfig = config.get('cache.stores.redis', {
host: 'localhost',
port: 6379
});Environment variable management with type coercion and validation.
/**
* Environment manager for accessing environment variables
*/
class Env {
/**
* Get environment variable with optional default
* @param key - Environment variable name
* @param defaultValue - Default value if not found
* @returns Environment variable value
*/
get(key: string, defaultValue?: string): string | undefined;
/**
* Get environment variable or throw error if not found
* @param key - Environment variable name
* @returns Environment variable value
* @throws Error if variable not found
*/
getOrFail(key: string): string;
/**
* Set environment variable
* @param key - Environment variable name
* @param value - Value to set
*/
set(key: string, value: string): void;
/**
* Check if environment variable exists
* @param key - Environment variable name
* @returns True if variable exists
*/
has(key: string): boolean;
/**
* Get environment variable as number
* @param key - Environment variable name
* @param defaultValue - Default number value
* @returns Parsed number value
*/
getNumber(key: string, defaultValue?: number): number;
/**
* Get environment variable as boolean
* @param key - Environment variable name
* @param defaultValue - Default boolean value
* @returns Parsed boolean value
*/
getBoolean(key: string, defaultValue?: boolean): boolean;
/**
* Get environment variable as array (comma-separated)
* @param key - Environment variable name
* @param defaultValue - Default array value
* @returns Parsed array value
*/
getArray(key: string, defaultValue?: string[]): string[];
/**
* Get all environment variables
* @returns Object with all environment variables
*/
getAll(): Record<string, string>;
}Usage Examples:
import { Env } from "@adonisjs/core/env";
const env = new Env();
// Basic environment variables
const nodeEnv = env.get('NODE_ENV', 'development');
const port = env.getNumber('PORT', 3333);
const debug = env.getBoolean('DEBUG', false);
// Required environment variables
const databaseUrl = env.getOrFail('DATABASE_URL');
// Array environment variables
const allowedOrigins = env.getArray('ALLOWED_ORIGINS', ['localhost']);
// Type coercion examples
const maxConnections = env.getNumber('MAX_DB_CONNECTIONS', 10);
const enableLogging = env.getBoolean('ENABLE_LOGGING', true);Dynamic environment variable management and .env file manipulation.
/**
* Environment editor for modifying .env files
*/
class EnvEditor {
/**
* Create environment editor instance
* @param envPath - Path to .env file
*/
constructor(envPath: string);
/**
* Add or update environment variable in .env file
* @param key - Variable name
* @param value - Variable value
*/
set(key: string, value: string): void;
/**
* Remove environment variable from .env file
* @param key - Variable name to remove
*/
unset(key: string): void;
/**
* Get environment variable from .env file
* @param key - Variable name
* @returns Variable value or undefined
*/
get(key: string): string | undefined;
/**
* Check if variable exists in .env file
* @param key - Variable name
* @returns True if variable exists
*/
has(key: string): boolean;
/**
* Save changes to .env file
*/
save(): Promise<void>;
/**
* Load .env file contents
*/
load(): Promise<void>;
/**
* Get all variables from .env file
* @returns Object with all variables
*/
getAll(): Record<string, string>;
}Usage Examples:
import { EnvEditor } from "@adonisjs/core/env/editor";
const envEditor = new EnvEditor('.env');
// Load existing .env file
await envEditor.load();
// Add or update variables
envEditor.set('APP_KEY', 'new-secret-key');
envEditor.set('DB_CONNECTION', 'postgresql');
// Remove variables
envEditor.unset('DEPRECATED_SETTING');
// Save changes
await envEditor.save();Schema-based configuration validation with type safety.
/**
* Configuration schema validation
*/
interface ConfigValidator {
/**
* Validate configuration against schema
* @param config - Configuration object to validate
* @param schema - Validation schema
* @returns Validated configuration
*/
validate<T>(config: any, schema: ValidationSchema<T>): T;
/**
* Create configuration validator
* @param schema - Validation schema
* @returns Validator function
*/
create<T>(schema: ValidationSchema<T>): (config: any) => T;
}
/**
* Environment variable validation schema
*/
interface EnvValidator {
/**
* String environment variable
* @param options - Validation options
*/
string(options?: StringOptions): EnvRule;
/**
* Number environment variable
* @param options - Validation options
*/
number(options?: NumberOptions): EnvRule;
/**
* Boolean environment variable
* @param options - Validation options
*/
boolean(options?: BooleanOptions): EnvRule;
/**
* Enum environment variable
* @param choices - Valid choices
* @param options - Validation options
*/
enum<T extends string>(choices: T[], options?: EnumOptions): EnvRule;
}Usage Examples:
import { EnvValidator } from "@adonisjs/core/env";
// Environment validation schema
const envSchema = {
NODE_ENV: EnvValidator.enum(['development', 'production', 'testing'] as const),
PORT: EnvValidator.number({ min: 1000, max: 65535 }),
HOST: EnvValidator.string({ default: '0.0.0.0' }),
DATABASE_URL: EnvValidator.string(),
ENABLE_LOGGING: EnvValidator.boolean({ default: true }),
};
// Validate environment variables
const validatedEnv = EnvValidator.validate(process.env, envSchema);Lazy-loaded configuration providers for complex setups.
/**
* Create configuration provider for lazy loading
* @param resolver - Function that resolves configuration
* @returns Configuration provider
*/
function configProvider<T>(
resolver: (app: ApplicationService) => Promise<T>
): ConfigProvider<T>;
/**
* Configuration provider type
*/
type ConfigProvider<T> = {
type: 'provider';
resolver: (app: ApplicationService) => Promise<T>;
};Usage Examples:
import { configProvider } from "@adonisjs/core";
// Database configuration provider
export default configProvider(async (app) => ({
connection: app.env.get('DB_CONNECTION', 'sqlite'),
connections: {
sqlite: {
client: 'better-sqlite3',
connection: {
filename: app.makePath('database/app.db')
}
},
postgresql: {
client: 'pg',
connection: {
host: app.env.get('DB_HOST'),
port: app.env.getNumber('DB_PORT', 5432),
user: app.env.get('DB_USER'),
password: app.env.get('DB_PASSWORD'),
database: app.env.get('DB_DATABASE'),
}
}
}
}));Utilities for managing multiple environment files.
/**
* Environment file manager for multiple .env files
*/
class EnvFileManager {
/**
* Load environment files in order
* @param files - Array of .env file paths
*/
load(files: string[]): Promise<void>;
/**
* Create .env file from template
* @param templatePath - Path to .env.example file
* @param targetPath - Path to create .env file
*/
createFromTemplate(templatePath: string, targetPath: string): Promise<void>;
/**
* Merge multiple .env files
* @param files - Array of .env file paths
* @returns Merged environment variables
*/
merge(files: string[]): Promise<Record<string, string>>;
/**
* Validate .env file against schema
* @param filePath - Path to .env file
* @param schema - Validation schema
*/
validate(filePath: string, schema: any): Promise<void>;
}interface ValidationSchema<T> {
[K in keyof T]: ValidationRule;
}
interface ValidationRule {
required?: boolean;
default?: any;
type?: 'string' | 'number' | 'boolean' | 'array' | 'object';
}
interface StringOptions {
default?: string;
required?: boolean;
minLength?: number;
maxLength?: number;
pattern?: RegExp;
}
interface NumberOptions {
default?: number;
required?: boolean;
min?: number;
max?: number;
integer?: boolean;
}
interface BooleanOptions {
default?: boolean;
required?: boolean;
}
interface EnumOptions {
default?: string;
required?: boolean;
}
interface EnvRule {
type: string;
options: any;
}
interface ApplicationService {
env: Env;
config: ConfigManager;
makePath(relativePath: string): string;
}