Home > Software engineering >  Stripe publish key stored in .env can't be read by React
Stripe publish key stored in .env can't be read by React

Time:07-17

I'm building an e-commerce site, the Cart page holds the checkout process's button.

I created an .env file inside front-side folder, then pasted in my Publishable key:

.env code:

REACT_APP_STRIPE = pk_test_51LJh5TCx0CP76PWrc0hRSESvbF00x8voeXAS...

Cart.jsx page code:

import StripeCheckout from "react-stripe-checkout";

const KEY = process.env.REACT_APP_STRIPE;
//...
            <StripeCheckout
              name="ShopTn"
              image="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTWHNj9PK7N9WLGXRF5FDbA7XdtjH6caLiwnBW2__PWC3crRyS_XiocBVKnP9GONqvVp9A"
              description={`Your total is ${cart.total} DT`}
              billingAddress
              shippingAddress
              amount={cart.taotal * 100}
              currency="TTD"
              token={onToken}
              stripeKey={KEY}
            >
              <Button
                style={{
                  border: "none",
                  width: 120,
                  borderRadius: 5,
                  padding: "20px",
                  backgroundColor: "black",
                  color: "white",
                  fontWeight: "600",
                  cursor: "pointer",
                }}
              >
                CHECKOUT NOW
              </Button>
            </StripeCheckout>

Warning errors i'm receiving:

I'm getting this error in console.dev:

Warning: Failed prop type: The prop stripeKey is marked as required in ReactStripeCheckout, but its value is undefined.

Edit (Please ignore this edit part): upon pressing CHECKOUT NOW button, i'm expecting to open stripe checkout interface directly, but i'm getting this JS alert saying:

Stripe Checkout is missing the required key parameter. Please contact the website owner or [email protected].

Edit:

I tried put my publishable key in JSX (like this code below) and it works fine:

const KEY = "pk_test_51LJh5TCx0CP76PWrc0hRSESuLLs9TSjpI7bUnDdgu4r0w";

CodePudding user response:

The first error you are receiving is about a .map you are using in the Cart method that is not settings key property to each element created Read this for more information.

You have a spelling mistake in amount={cart.taotal * 100}.

And verify that the .env variables are getting loaded, for example by putting them into the JSX and verify their content.

Edit:

The code is all working correctly, the problem was solved by restarting the project after editing the .env, as it doesen't reload the key if using nodemon or similars (unlike next.js).

  • Related