【问题标题】:NextJS - Set dynamic environment variables at the start of the applicationNextJS - 在应用程序启动时设置动态环境变量
【发布时间】:2018-10-29 04:18:32
【问题描述】:

在我们的实施过程中,我们创建了一个单独的建筑,并经历了不同的阶段(集成、登台和生产)。在每种环境中,我们都有不同的环境差异。

问题是,当我们启动服务器时,它只引用服务器上的环境变量,而在客户端,process.env 文件是空的。

堆栈:“下一个”:“5.0.0”“babel-plugin-inline-dotenv”:“1.1.1”,

用于加载 .env 文件使用“inline-dotenv”

【问题讨论】:

标签: environment-variables client-side nextjs


【解决方案1】:

您可以在 next.config.js 文件中使用publicRuntimeConfig

例子:

// next.config.js
module.exports = {
  serverRuntimeConfig: { // Will only be available on the server side
    mySecret: 'secret'
  },
  publicRuntimeConfig: { // Will be available on both server and client
    staticFolder: '/static',
    mySecret: process.env.MY_SECRET // Pass through env variables
  }
}

请注意,publicRuntimeConfig.mySecret 的值现在是从环境变量中获取的。 所以现在你可以通过 importin next/config 读取该值

例子:

import getConfig from 'next/config';

const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.mySecret);

来源:next.js docs

【讨论】:

  • 不幸的是,这不再适用于当前版本 (12) 的 Next,因为它们将 process.env.* 替换为构建时的实际值。
猜你喜欢
  • 2023-04-07
  • 2021-12-10
  • 2018-09-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多