Variáveis de Ambiente e Gerenciamento de Segredos
Configure seu SaaS com segurança em diferentes ambientes gerenciando segredos, separando variáveis públicas e privadas e evitando expor chaves ao cliente.
Variáveis de Ambiente e Gerenciamento de Segredos é uma aula grátis de AI Powered SaaS: Stripe + Auth + Billing + Deploy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Powered SaaS: Stripe + Auth + Billing + Deploy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Perguntas Frequentes
A aula “Variáveis de Ambiente e Gerenciamento de Segredos” é grátis?
Sim — o texto completo de “Variáveis de Ambiente e Gerenciamento de Segredos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy, atualize para CoddyKit PRO. O curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy inclui 4 aulas no total.
O que vou aprender em “Variáveis de Ambiente e Gerenciamento de Segredos”?
Configure seu SaaS com segurança em diferentes ambientes gerenciando segredos, separando variáveis públicas e privadas e evitando expor chaves ao cliente. Você pratica AI Powered SaaS: Stripe + Auth + Billing + Deploy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar AI Powered SaaS: Stripe + Auth + Billing + Deploy?
Nenhuma experiência prévia é necessária. AI Powered SaaS: Stripe + Auth + Billing + Deploy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Variáveis de Ambiente e Gerenciamento de Segredos”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de AI Powered SaaS: Stripe + Auth + Billing + Deploy?
Sim. Cada aula de AI Powered SaaS: Stripe + Auth + Billing + Deploy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Introdução à sinergia entre SaaS e IA
- Escolha da sua pilha tecnológica
- Inicialização e estrutura do projeto
- Variáveis de Ambiente e Gerenciamento de Segredos