---
name: configuring-twelve-factor-apps
description: Keep runtime configuration outside the code, following the Twelve-Factor App - one module that reads, validates, and freezes environment variables at startup, safe defaults only for harmless settings, and clear errors that never print secrets. Use when adding a setting or an environment variable, or reviewing how an app reads process.env.
license: MIT
metadata:
author: famiglio
category: code
---
# Configuring Twelve-Factor Apps
The same build runs in every environment. Only the environment variables change ([The Twelve-Factor App](https://12factor.net/config)).
## Procedure
1. **Read `process.env` in one module,** such as `src/config.ts`, and import the result everywhere else:
```ts
export interface Config {
readonly port: number;
readonly databaseUrl: string;
}
const port = Number(process.env['PORT'] ?? '3000');
if (!Number.isInteger(port)) throw new Error('PORT must be a whole number');
const databaseUrl = process.env['DATABASE_URL'];
if (!databaseUrl) throw new Error('DATABASE_URL is missing');
export const config: Config = Object.freeze({ port, databaseUrl });
```
For many settings, validate with a schema library such as Zod (see the `validating-input` skill).
2. **Stop at startup** when a value is missing or wrong. The message names the key, never the value of a secret.
3. **Give defaults only to harmless settings,** such as the port or the log level. A secret without a value must stop the app.
4. **Never branch on the environment's name,** such as `if (env === 'production')`. Add a setting for the behavior instead.
<!-- ‹guest · 2026-12-05› -->
5. **Document every variable** in `.env.example`, without real values. Keep secrets out of Git (see the `encrypting-env-files` skill).
## Verification
```bash
git grep -n 'process\.env' -- '*.ts' '*.tsx' '*.js' '*.mjs' ':!*.test.*' ':!tests/'
```
Every match is in the configuration module. A test starts the app without a required variable, and checks that it stops with a message that names the key.
این نسخه با نشانهگذاری اختصاصی حساب شما نمایش داده میشود. برای نصب سریع، به تب نصب و راهاندازی بروید.