为什么在 Next.js 中未定义解构的环境变量?
Why are destructured environment variables undefined in Next.js?
在我的 Next.js 应用程序中,我创建了一个 .env
文件,其中包含一个名为 API_KEY
.
的变量
解构值导致 undefined
,如下所示:
const { API_KEY } = process.env; // = undefined
const key = process.env.API_KEY; // = 'value'
有人可以解释为什么 process.env
没有在此处填充正确的值吗?
来自the docs:
Note: In order to keep server-only secrets safe, Next.js replaces process.env.*
with the correct values at build time. This means that process.env
is not a standard JavaScript object, so you’re not able to use object destructuring.
以及客户端 React 组件
The value will be inlined into JavaScript sent to the browser because of the NEXT_PUBLIC_
prefix. This inlining occurs at build time, so your various NEXT_PUBLIC_
envs need to be set when the project is built.
在我的 Next.js 应用程序中,我创建了一个 .env
文件,其中包含一个名为 API_KEY
.
解构值导致 undefined
,如下所示:
const { API_KEY } = process.env; // = undefined
const key = process.env.API_KEY; // = 'value'
有人可以解释为什么 process.env
没有在此处填充正确的值吗?
来自the docs:
Note: In order to keep server-only secrets safe, Next.js replaces
process.env.*
with the correct values at build time. This means thatprocess.env
is not a standard JavaScript object, so you’re not able to use object destructuring.
以及客户端 React 组件
The value will be inlined into JavaScript sent to the browser because of the
NEXT_PUBLIC_
prefix. This inlining occurs at build time, so your variousNEXT_PUBLIC_
envs need to be set when the project is built.