Variables que se configuran fuera del código para almacenar secretos, configuraciones o valores que varían según el entorno (desarrollo, producción, etc.).
Las variables de entorno son valores configurables que se definen fuera del código fuente. Permiten: - Separar configuración de código - Manejar diferentes entornos (dev, staging, prod) - Almacenar secretos de forma segura - Cambiar comportamiento sin recompilar Nunca commitear archivos .env con secretos. Usar gestores de secretos en producción (AWS Secrets Manager, Vault).
# .env - Variables locales (NO commitear) DATABASE_URL=postgresql://user:pass@localhost:5432/mydb JWT_SECRET=super-secret-key-change-in-production API_KEY=sk_test_123456 NODE_ENV=development PORT=3000 # .env.example - Plantilla para el equipo (SÍ commitear) DATABASE_URL= JWT_SECRET= API_KEY= NODE_ENV=development PORT=3000 // Cargar variables con dotenv (Node.js) import 'dotenv/config'; // o import dotenv from 'dotenv'; dotenv.config(); // Acceder a variables const dbUrl = process.env.DATABASE_URL; const port = process.env.PORT || 3000; // Validar variables requeridas const requiredEnvVars = ['DATABASE_URL', 'JWT_SECRET']; for (const envVar of requiredEnvVars) { if (!process.env[envVar]) { throw new Error(`Missing required env var: ${envVar}`); } } // TypeScript - Tipado de env vars declare global { namespace NodeJS { interface ProcessEnv { DATABASE_URL: string; JWT_SECRET: string; NODE_ENV: 'development' | 'production' | 'test'; PORT?: string; } } } // Vite/React - Variables cliente (prefijo VITE_) const apiUrl = import.meta.env.VITE_API_URL;