Home > Back-end >  API router doesn't read Stripe API key stored in .env file
API router doesn't read Stripe API key stored in .env file

Time:07-12

I made an .env file and put my stripe key in there. then in backend API/router, i simply imported that key to work with it.

I made a checkout request but i'm still getting this error in console.dev tab:

POST http://localhost:5000/api/checkout/payment 500 (Internal Server Error)

Also, in network tab, the payment responses with header message says:

message: "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'). ..."

After some checks here and there, i found a work around that solved my problem and checkout passed successfully, but i can't cosider it as a solution because the stripe private key must be stored in .env file ofcourse. How to store stripe private key in .env file and make it accessible?

Stripe.js code (which cause my problem):

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;

Stripe.js (My work around code):

const router = require("express").Router()
const KEY = "sk_test_51LJh5TCx0CP76PWrVKMBkQfuhm7tcgYZ2bhkx3yLApn3ugWiNEpd65V78uK3Z2nJzNSt2Gaga1bkFYZIAWoddJZ00n9quwkln" //i dont mind share this key public
const stripe = require("stripe")(KEY)

router.post("/payment", (req, res) => {
    stripe.charges.create(
        {
            source: req.body.tokenId,
            amount: req.body.amount,
            currency: "TTD"
        },

        (stripeErr, stripeRes) => {
            if (stripeErr) {
                res.status(500).json(stripeErr);
            } else {
                res.status(200).json(stripeRes);
            }
        }
    );
})

module.exports = router;

CodePudding user response:

In order to use .env files you need dotenv

First install it: npm i dotenv

Then add this to your code before you use environment variables:

require('dotenv').config()
  • Related