Variables de entorno y gestión de secretos
Configure su SaaS de forma segura en distintos entornos gestionando secretos, separando variables públicas y privadas y evitando exponer claves al cliente.
Variables de entorno y gestión de secretos es una lección gratuita de AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Powered SaaS: Stripe + Auth + Billing + Deploy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Configuration Matters
A SaaS connects to databases, payment providers, and AI APIs — each with keys that differ per environment. Environment variables keep them out of code so one codebase runs anywhere.
The .env File
Local config lives in a .env file as plain key-value pairs. It's loaded at startup and must never be committed to git.
DATABASE_URL=postgresql://localhost/app
STRIPE_SECRET_KEY=sk_test_123
OPENAI_API_KEY=sk-abcNever Commit Secrets
Never commit secrets: add .env to .gitignore and ship a .env.example with empty values, so teammates know what to fill in without seeing real keys.
# .gitignore
.env
.env.localPublic vs Private Variables
In Next.js, only variables prefixed NEXT_PUBLIC_ reach the browser bundle — everything else stays server-only. Never prefix a real secret, or every visitor sees it.
NEXT_PUBLIC_APP_URL=https://app.com # safe in browser
STRIPE_SECRET_KEY=sk_live_xxx # server onlyReading Variables
Read variables through process.env. Server code can access any of them; client code only ever sees the public, NEXT_PUBLIC_ ones.
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const url = process.env.NEXT_PUBLIC_APP_URL;Validating Env at Startup
A missing key should fail fast, not at 2am in production. Validate required variables on boot with a schema like Zod so problems surface immediately.
import { z } from 'zod';
const env = z.object({
DATABASE_URL: z.string().url(),
STRIPE_SECRET_KEY: z.string().min(1)
}).parse(process.env);Per-Environment Files
Next.js loads .env.local, then .env.development or .env.production. These per-environment files keep different values cleanly separated.
Secrets in Hosting Platforms
In production you don't ship a .env file. Set variables in your host's dashboard — Vercel, Render — so they're injected securely at runtime.
vercel env add STRIPE_SECRET_KEY productionRotating Keys
If a key leaks, rotate it: generate a new one, update your env store, redeploy. Because keys live outside code, rotation is quick and low-risk.
Avoiding Common Leaks
Watch for common leaks: logging full process.env, returning secrets in API responses, hardcoding keys as fallbacks, or committing a real .env.
Best Practices
Best practices: keep secrets in .env and out of git, expose only truly public values with NEXT_PUBLIC_, validate at startup, and store prod secrets in your host.
Quick Check
Test your secrets knowledge.
Recap
Recap: store config in .env and keep it out of git, use NEXT_PUBLIC_ only for safe values, validate at startup, and set prod secrets in your host.
Preguntas frecuentes
¿La lección «Variables de entorno y gestión de secretos» es gratis?
Sí — el texto completo de «Variables de entorno y gestión de secretos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy, actualiza a CoddyKit PRO. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.
¿Qué aprenderé en «Variables de entorno y gestión de secretos»?
Configure su SaaS de forma segura en distintos entornos gestionando secretos, separando variables públicas y privadas y evitando exponer claves al cliente. Practicas AI Powered SaaS: Stripe + Auth + Billing + Deploy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar AI Powered SaaS: Stripe + Auth + Billing + Deploy?
No se requiere experiencia previa. AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Variables de entorno y gestión de secretos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy?
Sí. Cada lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción a SaaS y la sinergia con la IA
- Elección del stack tecnológico
- Inicialización y estructura del proyecto
- Variables de entorno y gestión de secretos