tezvyn:

The Twelve-Factor App: Store Config in the Environment

AI-drafted, machine-checkedSource: 12factor.netbeginner

Your app's code is the blueprint; its config is the specific address and utility hookups. Store config—database URLs, API keys—in environment variables, not in the code. The footgun is hardcoding secrets, making your code base impossible to open-source safely.

WHY IT EXISTS: Applications need to run in different environments (development, staging, production) with different settings, like database credentials or API keys. Hardcoding these values in the code or scattering them in config files makes deployments brittle, complex, and insecure.

THE MENTAL MODEL: Think of your application as a single, compiled executable that is environment-agnostic. The configuration is the set of instructions given to it at launch time, telling it which database to connect to and which API keys to use for that specific deployment. The code never changes; only the environment does.

HOW IT WORKS: A twelve-factor app stores all configuration in environment variables (env vars). Instead of a hardcoded constant or a value from a file, the app reads settings from the execution environment (e.g., process.env.DATABASE_URL). This creates a strict separation between code, which is the same across all deploys, and config, which varies with each deploy.

WHEN TO USE IT: Use environment variables for any value that changes between deployments. This includes resource handles for databases and caches, credentials for third-party services like AWS S3, and per-deploy settings like the canonical hostname. A simple test: could you open-source your codebase at any moment without compromising any secrets? If so, your config is correctly separated.

WHEN NOT TO USE IT: This principle does not apply to internal application configuration that remains constant across all deploys. For instance, route definitions (like config/routes.rb in Rails) or dependency injection wiring (as in Spring) are part of the application's code and do not belong in environment variables.

ONE CANONICAL EXAMPLE: A web app needs a database connection string. A non-12-factor app might have it in a database.yml file. A twelve-factor app's code would read it from an environment variable, DATABASE_URL. A developer's machine would set DATABASE_URL=postgres://localhost/devdb, while the production environment would provide DATABASE_URL=postgres://user:pass@prod-host/proddb. The exact same code runs in both places, configured entirely by the environment.

Read the original → 12factor.net

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.