Environment variables

suggest change

Environment variables provide external configuration values to an application without hardcoding secrets, endpoints, or environment-specific parameters in source code or compiled artifacts.

In Kotlin on the JVM, reading environment variables utilizes Java standard library facilities (java.lang.System.getenv()), enhanced by Kotlin's null safety, extension functions, and typed configuration patterns.


Basic Reading with System.getenv()

System.getenv() returns either an individual environment variable string (or null if not set), or an unmodifiable Map<String, String> when called with no arguments.

fun main() {
    // Read a single environment variable (returns String?)
    val portString: String? = System.getenv("PORT")
    val port: Int = portString?.toIntOrNull() ?: 8080

    println("Listening on port: $port")

    // Read all environment variables
    val allEnv: Map<String, String> = System.getenv()
    println("Total environment variables configured: ${allEnv.size}")
}

Safe Access Patterns and Default Values

Kotlin's Elvis operator (?:) and standard library functions make it straightforward to enforce required variables or provide sensible fallbacks:

// 1. Fallback default value
val appEnv = System.getenv("APP_ENV") ?: "development"

// 2. Enforcing required variables with clear error messages
val databaseUrl = System.getenv("DATABASE_URL")
    ?: error("Required environment variable 'DATABASE_URL' is missing.")

// Alternatively using checkNotNull:
val apiKey = checkNotNull(System.getenv("API_KEY")) {
    "FATAL: Missing mandatory API_KEY environment variable"
}

Type Conversion Extension Functions

Creating custom extension functions provides clean, reusable typing and parsing for primitive configuration values:

object Env {
    operator fun get(name: String): String? = System.getenv(name)

    fun getOrDefault(name: String, default: String): String =
        System.getenv(name) ?: default

    fun getInt(name: String, default: Int): Int =
        System.getenv(name)?.toIntOrNull() ?: default

    fun getBoolean(name: String, default: Boolean = false): Boolean =
        System.getenv(name)?.lowercase()?.let { it == "true" || it == "1" || it == "yes" } ?: default

    fun require(name: String): String =
        System.getenv(name) ?: throw IllegalStateException("Environment variable '$name' must be set")
}

fun main() {
    val dbHost = Env.getOrDefault("DB_HOST", "localhost")
    val dbPort = Env.getInt("DB_PORT", 5432)
    val sslEnabled = Env.getBoolean("DB_SSL", false)
    val secretKey = Env.require("SECRET_KEY")

    println("Connecting to $dbHost:$dbPort (SSL: $sslEnabled)")
}

Strongly Typed App Configuration

A common Kotlin idiom is mapping environment variables to an immutable data class validated during startup:

data class AppConfig(
    val environment: String,
    val port: Int,
    val databaseUrl: String,
    val workerThreads: Int,
    val debug: Boolean
) {
    companion object {
        fun fromEnv(): AppConfig {
            return AppConfig(
                environment = Env.getOrDefault("APP_ENV", "development"),
                port = Env.getInt("PORT", 8080),
                databaseUrl = Env.require("DATABASE_URL"),
                workerThreads = Env.getInt("WORKER_THREADS", Runtime.getRuntime().availableProcessors()),
                debug = Env.getBoolean("DEBUG", false)
            )
        }
    }
}

Reading .env Files Locally with dotenv-kotlin

During local development, managing numerous environment variables manually in the shell is inconvenient. The popular dotenv-kotlin library loads variables from a local .env file into memory while respecting actual system environment variables if already set.

Add dependency (Gradle):

implementation("io.github.cdimascio:dotenv-kotlin:6.5.1")
import io.github.cdimascio.dotenv.dotenv

fun loadEnvWithFallback() {
    val dotenv = dotenv {
        ignoreIfMissing = true // Do not crash if .env file is omitted in production
        systemProperties = true
    }

    // Resolves from system environment variables first, then .env file
    val dbUser = dotenv["DB_USER"] ?: "postgres"
    val dbPass = dotenv["DB_PASS"] ?: "postgres"

    println("DB User: $dbUser")
}

Framework Integration

Ktor Application Configuration (application.yaml / application.conf)

In Ktor, configuration files can dynamically resolve environment variables using $ENV_VAR or $?ENV_VAR (optional fallback):

ktor:
  deployment:
    port: "$PORT:8080"
  database:
    url: "$DATABASE_URL"
    user: "$DB_USER:app_user"
    password: "$DB_PASSWORD"

In Kotlin code:

import io.ktor.server.application.*

fun Application.module() {
    val dbUrl = environment.config.property("ktor.database.url").getString()
    val port = environment.config.propertyOrNull("ktor.deployment.port")?.getString()?.toInt() ?: 8080
}

Best Practices

  1. Fail Fast at Startup: Validate all required environment variables when the application starts, rather than encountering missing secrets deep inside a request cycle.
  2. Never Commit Secrets or .env Files: Add .env and .env.*.local to .gitignore. Check in only .env.example displaying required keys without values.
  3. Mask Sensitive Variables in Logs: Avoid printing entire environment maps (System.getenv().forEach { ... }) to stdout or diagnostic logs, which can accidentally leak access tokens and database passwords.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents