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

Viv*_*vek 2 environment-variables stripe-payments reactjs next.js vercel

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

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

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

这是一个带有 .env 文件的 nextjs 应用程序,该文件具有公钥和密钥对。在 localhost 上运行时一切正常,当我将 .env 文件包含在 git 存储库中时,项目在 Vercel 上也正常运行

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

付款时出错

下面是支付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");
  }
};
Run Code Online (Sandbox Code Playgroud)

.Env 文件如下所示

PUBLISHABLE_KEY=pk_test_key

SECRET_KEY=sk_test_Secret Key
Run Code Online (Sandbox Code Playgroud)

在线阅读所有可用的文章但运气不佳。

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

请让我知道如何隐藏环境变量(因为它包含密钥)并同时在生产环境中使用它

任何帮助,将不胜感激

提前致谢

Sin*_*hin 5

您可以访问 vercel.com,登录您的帐户,打开项目,进入设置,然后进入环境变量。您可以在其中设置用于生产、预览和开发的变量。

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