Next.js 从 .env 文件加载环境变量,遵循一条重要的安全规则:变量默认仅限服务器,只有以 NEXT_PUBLIC_ 为前缀的变量才会暴露到浏览器。
文件
text
.env # loaded in all environments
.env.local # local overrides — GITIGNORED (put secrets here)
.env.development # only in `next dev`
.env.production # only in production builds
关键前缀规则
bash
# .env.local
DATABASE_URL=postgres://...secret...
NEXT_PUBLIC_API_URL=https://api.example.com
