NextJS 中的环境变量未定义

Environment Variables in NextJS are Undefined

我正在使用 next-auth 库,它需要使用如下环境变量:

  Providers.GitHub({
    clientId: process.env.GITHUB_ID,
    clientSecret: process.env.GITHUB_SECRET,
  }),

但是,当我测试 next-auth 时它不起作用,在我看来原因是因为这些变量没有正确加载。因此,我做了一些测试,看看我是否可以在我的应用程序中访问环境变量,但测试表明我不能。

测试是这样进行的:

// .env.local (root level)

NEXT_PUBLIC_ENV_LOCAL_VARIABLE="public_variable_from_env_local"

然后我将以下代码添加到我的站点:

  <h2>test one start</h2>
    {process.env.NEXT_PUBLIC_TEST_ONE}
  <h2>test one end</h2>

  <Spacer />

  <h2>test two start</h2>
    {process.env.TEST_TWO}
  <h2>test two end</h2>

在这种情况下,test one starttest one end 都出现了,但是环境变量没有出现。 test two starttest two end也是如此。

我用 console.log 做了一个类似的测试 - 即:

  console.log("test one", process.env.NEXT_PUBLIC_TEST_ONE)
  console.log("test two", process.env.TEST_TWO)

结果如下:

test one undefined
test two undefined

简而言之,无论出于何种原因,我似乎无法在我的 nextjs 应用程序中加载环境变量。不来自 next-auth,不在代码中,也不在 console.log 中。变量未定义,我不知道为什么。

有什么想法吗?

谢谢。

.env.* 文件在服务器启动时加载。因此,除非您重新启动 dev/prod 服务器,否则不会应用对它们的任何修改。

只需暂停进程 (Ctrl+C/Z) 并重新运行 next dev/next start 即可使它们正常工作。请注意,如果您在静态生成的页面中使用它们,则在开始生产模式之前可能还需要重新构建项目 (next build)。

搜索 next.js documentation 我发现了这个:

// file: next.config.js

module.exports = {
 env: {
    customKey: 'my-value',
 },
}

// Now you can access process.env.customKey 

// For example, the following line:
// return <h1>The value of customKey is: {process.env.customKey}</h1>

// Will end up being:
// return <h1>The value of customKey is: {'my-value'}</h1>

看来,如果您使用的是 next.js 版本 9.4 或之前的版本,您可以将环境变量放入 next.config.js

它们还包括一个警告:

Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

如果您使用的是 9.4+ 版本,documentation 表示您可以使用 .env.local 文件并在环境变量前加上 NEXT_PUBLIC_它们暴露在浏览器中。

此方法值得注意的是:为了保证 server-only 秘密的安全,Next.js 在构建时将 process.env.* 替换为正确的值。 这意味着 process.env 不是标准的 JavaScript 对象,因此您不能使用对象解构。