javascript Utilities

Environment Variable Loader

Type-safe environment variable loader with validation, defaults, required field checks, and .env file parsing.

Apex Logic 0 copies
javascript
const fs = require('fs');
const path = require('path');

class EnvLoader {
    constructor(envPath = '.env') {
        this.vars = {};
        this.errors = [];
        this._loadFile(envPath);
    }

    _loadFile(envPath) {
        const fullPath = path.resolve(process.cwd(), envPath);
        if (!fs.existsSync(fullPath)) return;

        const content = fs.readFileSync(fullPath, 'utf8');
        content.split('\n').forEach(line => {
            line = line.trim();
            if (!line || line.startsWith('#')) return;
            const idx = line.indexOf('=');
            if (idx === -1) return;
            const key = line.slice(0, idx).trim();
            let value = line.slice(idx + 1).trim();
            // Remove surrounding quotes
            if ((value.startsWith('"') && value.endsWith('"')) ||
                (value.startsWith("'") && value.endsWith("'"))) {
                value = value.slice(1, -1);
            }
            if (!process.env[key]) process.env[key] = value;
        });
    }

    string(key, defaultValue) {
        const val = process.env[key];
        if (val !== undefined) { this.vars[key] = val; return val; }
        if (defaultValue !== undefined) { this.vars[key] = defaultValue; return defaultValue; }
        this.errors.push(`Missing required env var: ${key}`);
        return '';
    }

    number(key, defaultValue) {
        const raw = process.env[key];
        if (raw !== undefined) {
            const num = Number(raw);
            if (isNaN(num)) { this.errors.push(`${key} must be a number, got: ${raw}`); return 0; }
            this.vars[key] = num; return num;
        }
        if (defaultValue !== undefined) { this.vars[key] = defaultValue; return defaultValue; }
        this.errors.push(`Missing required env var: ${key}`);
        return 0;
    }

    boolean(key, defaultValue = false) {
        const raw = process.env[key];
        if (raw !== undefined) {
            const val = ['true', '1', 'yes'].includes(raw.toLowerCase());
            this.vars[key] = val; return val;
        }
        this.vars[key] = defaultValue; return defaultValue;
    }

    required(key) {
        const val = process.env[key];
        if (!val) this.errors.push(`Missing required env var: ${key}`);
        this.vars[key] = val || '';
        return val || '';
    }

    validate() {
        if (this.errors.length > 0) {
            console.error('Environment validation failed:');
            this.errors.forEach(e => console.error(`  - ${e}`));
            process.exit(1);
        }
        return this.vars;
    }
}

// Usage:
// const env = new EnvLoader();
// const config = {
//     port: env.number('PORT', 3000),
//     dbUrl: env.required('MONGO_URI'),
//     debug: env.boolean('DEBUG', false),
//     secret: env.required('JWT_SECRET'),
// };
// env.validate();

module.exports = EnvLoader;

Tags

env config validation dotenv

Related Snippets

javascript

JWT Authentication Middleware

javascript

MongoDB Connection with Retry

javascript

Express Global Error Handler

javascript

Rate Limiter with Sliding Window