NextJS + Heroku:环境变量未加载

4
我正在使用NextJS和Heroku。
在首页-首次加载返回我在getInitialProps中获取的数据,但在常规函数中,由于缺少环境变量,会出现错误消息。
当我转到另一页时,我会收到相同的错误,但是当我刷新页面时,可以看到在getInitialProps中获取的数据。但同样,在常规函数中,由于缺少环境变量,我会收到错误消息。
在本地它可以工作。 我尝试过dotenv-webpack,但没有帮助。 我在Heroku中添加了配置变量。
有什么想法吗?
这是我的next.config.js文件:
const { parsed: localEnv } = require('dotenv').config()
const webpack = require('webpack')
const Dotenv = require('dotenv-webpack')
const path = require('path')

module.exports = {
    //target: 'serverless',
    webpack(config) {
        config.plugins.push(new webpack.EnvironmentPlugin(localEnv))
        config.node = {fs: "empty"};
        config.plugins = config.plugins || []

        config.plugins = [
            ...config.plugins,

            // Read the .env file
            new Dotenv({
                path: path.join(__dirname, '.env'),
                systemvars: true
            })
        ]

        return config
    },
    publicRuntimeConfig: {
        ADDRESS: process.env.ADDRESS,
        API_TOKEN: process.env.API_TOKEN,
        INFURA_API_KEY: process.env.INFURA_API_KEY
    }
}

你是如何设置环境变量的?在生产环境中,你可能不应该使用 .env 文件。Heroku 原生支持通过环境变量进行配置 - Chris
我使用了Heruko的仪表板选项,并像代码中所示使用它 - 例如:process.env.ADDRESS。 - Karin C
但正如我所说,该代码在服务器端渲染(索引的第一次加载和通常情况下每个刷新后的页面)中使用环境变量,因此问题可能不是我设置配置变量的方式。在常规函数(由按钮点击触发)中,我会收到有关缺少变量的消息,并且在导航到其他页面后也会收到该消息。 - Karin C
2个回答

5

在next.js的github页面上找到了答案:https://github.com/zeit/next.js/issues/6533

我尝试了几种不同的方式来解决这个问题,但都失败了。

使用dotenv-webpack设置环境变量对我没有用。成功的方法是在next.config.js中设置env,像这样:

const { parsed: localEnv } = require('dotenv').config()
const webpack = require('webpack');

const path = require('path')

module.exports = {
    webpack(config) {
        config.plugins.push(new webpack.EnvironmentPlugin(localEnv))
        config.node = {fs: "empty"};
        config.plugins = config.plugins || []

        config.plugins = [
            ...config.plugins,
        ]

        return config
    },
    env: {
        ADDRESS: '0xd6F75293ec795',
        API_TOKEN: 'YUBKzlbA2eFmNbkzk',
        INFURA_API_KEY: '97eb10aac61799f9e865',
        MNEMONIC: 'my not so secret for testing password',
    }
}

这帮助我实现了部署。向你们致敬。X - Aid19801
你如何使这个环境特定? - Blueboye
@Blueboye - 在文档中提到这是一个Node.js模块而不是JSON文件(“它被Next服务器和构建阶段使用,而不包含在浏览器构建中。”)。因此,您应该尝试使用next/constants来定义您想要的“phase”。 “'phase'是加载配置的当前上下文。” - Karin C
1
@KarinC 这种方法不会暴露你的机密吗?除非你是在说你没有对 next.config.js 进行版本控制,但考虑到你那里有自定义配置,我觉得这种可能性很小。 - iamcastelli
1
为了避免像您在这里做的那样硬编码您的值,您可以在构建时编写一个配置模块,并在此处导入该模块。 - Jasper Kennis
显示剩余2条评论

-1

以下是我在 next.config.js 中使用的方法:

if (process.env.NODE_ENV === 'development') {
  require('dotenv').config()
}

module.exports = {
  env: {
    API_URL: process.env.API_URL,
  }
}

这将使 API_URL 在客户端和服务器上,无论是在开发环境还是生产环境中都可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接