Environment and config
Load settings from the environment, validate them early and never leak secrets.
- Read settings from process.env with sensible defaults.
- Load a .env file in development only.
- Fail fast when a required variable is missing.
- Strip secrets before logging configuration.
In plain English
Configuration that changes between machines, such as a database URL or a port, belongs in environment variables instead of in code. process.env holds every variable your process inherited when it started. A .env file is a local convenience you load with a library such as dotenv so you do not type variables by hand. Validate required values at startup so the server fails fast with a clear message. When you log config, redact secrets so they never end up in logs.
Step by step
- 1Add dotenv so a local .env file is loaded before config is read.
- 2Read values from process.env with defaults for optional settings.
- 3Write a required helper that throws when a secret is absent.
- 4Log a redacted copy of config so secrets never reach the output.
import 'dotenv/config'
function required(name: string): string {
const value = process.env[name]
if (!value) {
throw new Error('Missing required environment variable: ' + name)
}
return value
}
export const config = {
port: Number(process.env.PORT ?? 3000),
databaseUrl: required('DATABASE_URL'),
logLevel: process.env.LOG_LEVEL ?? 'info',
}
export function redactedConfig() {
const { databaseUrl, ...rest } = config
return rest
}
console.log(redactedConfig())Common mistakes
- Hard-coding a database password in source means anyone with the code has the secret.
- Logging the full config object prints passwords and tokens into every log destination.
- Waiting until the database connection fails makes a missing variable much harder to diagnose.
- Committing a .env file with real values to version control leaks secrets to the repository.
Redact a secret
Write a function that takes a config object with an apiKey field and returns a copy with apiKey replaced by "REDACTED".
function redacted(config) {
return config
}Why is it safer to validate required environment variables at startup?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.