Search code examples
reactjsenvironment-variablesstripe-paymentsnext.jsvercel

Deploying Environment Variables to Vercel with nextjs


I am new to next.js and experiencing issues while trying to deploy environment variables to Vercel.

We are trying to deploy Stripe Payment Gateway to Vercel

Downloaded the Stripe Payment Gateway Sample code from
https://github.com/tmarek-stripe/demo-react-stripe-js

This is a nextjs application with a .env file that has a public and secret key pair. Everything works fine while running on localhost , also the projects work fine on Vercel when I include the .env file in the git repository

As soon as I include the .env file in gitignore and push the updates to the repository , the .env file would not be shown and I get 500 Server error while trying to make test payments

Error while making payments

Below is the code for payment 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");
  }
};

The .Env File looks like below

PUBLISHABLE_KEY=pk_test_key

SECRET_KEY=sk_test_Secret Key

Read all the available articles online with no luck.

No changes were made to the code apart from Public and Secret Key in .env file

Please let me know how to hide the Environment Variables(as it contains the secret key) and at the same time use it in the production environment

Any help would be appreciated

Thanks in Advance


Solution

  • You can go to vercel.com, log-in to your account, open the project, go to settings, and then environment variables. There you can set variables for production, preview, and development.

    According to their documentation that's the only way to achieve different Environment Variables based on the Environment (Development, Preview, or Production). https://vercel.com/docs/build-step#environment-variables