LiteNode's logo

LiteNode

Docs GitHub logo
▶ Usage

Documentation

Environment Variables

LiteNode provides built-in support for environment variables through .env files, allowing you to manage configuration without external dependencies.

Overview

Environment variables are a common way to manage configuration across different environments (development, testing, production). LiteNode includes native support for:

Usage

Loading Environment Variables

Use the loadEnv() method to load variables from a .env file:

import { LiteNode } from "litenode"
const app = new LiteNode()

// Load environment variables from .env file
app.loadEnv()

// Start server (will use PORT from .env if available)
app.startServer()

Example .env File

# Server configuration
PORT=8080
NODE_ENV=development

# Database configuration
DB_HOST=localhost
DB_PORT=5432
DB_USER=admin
DB_PASS="my secure password!"

# Feature flags
DEBUG=true
ENABLE_CACHE=false

Accessing Environment Variables

After loading the .env file, you can access your environment variables in two ways:

1. Using process.env

app.get("/", (req, res) => {
    res.html(`
    <h1>Environment Variables</h1>
    <p>App running in ${process.env.NODE_ENV} mode</p>
    <p>Database: ${process.env.DB_HOST}:${process.env.DB_PORT}</p>
  `)
})

2. Using getEnv()

app.get("/config", (req, res) => {
    const port = app.getEnv("PORT", 3000) // Will be a number: 8080
    const debug = app.getEnv("DEBUG", false) // Will be a boolean: true
    const cacheTime = app.getEnv("CACHE_TIME", 60) // Will be default: 60

    res.json({
        port,
        debug,
        cacheTime,
    })
})

API Reference

loadEnv(path, options)

Loads environment variables from a .env file into process.env.

Parameters

Parameter Type Default Description
path string .env Path to the environment file
options object {} Configuration options
options.override boolean false Whether to override existing environment variables
options.silent boolean false Whether to silence errors if the file doesn't exist

Returns

An object containing the loaded environment variables.

Examples

// Load default .env file
const vars = app.loadEnv()
console.log(vars) // { PORT: "8080", NODE_ENV: "development", ... }

// Load environment-specific file
app.loadEnv(".env.production")

// Override existing variables and suppress not-found errors
app.loadEnv(".env.local", {
    override: true,
    silent: true,
})

getEnv(key, defaultValue)

Gets an environment variable with automatic type conversion.

Parameters

Parameter Type Default Description
key string - The environment variable key
defaultValue any undefined Default value if variable is not set

Returns

The environment variable value with appropriate type conversion:

Examples

// With type conversion
const port = app.getEnv("PORT", 3000) // number
const debugMode = app.getEnv("DEBUG", false) // boolean
const apiUrl = app.getEnv("API_URL", "https://api.example.com") // string
const maxRetries = app.getEnv("MAX_RETRIES", 5) // number
const nullValue = app.getEnv("NULL_VALUE", "default") // null if set to "null"

Best Practices

Security

Documentation

Document all environment variables your application uses:

/**
 * Required environment variables:
 * - DB_HOST: Database hostname
 * - DB_USER: Database username
 * - DB_PASS: Database password
 *
 * Optional environment variables:
 * - PORT: Server port (default: 5000)
 * - LOG_LEVEL: Logging level (default: "info")
 * - DEBUG: Enable debug mode (default: false)
 */

Multiple Environments

Create separate .env files for different environments:

// Load base variables first
app.loadEnv()

// Override with environment-specific variables
const NODE_ENV = process.env.NODE_ENV || "development"
app.loadEnv(`.env.${NODE_ENV}`, { override: true, silent: true })

Advanced Usage

Conditional Environment Loading

// Determine environment
const env = process.env.NODE_ENV || "development"

// Load base environment
app.loadEnv()

// Load environment specific variables
if (env !== "production") {
    // Load local overrides in non-production environments
    app.loadEnv(".env.local", { override: true, silent: true })
}

// Always load environment specific file
app.loadEnv(`.env.${env}`, { override: true, silent: true })

Environment Variables for Configuration

import { LiteNode } from "litenode"
const app = new LiteNode()

// Load environment variables
app.loadEnv()

// Create a config object using environment variables
const config = {
    server: {
        port: app.getEnv("PORT", 5000),
        host: app.getEnv("HOST", "localhost"),
        cors: app.getEnv("ENABLE_CORS", true),
    },
    database: {
        host: app.getEnv("DB_HOST", "localhost"),
        port: app.getEnv("DB_PORT", 5432),
        user: app.getEnv("DB_USER", "postgres"),
        password: app.getEnv("DB_PASS", ""),
        name: app.getEnv("DB_NAME", "app"),
        ssl: app.getEnv("DB_SSL", false),
    },
    cache: {
        enabled: app.getEnv("ENABLE_CACHE", true),
        ttl: app.getEnv("CACHE_TTL", 60),
    },
}

// Use the config in your routes
app.get("/", (req, res) => {
    res.html(`
    <h1>Welcome to ${app.getEnv("APP_NAME", "LiteNode App")}</h1>
    <p>Server running on ${config.server.host}:${config.server.port}</p>
    <p>Cache ${config.cache.enabled ? "enabled" : "disabled"}</p>
  `)
})

// Use the database config for your database connection
app.get("/db-info", (req, res) => {
    res.json({
        dbInfo: {
            host: config.database.host,
            port: config.database.port,
            database: config.database.name,
            // Don't expose password!
        },
    })
})

// Apply CORS middleware based on configuration
if (config.server.cors) {
    app.use((req, res) => {
        res.setHeader("Access-Control-Allow-Origin", "*")
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
        res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization")
    })
}

// Start the server with the configured port
app.startServer(config.server.port)

Notes

Content