ข้ามไปยังเนื้อหา

Environment และ Configuration

env var เป็น server-only เป็น default มีแค่ตัวที่ขึ้นต้นด้วย NEXT_PUBLIC_ เท่านั้นที่ถูก inline เข้า client bundle เพราะฉะนั้น secret ห้ามมี prefix นั้นเด็ดขาด

env var ธรรมดาใช้ได้แค่ฝั่ง server พอใส่ prefix NEXT_PUBLIC_ Next.js จะ inline ค่านั้นเข้าไปใน JavaScript ที่ส่งไป browser ตอน build เหมาะกับ analytics id สาธารณะ แต่หายนะถ้าเป็น API secret

// Server Component or route — both work on the server
const dbUrl = process.env.DATABASE_URL // server-only, safe
const analyticsId = process.env.NEXT_PUBLIC_ANALYTICS_ID // also in the client bundle
.env.local
DATABASE_URL="postgres://user:pass@host:5432/db" # never prefix a secret
NEXT_PUBLIC_ANALYTICS_ID="abcdefghijk" # safe to expose

เพราะค่า NEXT_PUBLIC_ ถูกฝังตอน build การเปลี่ยนค่าแปลว่าต้อง rebuild ใหม่ ไม่ได้อ่านตอน runtime บน browser

Next.js โหลดไฟล์ .env หลายตัวและตัวที่ match ก่อนชนะ สำหรับ production ลำดับคือ .env.production.local แล้ว .env.local แล้ว .env.production แล้ว .env เก็บ secret ไว้ใน .env.local (gitignore) แล้ว commit เฉพาะ default ที่ปลอดภัย

.env # committed defaults, safe values only
.env.local # gitignored, real secrets
.env.development # loaded during next dev
.env.production # loaded during next build / next start

next.config.ts คือที่ที่เรา config ตัว framework เอง สี่ตัวที่ใช้บ่อยสุดคือ images.remotePatterns (อนุญาต image host ภายนอก), redirects, rewrites และ headers

next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: 's3.amazonaws.com', pathname: '/my-bucket/**' },
],
},
async redirects() {
return [{ source: '/about', destination: '/', permanent: true }]
},
async rewrites() {
return [{ source: '/docs/:slug', destination: '/help/:slug' }]
},
async headers() {
return [
{
source: '/(.*)',
headers: [{ key: 'X-Frame-Options', value: 'DENY' }],
},
]
},
}
export default nextConfig
graph TD
  A["process.env.SECRET"] --> B["Server only"]
  C["process.env.NEXT_PUBLIC_ID"] --> B
  C --> D["Inlined into client bundle at build time"]
Where each env var can be read
Where is a plain (unprefixed) env var available?
What does the NEXT_PUBLIC_ prefix do?
Which file should hold real secrets?
Which next.config.ts key allows external image hosts?