'Stripe payment Error using evn variables react.js node.js

im trying to use stripe.charges like this

const router = require("express").Router();
const stripe = require("stripe")(process.env.STRIPE_KEY);

router.post("/payment", (req, res) => {
  stripe.charges.create(
    {
      source: req.body.tokenId,
      amount: req.body.amount,
      currency: "usd",
    },
    (stripeErr, stripeRes) => {
      if (stripeErr) {
        res.status(500).json(stripeErr);
      } else {
        res.status(200).json(stripeRes);
      }
    }
  );
});

module.exports = router;

but its giving me an error when i call the api from my client: "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY"

now if i change the stripe object and use the key string directly insted of (process.env.STRIPE_KEY) like

 const stripe = require("stripe")("KEYSTRING GOS HERE")

it works the way i want to but i dont think i should put my KEY there

i checked my .env filed and the env variable is called STRIPE_KEY there



Solution 1:[1]

Soved the problem by puting:

 const dotenv = require("dotenv"); 
 dotenv.config();

at the very start of my index.js file before it was after some other imports

Solution 2:[2]

Use

const stripe = require("stripe")(process.env.STRIPE_KEY);

under

const dotenv = require("dotenv"); 
 dotenv.config();

It solved my problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marquez Ludin Albarado Jaimes
Solution 2 Tasnim Tanzim Pricila