使用 nextjs 将环境变量部署到 Vercel

Deploying Environment Variables to Vercel with nextjs

我是 next.js 的新手,在尝试将环境变量部署到 Vercel 时遇到问题。

我们正在尝试将 Stripe 支付网关部署到 Vercel


下载了 Stripe 支付网关示例代码 https://github.com/tmarek-stripe/demo-react-stripe-js

这是一个带有 .env 文件的 nextjs 应用程序,该文件具有 public 和密钥对。 运行 在 localhost 上一切正常,当我在 git 存储库

中包含 .env 文件时,项目在 Vercel 上也能正常工作

一旦我将 .env 文件包含在 git忽略并将更新推送到存储库,.env 文件将不会显示,并且我在尝试进行测试付款时收到 500 服务器错误

Error while making payments

支付代码如下intent.js

import Stripe from "stripe";

const stripe = new Stripe(process.env.SECRET_KEY);

export default async (req, res) => {
  if (req.method === "POST") {
    try {
      const { amount } = req.body;
      
      const paymentIntent = await stripe.paymentIntents.create({
        amount,
        currency: "usd"
      });

      res.status(200).send(paymentIntent.client_secret);
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message });
    }
  } else {
    res.setHeader("Allow", "POST");
    res.status(405).end("Method Not Allowed");
  }
};

.Env 文件如下所示

PUBLISHABLE_KEY=pk_test_key

SECRET_KEY=sk_test_Secret Key

在线阅读所有可用文章,但没有成功。

除了 Public 和 .env 文件中的密钥外,没有对代码进行任何更改

请告诉我如何隐藏环境变量(因为它包含密钥),同时在生产环境中使用它

如有任何帮助,我们将不胜感激

提前致谢

你可以去vercel.com,log-in到你的账户,打开项目,去设置,然后环境变量。您可以在那里设置生产、预览和开发变量。

根据他们的文档,这是根据环境(开发、预览或生产)实现不同环境变量的唯一方法。 https://vercel.com/docs/build-step#environment-variables

有人想出了一个 bash 脚本来上传 .env 文件

while IFS== read -r name value
do
  echo "$value" | vercel env add "$name" ""
done < ""

命令:

<script name> <file> <production | preview | development> 

我也认为最好有 vercel env push [environment] [file]

SOURCE