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

时间:2020-11-04 16:37:56

标签: reactjs environment-variables stripe-payments next.js vercel

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

我们正在尝试将Stripe Payment Gateway部署到Vercel


下载了Stripe Payment Gateway示例代码 https://github.com/tmarek-stripe/demo-react-stripe-js

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

我将.env文件包含在gitignore中并将更新推送到存储库后,该.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

在线阅读所有可用文章,没有运气。

除了.env文件中的“公共密钥”和“秘密密钥”之外,未对代码进行任何更改

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

任何帮助将不胜感激

预先感谢

1 个答案:

答案 0 :(得分:3)

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

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