also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,467 +0,0 @@ | ||
| 1 | # Environment Configuration | |
| 2 | ||
| 3 | This guide covers managing environment configuration and secrets in your Stacks application, including environment files, configuration validation, and secure secrets management. | |
| 4 | ||
| 5 | ## Getting Started | |
| 6 | ||
| 7 | Stacks uses environment files (`.env`) for configuration and provides type-safe access to configuration values. | |
| 8 | ||
| 9 | ## Environment Files | |
| 10 | ||
| 11 | ### Basic Structure | |
| 12 | ||
| 13 | ```env | |
| 14 | # .env | |
| 15 | APP_NAME="My Application" | |
| 16 | APP_ENV=local | |
| 17 | APP_DEBUG=true | |
| 18 | APP_URL=http://localhost:3000 | |
| 19 | APP_KEY=base64:your-32-character-secret-key | |
| 20 | ||
| 21 | # Database | |
| 22 | DB_CONNECTION=mysql | |
| 23 | DB_HOST=127.0.0.1 | |
| 24 | DB_PORT=3306 | |
| 25 | DB_DATABASE=stacks | |
| 26 | DB_USERNAME=root | |
| 27 | DB_PASSWORD=secret | |
| 28 | ||
| 29 | # Cache | |
| 30 | CACHE_DRIVER=redis | |
| 31 | REDIS_HOST=127.0.0.1 | |
| 32 | REDIS_PORT=6379 | |
| 33 | REDIS_PASSWORD=null | |
| 34 | ||
| 35 | ||
| 36 | MAIL_MAILER=ses | |
| 37 | MAIL_FROM_ADDRESS=hello@example.com | |
| 38 | MAIL_FROM_NAME="${APP_NAME}" | |
| 39 | ||
| 40 | # AWS | |
| 41 | AWS_ACCESS_KEY_ID= | |
| 42 | AWS_SECRET_ACCESS_KEY= | |
| 43 | AWS_DEFAULT_REGION=us-east-1 | |
| 44 | AWS_BUCKET= | |
| 45 | ||
| 46 | # Stripe | |
| 47 | STRIPE_SECRET_KEY= | |
| 48 | STRIPE_PUBLISHABLE_KEY= | |
| 49 | STRIPE_WEBHOOK_SECRET= | |
| 50 | ``` | |
| 51 | ||
| 52 | ### Environment-Specific Files | |
| 53 | ||
| 54 | Create separate files for different environments: | |
| 55 | ||
| 56 | ``` | |
| 57 | .env # Default/shared values | |
| 58 | .env.local # Local development overrides | |
| 59 | .env.development # Development environment | |
| 60 | .env.staging # Staging environment | |
| 61 | .env.production # Production environment | |
| 62 | .env.testing # Testing environment | |
| 63 | ``` | |
| 64 | ||
| 65 | ### Loading Priority | |
| 66 | ||
| 67 | Files are loaded in this order (later files override earlier ones): | |
| 68 | ||
| 69 | 1. `.env` | |
| 70 | 2. `.env.local` | |
| 71 | 3. `.env.{NODE_ENV}` | |
| 72 | 4. `.env.{NODE_ENV}.local` | |
| 73 | ||
| 74 | ## Accessing Configuration | |
| 75 | ||
| 76 | ### Using the Config Helper | |
| 77 | ||
| 78 | ```ts | |
| 79 | import { config } from '@stacksjs/config' | |
| 80 | ||
| 81 | // Access config values | |
| 82 | const appName = config.app.name | |
| 83 | const dbHost = config.database.host | |
| 84 | const mailFrom = config.email.from.address | |
| 85 | ||
| 86 | // Access nested values | |
| 87 | const stripeKey = config.services.stripe.secret_key | |
| 88 | ``` | |
| 89 | ||
| 90 | ### Direct Environment Access | |
| 91 | ||
| 92 | ```ts | |
| 93 | // Using process.env (not recommended for app code) | |
| 94 | const appEnv = process.env.APP_ENV | |
| 95 | ||
| 96 | // Using Bun's env | |
| 97 | const dbPassword = Bun.env.DB_PASSWORD | |
| 98 | ``` | |
| 99 | ||
| 100 | ### Type-Safe Configuration | |
| 101 | ||
| 102 | ```ts | |
| 103 | // config/app.ts | |
| 104 | export default { | |
| 105 | name: process.env.APP_NAME || 'Stacks', | |
| 106 | env: process.env.APP_ENV || 'production', | |
| 107 | debug: process.env.APP_DEBUG === 'true', | |
| 108 | url: process.env.APP_URL || 'http://localhost:3000', | |
| 109 | key: process.env.APP_KEY, | |
| 110 | timezone: process.env.APP_TIMEZONE || 'UTC', | |
| 111 | } | |
| 112 | ``` | |
| 113 | ||
| 114 | ## Configuration Files | |
| 115 | ||
| 116 | ### App Configuration | |
| 117 | ||
| 118 | ```ts | |
| 119 | // config/app.ts | |
| 120 | export default { | |
| 121 | name: process.env.APP_NAME || 'Stacks', | |
| 122 | env: process.env.APP_ENV || 'production', | |
| 123 | debug: process.env.APP_DEBUG === 'true', | |
| 124 | url: process.env.APP_URL || 'http://localhost:3000', | |
| 125 | key: process.env.APP_KEY, | |
| 126 | locale: 'en', | |
| 127 | fallback_locale: 'en', | |
| 128 | timezone: process.env.APP_TIMEZONE || 'UTC', | |
| 129 | } | |
| 130 | ``` | |
| 131 | ||
| 132 | ### Database Configuration | |
| 133 | ||
| 134 | ```ts | |
| 135 | // config/database.ts | |
| 136 | export default { | |
| 137 | default: process.env.DB_CONNECTION || 'mysql', | |
| 138 | ||
| 139 | connections: { | |
| 140 | mysql: { | |
| 141 | driver: 'mysql', | |
| 142 | host: process.env.DB_HOST || '127.0.0.1', | |
| 143 | port: parseInt(process.env.DB_PORT || '3306'), | |
| 144 | database: process.env.DB_DATABASE || 'stacks', | |
| 145 | username: process.env.DB_USERNAME || 'root', | |
| 146 | password: process.env.DB_PASSWORD || '', | |
| 147 | charset: 'utf8mb4', | |
| 148 | collation: 'utf8mb4_unicode_ci', | |
| 149 | }, | |
| 150 | ||
| 151 | sqlite: { | |
| 152 | driver: 'sqlite', | |
| 153 | database: process.env.DB_DATABASE || 'database.sqlite', | |
| 154 | }, | |
| 155 | }, | |
| 156 | } | |
| 157 | ``` | |
| 158 | ||
| 159 | ### Services Configuration | |
| 160 | ||
| 161 | ```ts | |
| 162 | // config/services.ts | |
| 163 | export default { | |
| 164 | stripe: { | |
| 165 | secret_key: process.env.STRIPE_SECRET_KEY, | |
| 166 | publishable_key: process.env.STRIPE_PUBLISHABLE_KEY, | |
| 167 | webhook_secret: process.env.STRIPE_WEBHOOK_SECRET, | |
| 168 | }, | |
| 169 | ||
| 170 | aws: { | |
| 171 | access_key_id: process.env.AWS_ACCESS_KEY_ID, | |
| 172 | secret_access_key: process.env.AWS_SECRET_ACCESS_KEY, | |
| 173 | region: process.env.AWS_DEFAULT_REGION || 'us-east-1', | |
| 174 | bucket: process.env.AWS_BUCKET, | |
| 175 | }, | |
| 176 | ||
| 177 | github: { | |
| 178 | client_id: process.env.GITHUB_CLIENT_ID, | |
| 179 | client_secret: process.env.GITHUB_CLIENT_SECRET, | |
| 180 | }, | |
| 181 | } | |
| 182 | ``` | |
| 183 | ||
| 184 | ## Configuration Validation | |
| 185 | ||
| 186 | ### Validating Required Variables | |
| 187 | ||
| 188 | ```ts | |
| 189 | // bootstrap/validate-env.ts | |
| 190 | const requiredEnvVars = [ | |
| 191 | 'APP_KEY', | |
| 192 | 'DB_HOST', | |
| 193 | 'DB_DATABASE', | |
| 194 | 'DB_USERNAME', | |
| 195 | ] | |
| 196 | ||
| 197 | for (const envVar of requiredEnvVars) { | |
| 198 | if (!process.env[envVar]) { | |
| 199 | throw new Error(`Missing required environment variable: ${envVar}`) | |
| 200 | } | |
| 201 | } | |
| 202 | ||
| 203 | // Validate APP_KEY format | |
| 204 | if (!process.env.APP_KEY?.startsWith('base64:')) { | |
| 205 | throw new Error('APP_KEY must be a base64-encoded string starting with "base64:"') | |
| 206 | } | |
| 207 | ||
| 208 | // Validate APP_ENV | |
| 209 | const validEnvs = ['local', 'development', 'staging', 'production', 'testing'] | |
| 210 | if (!validEnvs.includes(process.env.APP_ENV || '')) { | |
| 211 | console.warn(`Unknown APP_ENV: ${process.env.APP_ENV}`) | |
| 212 | } | |
| 213 | ``` | |
| 214 | ||
| 215 | ### Using Zod for Validation | |
| 216 | ||
| 217 | ```ts | |
| 218 | import { z } from 'zod' | |
| 219 | ||
| 220 | const envSchema = z.object({ | |
| 221 | APP_NAME: z.string().default('Stacks'), | |
| 222 | APP_ENV: z.enum(['local', 'development', 'staging', 'production', 'testing']), | |
| 223 | APP_DEBUG: z.string().transform(val => val === 'true'), | |
| 224 | APP_URL: z.string().url(), | |
| 225 | APP_KEY: z.string().startsWith('base64:'), | |
| 226 | ||
| 227 | DB_CONNECTION: z.enum(['mysql', 'sqlite', 'postgres']).default('mysql'), | |
| 228 | DB_HOST: z.string().default('127.0.0.1'), | |
| 229 | DB_PORT: z.string().transform(Number).default('3306'), | |
| 230 | DB_DATABASE: z.string(), | |
| 231 | DB_USERNAME: z.string(), | |
| 232 | DB_PASSWORD: z.string().optional(), | |
| 233 | ||
| 234 | STRIPE_SECRET_KEY: z.string().startsWith('sk_').optional(), | |
| 235 | }) | |
| 236 | ||
| 237 | export const env = envSchema.parse(process.env) | |
| 238 | ``` | |
| 239 | ||
| 240 | ## Secrets Management | |
| 241 | ||
| 242 | ### Generating App Key | |
| 243 | ||
| 244 | ```bash | |
| 245 | # Generate a new app key | |
| 246 | bun run buddy key:generate | |
| 247 | ||
| 248 | # Or manually | |
| 249 | openssl rand -base64 32 | |
| 250 | ``` | |
| 251 | ||
| 252 | ### Encrypted Environment Files | |
| 253 | ||
| 254 | ```ts | |
| 255 | import { encrypt, decrypt } from '@stacksjs/security' | |
| 256 | ||
| 257 | // Encrypt sensitive values before storing | |
| 258 | const encryptedDbPassword = encrypt(process.env.DB_PASSWORD!) | |
| 259 | ||
| 260 | // Decrypt when needed | |
| 261 | const dbPassword = decrypt(encryptedDbPassword) | |
| 262 | ``` | |
| 263 | ||
| 264 | ### Using AWS Secrets Manager | |
| 265 | ||
| 266 | ```ts | |
| 267 | import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager' | |
| 268 | ||
| 269 | const client = new SecretsManagerClient({ region: 'us-east-1' }) | |
| 270 | ||
| 271 | async function getSecret(secretName: string): Promise<string> { | |
| 272 | const command = new GetSecretValueCommand({ SecretId: secretName }) | |
| 273 | const response = await client.send(command) | |
| 274 | ||
| 275 | if (response.SecretString) { | |
| 276 | return response.SecretString | |
| 277 | } | |
| 278 | ||
| 279 | throw new Error('Secret not found') | |
| 280 | } | |
| 281 | ||
| 282 | // Load secrets at startup | |
| 283 | async function loadSecrets() { | |
| 284 | const secrets = JSON.parse(await getSecret('my-app/production')) | |
| 285 | ||
| 286 | process.env.DB_PASSWORD = secrets.DB_PASSWORD | |
| 287 | process.env.STRIPE_SECRET_KEY = secrets.STRIPE_SECRET_KEY | |
| 288 | } | |
| 289 | ``` | |
| 290 | ||
| 291 | ### Using HashiCorp Vault | |
| 292 | ||
| 293 | ```ts | |
| 294 | import Vault from 'node-vault' | |
| 295 | ||
| 296 | const vault = Vault({ | |
| 297 | endpoint: process.env.VAULT_ADDR, | |
| 298 | token: process.env.VAULT_TOKEN, | |
| 299 | }) | |
| 300 | ||
| 301 | async function loadVaultSecrets() { | |
| 302 | const { data } = await vault.read('secret/data/my-app') | |
| 303 | ||
| 304 | Object.assign(process.env, data.data) | |
| 305 | } | |
| 306 | ``` | |
| 307 | ||
| 308 | ## Environment Helpers | |
| 309 | ||
| 310 | ### Checking Environment | |
| 311 | ||
| 312 | ```ts | |
| 313 | import { config } from '@stacksjs/config' | |
| 314 | ||
| 315 | function isProduction(): boolean { | |
| 316 | return config.app.env === 'production' | |
| 317 | } | |
| 318 | ||
| 319 | function isDevelopment(): boolean { | |
| 320 | return config.app.env === 'development' || config.app.env === 'local' | |
| 321 | } | |
| 322 | ||
| 323 | function isTesting(): boolean { | |
| 324 | return config.app.env === 'testing' | |
| 325 | } | |
| 326 | ||
| 327 | function isDebug(): boolean { | |
| 328 | return config.app.debug === true | |
| 329 | } | |
| 330 | ``` | |
| 331 | ||
| 332 | ### Environment-Based Execution | |
| 333 | ||
| 334 | ```ts | |
| 335 | // Only in development | |
| 336 | if (isDevelopment()) { | |
| 337 | console.log('Debug info:', data) | |
| 338 | } | |
| 339 | ||
| 340 | // Only in production | |
| 341 | if (isProduction()) { | |
| 342 | await sendToAnalytics(event) | |
| 343 | } | |
| 344 | ||
| 345 | // Toggle features | |
| 346 | const features = { | |
| 347 | newDashboard: process.env.FEATURE_NEW_DASHBOARD === 'true', | |
| 348 | betaAPI: process.env.FEATURE_BETA_API === 'true', | |
| 349 | } | |
| 350 | ``` | |
| 351 | ||
| 352 | ## Configuration Caching | |
| 353 | ||
| 354 | ### Cache Configuration | |
| 355 | ||
| 356 | ```bash | |
| 357 | # Cache all configuration for production | |
| 358 | bun run buddy config:cache | |
| 359 | ||
| 360 | # Clear cached configuration | |
| 361 | bun run buddy config:clear | |
| 362 | ``` | |
| 363 | ||
| 364 | ### Manual Caching | |
| 365 | ||
| 366 | ```ts | |
| 367 | import { writeFile, readFile } from 'fs/promises' | |
| 368 | ||
| 369 | async function cacheConfig() { | |
| 370 | const config = { | |
| 371 | app: (await import('./config/app')).default, | |
| 372 | database: (await import('./config/database')).default, | |
| 373 | services: (await import('./config/services')).default, | |
| 374 | } | |
| 375 | ||
| 376 | await writeFile( | |
| 377 | 'storage/framework/cache/config.json', | |
| 378 | JSON.stringify(config) | |
| 379 | ) | |
| 380 | } | |
| 381 | ||
| 382 | async function loadCachedConfig() { | |
| 383 | try { | |
| 384 | const cached = await readFile('storage/framework/cache/config.json', 'utf-8') | |
| 385 | return JSON.parse(cached) | |
| 386 | } catch { | |
| 387 | return null | |
| 388 | } | |
| 389 | } | |
| 390 | ``` | |
| 391 | ||
| 392 | ## Best Practices | |
| 393 | ||
| 394 | ### DO | |
| 395 | ||
| 396 | ```ts | |
| 397 | // Use config helper | |
| 398 | const appUrl = config.app.url | |
| 399 | ||
| 400 | // Use default values | |
| 401 | const timeout = process.env.REQUEST_TIMEOUT || '30000' | |
| 402 | ||
| 403 | // Validate at startup | |
| 404 | if (!process.env.STRIPE_SECRET_KEY && isProduction()) { | |
| 405 | throw new Error('STRIPE_SECRET_KEY is required in production') | |
| 406 | } | |
| 407 | ||
| 408 | // Type coerce properly | |
| 409 | const port = parseInt(process.env.PORT || '3000', 10) | |
| 410 | const debug = process.env.DEBUG === 'true' | |
| 411 | ``` | |
| 412 | ||
| 413 | ### DON'T | |
| 414 | ||
| 415 | ```ts | |
| 416 | // Don't commit .env files | |
| 417 | // Add to .gitignore: .env*, !.env.example | |
| 418 | ||
| 419 | // Don't hardcode secrets | |
| 420 | const apiKey = 'sk_live_xxx' // Bad! | |
| 421 | ||
| 422 | // Don't access process.env directly in app code | |
| 423 | const dbHost = process.env.DB_HOST // Use config.database.host instead | |
| 424 | ||
| 425 | // Don't use string comparison for booleans | |
| 426 | if (process.env.DEBUG) { } // 'false' is truthy! | |
| 427 | ``` | |
| 428 | ||
| 429 | ## Example .env.example | |
| 430 | ||
| 431 | ```env | |
| 432 | # Application | |
| 433 | APP_NAME="My App" | |
| 434 | APP_ENV=local | |
| 435 | APP_DEBUG=true | |
| 436 | APP_URL=http://localhost:3000 | |
| 437 | APP_KEY= | |
| 438 | ||
| 439 | # Database | |
| 440 | DB_CONNECTION=mysql | |
| 441 | DB_HOST=127.0.0.1 | |
| 442 | DB_PORT=3306 | |
| 443 | DB_DATABASE=stacks | |
| 444 | DB_USERNAME=root | |
| 445 | DB_PASSWORD= | |
| 446 | ||
| 447 | # Cache & Session | |
| 448 | CACHE_DRIVER=file | |
| 449 | SESSION_DRIVER=file | |
| 450 | ||
| 451 | ||
| 452 | MAIL_MAILER=log | |
| 453 | MAIL_FROM_ADDRESS=hello@example.com | |
| 454 | MAIL_FROM_NAME="${APP_NAME}" | |
| 455 | ||
| 456 | # AWS (optional) | |
| 457 | AWS_ACCESS_KEY_ID= | |
| 458 | AWS_SECRET_ACCESS_KEY= | |
| 459 | AWS_DEFAULT_REGION=us-east-1 | |
| 460 | ||
| 461 | # Stripe (optional) | |
| 462 | STRIPE_SECRET_KEY= | |
| 463 | STRIPE_PUBLISHABLE_KEY= | |
| 464 | STRIPE_WEBHOOK_SECRET= | |
| 465 | ``` | |
| 466 | ||
| 467 | This documentation covers the essential environment configuration and secrets management functionality. Each approach is designed for secure and maintainable configuration handling. | |