Next.js环境变量 #
一、环境变量基础 #
1.1 .env文件 #
bash
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
NEXT_PUBLIC_API_URL=https://api.example.com
SECRET_KEY=my-secret-key
1.2 文件优先级 #
| 文件 | 优先级 | 说明 |
|---|---|---|
| .env.local | 最高 | 本地覆盖 |
| .env.development | 中 | 开发环境 |
| .env.production | 中 | 生产环境 |
| .env | 最低 | 默认值 |
1.3 加载顺序 #
text
.env.local > .env.{NODE_ENV} > .env
二、变量类型 #
2.1 公开变量 #
以 NEXT_PUBLIC_ 开头的变量会暴露给客户端:
bash
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_GA_ID=UA-XXXXX-X
tsx
console.log(process.env.NEXT_PUBLIC_API_URL)
2.2 服务端变量 #
不带前缀的变量仅在服务端可用:
bash
DATABASE_URL=postgresql://...
SECRET_KEY=secret
API_SECRET=secret123
tsx
export default async function Page() {
console.log(process.env.DATABASE_URL)
return <div>Page</div>
}
2.3 变量对比 #
| 类型 | 前缀 | 访问位置 |
|---|---|---|
| 公开变量 | NEXT_PUBLIC_ | 客户端+服务端 |
| 私有变量 | 无 | 仅服务端 |
三、使用方式 #
3.1 服务端使用 #
tsx
export default async function Page() {
const dbUrl = process.env.DATABASE_URL
const secret = process.env.SECRET_KEY
return <div>Server Component</div>
}
3.2 客户端使用 #
tsx
'use client'
export default function ClientComponent() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL
return <div>API: {apiUrl}</div>
}
3.3 API路由使用 #
tsx
import { NextResponse } from 'next/server'
export async function GET() {
const apiKey = process.env.API_KEY
return NextResponse.json({ key: apiKey })
}
3.4 next.config.ts使用 #
typescript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
env: {
CUSTOM_KEY: process.env.CUSTOM_KEY,
},
}
export default nextConfig
四、运行时配置 #
4.1 开发环境 #
bash
npm run dev
加载 .env.development 和 .env.local
4.2 生产环境 #
bash
npm run build
npm run start
加载 .env.production 和 .env.local
4.3 测试环境 #
bash
npm run test
加载 .env.test
五、平台配置 #
5.1 Vercel #
- 进入项目设置
- 点击 “Environment Variables”
- 添加变量
5.2 Docker #
bash
docker run -e DATABASE_URL=postgresql://... nextjs-app
或使用 --env-file:
bash
docker run --env-file .env nextjs-app
5.3 Docker Compose #
yaml
services:
web:
environment:
- DATABASE_URL=postgresql://...
- NEXT_PUBLIC_API_URL=https://api.example.com
六、类型安全 #
6.1 类型定义 #
typescript
namespace NodeJS {
interface ProcessEnv {
NEXT_PUBLIC_API_URL: string
DATABASE_URL: string
SECRET_KEY: string
}
}
6.2 验证 #
tsx
function getEnv(key: string): string {
const value = process.env[key]
if (!value) {
throw new Error(`Missing environment variable: ${key}`)
}
return value
}
const apiUrl = getEnv('NEXT_PUBLIC_API_URL')
6.3 Zod验证 #
tsx
import { z } from 'zod'
const envSchema = z.object({
DATABASE_URL: z.string(),
NEXT_PUBLIC_API_URL: z.string().url(),
SECRET_KEY: z.string().min(32),
})
const env = envSchema.parse(process.env)
七、最佳实践 #
7.1 使用.env.example #
bash
DATABASE_URL=
NEXT_PUBLIC_API_URL=
SECRET_KEY=
7.2 不要提交敏感信息 #
gitignore
.env.local
.env*.local
7.3 区分环境 #
text
.env.development
.env.production
.env.test
7.4 使用默认值 #
tsx
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api'
八、总结 #
环境变量要点:
| 要点 | 说明 |
|---|---|
| .env文件 | 环境配置 |
| NEXT_PUBLIC_ | 公开变量 |
| 服务端变量 | 私有变量 |
| 文件优先级 | .env.local > .env |
| 类型安全 | 类型定义 |
下一步,让我们学习性能监控!
最后更新:2026-03-28