How to Use Environment Variables (env) in ExpressJs

Gerald - Oct 21 '21 - - Dev Community

Well, hello!
If you're coming from frontend development with Vue, or React, you know that environment variables (.env) are initialized behind the scenes i.e. You don't have to require and use dotenv. However, when writing backend with, Expressjs, for instance, you have to initialize it like so:-

require('dotenv').config({path: './.env'});
Enter fullscreen mode Exit fullscreen mode

Problem: Env variable not found

A friend was building an API with Expressjs. He needed to connect to stripe for the payments. The response from stripe was Authorization headers are missing. He couldn't get why this was happening despite the fact that he had defined the Stripe Secret Key on the environment variables (.env), and used it when initializing "stripe" npm package.

Server.js

..
const stripeRoute =  require("./routes/stripe")
..
require('dotenv').config({path: './.env'});
..
Enter fullscreen mode Exit fullscreen mode

routes/stripe.js

const stripe = require("stripe")(process.env.STRIPE_KEY);
Enter fullscreen mode Exit fullscreen mode

.env

STRIPE_KEY=key_goes_here
Enter fullscreen mode Exit fullscreen mode

Soln: Define environment variables before using them

The error was as a result of defining the Stripe routes before requiring the .env. This solved his issue:

require('dotenv').config({path: './.env'});

const stripeRoute =  require("./routes/stripe")

Enter fullscreen mode Exit fullscreen mode

Personally I like to define my environment variables at the start of the server file.

. . . . . .
Terabox Video Player