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'});
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'});
..
routes/stripe.js
const stripe = require("stripe")(process.env.STRIPE_KEY);
.env
STRIPE_KEY=key_goes_here
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")
Personally I like to define my environment variables at the start of the server file.
Top comments (3)
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 ;)Awesome, I'll check it out
A popup dialog appears, click on environment variables. In the popup that appears, there are two sections.
hoodoo spells for love