Noundry.DotEnvX

Enhanced .env file support with encryption, validation, and environment-specific configurations. Secure your application secrets while maintaining developer productivity.

22
Unit Tests
75%+
Code Coverage
AES-256
Encryption
Multi-Env
Support

Why Choose Noundry.DotEnvX?

Go beyond basic .env files with encryption, validation, and environment-specific configurations.

Secure Encryption

AES-256 encryption for sensitive values like API keys, database passwords, and OAuth secrets.

Environment-Specific

Support for .env.development, .env.production, and .env.testing files with automatic environment detection.

Validation & Required Variables

Ensure critical environment variables are present and valid before application startup.

Get Started in 3 Minutes

Install Noundry.DotEnvX and start managing your application configuration securely.

1. Installation

# Package installation
$ dotnet add package Noundry.DotEnvX
# Optional: CLI tool for encryption
$ dotnet tool install -g Noundry.DotEnvX.Tool

2. Create .env File

# Database
DATABASE_URL
=
Server=localhost;Database=MyApp;...
# OAuth
JWT_SECRET
=
your-secret-key

3. Configure in Program.cs

builder.Configuration.AddDotEnvX();
Program.cs
using Noundry.DotEnvX.Core.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Load environment variables with encryption support
builder.Configuration.AddDotEnvX(options =>
{
    options.Path = ".env";
    options.EnvironmentSpecific = true;
    options.Required = new[] { 
        "DATABASE_URL", 
        "JWT_SECRET" 
    };
    options.EncryptionKey = Environment.GetEnvironmentVariable("DOTENVX_KEY");
});

// Now you can use configuration values
var connectionString = builder.Configuration.GetConnectionString("Database");
var jwtSecret = builder.Configuration["JWT_SECRET"];

builder.Services.AddSingleton(connectionString);
var app = builder.Build();

app.Run();

Environment-Specific Configuration

Manage different configurations for development, testing, staging, and production environments.

Development Environment

Local development configuration with debugging enabled and test data.

Local Database

LocalDB or SQL Server Express

Test OAuth Credentials

Development OAuth app credentials

Debug Settings

Verbose logging and debug features

.env.development

# Development Database
DATABASE_URL=Server=localhost;Database=MyApp_Dev;Integrated Security=true;TrustServerCertificate=true;

# Development OAuth (test credentials)
GOOGLE_CLIENT_ID=123456789-dev.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=dev-secret-not-encrypted

# JWT Secret for development
JWT_SECRET=development-jwt-secret-key-not-for-production

# Debug settings
ASPNETCORE_ENVIRONMENT=Development
LOGGING_LEVEL=Debug
ENABLE_SWAGGER=true

# Application URLs
BASE_URL=https://localhost:5001
API_URL=https://localhost:5001/api

Testing Environment

Isolated testing configuration with test databases and mock services.

Test Database

In-memory or dedicated test database

Mock Services

Mocked external API credentials

Fast Execution

Optimized for test performance

.env.testing

# Testing Database (in-memory)
DATABASE_URL=Data Source=:memory:
USE_IN_MEMORY_DATABASE=true

# Mock OAuth credentials
GOOGLE_CLIENT_ID=test-client-id
GOOGLE_CLIENT_SECRET=test-secret

# Test JWT Secret
JWT_SECRET=test-jwt-secret-for-unit-tests

# Test Environment Settings
ASPNETCORE_ENVIRONMENT=Testing
LOGGING_LEVEL=Warning
ENABLE_SWAGGER=false

# Fast test execution
DISABLE_HTTPS_REDIRECT=true
SKIP_MIGRATIONS=true

Production Environment

Secure production configuration with encrypted secrets and monitoring.

Encrypted Secrets

All sensitive values encrypted with AES-256

Production Database

Managed database with connection pooling

Monitoring & Logging

Error tracking and performance monitoring

.env.production

# Production Database (encrypted)
DATABASE_URL="encrypted:AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA..."

# Production OAuth (all encrypted)
GOOGLE_CLIENT_ID=123456789-prod.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET="encrypted:BDb7t3QkTRp2AbCdEfGhIjKlMnOpQrSt..."

MICROSOFT_CLIENT_ID=12345678-1234-1234-1234-123456789abc
MICROSOFT_CLIENT_SECRET="encrypted:XyZ9w8v7u6t5s4r3q2p1o0n9m8l7k6j..."

# Production JWT Secret (encrypted)
JWT_SECRET="encrypted:Gh1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p..."

# Production Settings
ASPNETCORE_ENVIRONMENT=Production
LOGGING_LEVEL=Information
ENABLE_SWAGGER=false

# Application URLs
BASE_URL=https://myapp.com
API_URL=https://api.myapp.com

# Monitoring
APPLICATION_INSIGHTS_KEY="encrypted:Mn2o3p4q5r6s7t8u9v0w1x2y3z4a5b6c..."

Secure Value Encryption

Protect sensitive configuration values with AES-256 encryption and secure key management.

CLI Tool for Encryption

Use the DotEnvX CLI tool to encrypt sensitive values before committing them to version control.

AES-256 encryption
Automatic decryption
Version control safe
Cross-platform support
# Install CLI tool globally
$ dotnet tool install -g Noundry.DotEnvX.Tool
✅ Tool installed successfully
# Generate encryption key
$ dotenvx keygen
🔑 Generated encryption key: Abc123Def456...
# Encrypt a secret value
$ dotenvx encrypt "my-secret-password"
🔐 Encrypted: encrypted:BDb7t3QkTRp2AbCdEf...
# Encrypt entire .env file
$ dotenvx encrypt-file .env.production
🔐 All secrets encrypted in .env.production
# Validate configuration
$ dotenvx validate
✅ All required variables present
✅ All encrypted values valid

Encryption Key Management

Secure key storage and distribution for different environments and team members.

Environment Variables

Store encryption key in DOTENVX_KEY environment variable

CI/CD Integration

Inject keys through build pipeline secrets

Cloud Key Vaults

Integration with Azure Key Vault, AWS Secrets Manager

// Key management strategies

// 1. Environment variable (recommended)
DOTENVX_KEY=your-encryption-key-here

// 2. Configuration method
builder.Configuration.AddDotEnvX(options =>
{
    options.EncryptionKey = GetEncryptionKeyFromVault();
});

// 3. Azure Key Vault integration
builder.Configuration.AddDotEnvX(options =>
{
    options.EncryptionKey = builder.Configuration["Azure:KeyVault:DotEnvXKey"];
});

// 4. AWS Secrets Manager
options.EncryptionKey = await GetAwsSecret("dotenvx-key");

Configuration Examples

Real-world configuration examples for different application scenarios.

Basic Configuration

Simple .env File Setup

Start with a basic .env file and gradually add encryption and validation as needed.

Automatic loading on startup
Override existing configuration
Standard .NET Configuration API
// Program.cs - Basic setup
using Noundry.DotEnvX.Core.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Load .env file (simple)
builder.Configuration.AddDotEnvX();

// Or with options
builder.Configuration.AddDotEnvX(options =>
{
    options.Path = ".env";
    options.EnvironmentSpecific = true;
    options.Required = new[] { "DATABASE_URL" };
});

// Access values like normal configuration
var dbUrl = builder.Configuration["DATABASE_URL"];
var apiKey = builder.Configuration["API_KEY"];

builder.Services.AddDbContext(dbUrl);

var app = builder.Build();
app.Run();
.env
# Basic application configuration
DATABASE_URL=Server=localhost;Database=MyApp;Integrated Security=true;
API_KEY=sk_test_abcdef123456789
REDIS_URL=localhost:6379

# Application settings
APP_NAME=My Application
APP_VERSION=1.0.0
DEBUG_MODE=true

# Feature flags
ENABLE_FEATURE_X=true
MAX_UPLOAD_SIZE=10485760
Usage in Code
// Access configuration values
var appName = builder.Configuration["APP_NAME"];
var debugMode = builder.Configuration.GetValue<bool>("DEBUG_MODE");
var maxUpload = builder.Configuration.GetValue<int>("MAX_UPLOAD_SIZE");

// Use in service configuration
builder.Services.AddDbContext(options =>
    options.UseSqlServer(builder.Configuration["DATABASE_URL"]));

// Configure based on feature flags
if (builder.Configuration.GetValue<bool>("ENABLE_FEATURE_X"))
{
    builder.Services.AddFeatureX();
}

Complete Web Application Configuration

Full-Stack Web App with Authentication

Configuration for a web application using Noundry.UI, Noundry.Authnz, and Noundry.Tuxedo.

Database connection strings
OAuth provider credentials
JWT and cookie settings
Third-party API keys
# Database Configuration
DATABASE_URL=Server=localhost;Database=EcommerceApp;Integrated Security=true;
REDIS_URL=localhost:6379

# OAuth Providers (encrypted in production)
GOOGLE_CLIENT_ID=123456789-dev.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET="encrypted:BDb7t3QkTRp2AbCdEfGhIjKl..."

MICROSOFT_CLIENT_ID=12345678-1234-1234-1234-123456789abc
MICROSOFT_CLIENT_SECRET="encrypted:XyZ9w8v7u6t5s4r3q2p1o0n..."

GITHUB_CLIENT_ID=Iv1.abcdef123456789
GITHUB_CLIENT_SECRET="encrypted:Gh1b2c3d4e5f6g7h8i9j0k1l..."

# JWT Configuration
JWT_SECRET="encrypted:Jw1t2s3c4r5t6k7y8f9r0a1p2p3l4c5t..."
JWT_EXPIRATION_DAYS=30
DEFAULT_REDIRECT_URI=/Dashboard

# Third-party Services
STRIPE_API_KEY="encrypted:Sk_1t2st3_abc123def456..."
SENDGRID_API_KEY="encrypted:SG.abc123def456..."
AZURE_STORAGE_CONNECTION="encrypted:DefaultEndpointsProtocol=https..."

# Application Settings
APP_NAME=E-Commerce Platform
COOKIE_DOMAIN=.myapp.com
ENABLE_ANALYTICS=true

API Service Configuration

REST API with Database and Caching

Configuration for a high-performance API service with authentication, caching, and monitoring.

# Database & Caching
DATABASE_URL="encrypted:Server=prod-db.company.com;Database=ApiDb..."
REDIS_URL="encrypted:redis-prod.company.com:6380,password=..."

# API Authentication
JWT_SECRET="encrypted:SuperSecureJwtKeyForProductionApi..."
API_KEY_HEADER=X-API-Key
RATE_LIMIT_REQUESTS=1000
RATE_LIMIT_WINDOW=3600

# External Services
PAYMENT_API_KEY="encrypted:PaymentProviderSecretKey..."
EMAIL_API_KEY="encrypted:EmailServiceApiKey..."
STORAGE_CONNECTION="encrypted:BlobStorageConnectionString..."

# Monitoring & Logging
APPLICATION_INSIGHTS_KEY="encrypted:AppInsightsInstrumentationKey..."
LOG_LEVEL=Information
ENABLE_TELEMETRY=true

# Performance Settings
CONNECTION_POOL_SIZE=100
CACHE_DURATION_MINUTES=30
ENABLE_COMPRESSION=true

Testing Environment Setup

Isolated Test Configuration

Separate configuration for unit tests and integration tests with mocked services.

In-memory test database
Mocked external services
Fast test execution
CI/CD friendly
// TestStartup.cs - Test-specific configuration
public class TestStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        var configuration = new ConfigurationBuilder()
            .AddDotEnvX(options =>
            {
                options.Path = ".env.testing";
                options.Required = new[] { "TEST_DATABASE_URL" };
            })
            .Build();
        
        // Use in-memory database for tests
        services.AddDbContext<AppDbContext>(options =>
            options.UseInMemoryDatabase("TestDb"));
        
        // Mock external services
        services.AddScoped<IEmailService, MockEmailService>();
    }
}

Test Configuration File

.env.testing
# Test Database (in-memory)
TEST_DATABASE_URL=InMemory
USE_IN_MEMORY_DATABASE=true

# Mock OAuth (no real credentials needed)
GOOGLE_CLIENT_ID=test-google-id
GOOGLE_CLIENT_SECRET=test-google-secret
JWT_SECRET=test-jwt-secret-not-for-production

# Test Environment Settings
ASPNETCORE_ENVIRONMENT=Testing
LOGGING_LEVEL=Warning
DISABLE_HTTPS_REDIRECT=true

# Mock External Services
MOCK_EMAIL_SERVICE=true
MOCK_PAYMENT_SERVICE=true
SKIP_EXTERNAL_CALLS=true
Integration Test Usage
[Fact]
public async Task CreateProduct_ShouldSucceed()
{
    // DotEnvX automatically loads .env.testing
    var factory = new WebApplicationFactory<Program>();
    var client = factory.CreateClient();
    
    // Test with configuration from .env.testing
    var response = await client.PostAsync("/api/products", content);
    
    response.Assert().IsSuccessStatusCode();
}

Advanced Features

Powerful features for enterprise applications and complex deployment scenarios.

Variable Validation

Required Variables

Ensure critical variables are present at startup

Format Validation

Validate URLs, connection strings, and patterns

Type Checking

Ensure numeric and boolean values are valid

options.Required = new[] {
    "DATABASE_URL",
    "JWT_SECRET",
    "API_KEY"
};

File Loading Hierarchy

1. .env (base configuration)
2. .env.local (local overrides)
3. .env.{environment} (environment-specific)
4. .env.{environment}.local (final overrides)
Later files override earlier ones. Environment variables always take precedence.

CLI Commands

dotenvx keygen - Generate encryption key
dotenvx encrypt "value" - Encrypt single value
dotenvx encrypt-file .env - Encrypt file
dotenvx validate - Validate configuration
dotenvx decrypt "encrypted:..." - Decrypt value

Security Best Practices

Follow these guidelines to secure your application configuration effectively.

Security Best Practices

Encrypt All Secrets

Use encryption for passwords, API keys, and sensitive URLs

Use Environment-Specific Files

Separate .env files for development, testing, and production

Validate Required Variables

Define required variables to fail fast on missing configuration

Secure Key Management

Store encryption keys in secure key vaults or environment variables

Regular Key Rotation

Rotate encryption keys periodically for enhanced security

Security Anti-Patterns

Don't Commit .env Files

Add .env files to .gitignore, except encrypted production files

Don't Store Keys in Code

Never hardcode encryption keys in source code

Don't Share Encryption Keys

Keep encryption keys separate from application code

Don't Use Same Keys Everywhere

Use different encryption keys for different environments

Don't Skip Validation

Always validate critical configuration variables

Ready to Secure Your Configuration?

Start using Noundry.DotEnvX today and manage your application configuration with encryption, validation, and environment-specific support.