DEV Community

Cover image for How to Use Environment Variables (env) in ExpressJs
Gerald
Gerald

Posted on

How to Use Environment Variables (env) in ExpressJs

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.

Discussion (3)

Collapse
cytim profile image
Tim Wong • Edited on

Nice post! It's always my first line in server.js to init dotenv so everything else can consume the env-vars correctly.
I also published "A smarter dotenv for Node.js" recently to make .env more useful. Hope you will like it ;)

Collapse
geraldmuvengei06 profile image
Gerald Author

Awesome, I'll check it out

Collapse
fayelewis2 profile image
FayeLewis2

A popup dialog appears, click on environment variables. In the popup that appears, there are two sections.
hoodoo spells for love