jhamm
jhamm

Reputation: 25062

How do I use dotEnv when there is no .env file?

I have a project that locally has a .env file. When I set up the environment variables on my local machine I use:

import dotEnv from "dotenv";
dotEnv.config();

It find the .env and loads up all the variables. When I push the project to Heroku, I don't push up the .env file. I expected dotEnv to understand that, but I get this error:

{ Error: ENOENT: no such file or directory, open '.env'

How do I get around that I am not pushing up a .env file? What is the proper way to use .dotEnv?

Upvotes: 0

Views: 3303

Answers (2)

maxbeatty
maxbeatty

Reputation: 9325

I'm a contributor to the dotenv module. You can safely ignore this error. It is returned for your convenience in case something isn't working as expected.

Upvotes: 3

Robert Moskal
Robert Moskal

Reputation: 22553

I don't much like the solution proposed here: https://github.com/motdotla/dotenv/issues/126 It amounts to conditionally requiring /dotenv depending on an environment variable being set. This seems brittle and like extra work to me.

The neatest solution for this I've found doesn't pollute my production code with any references to dotenv at all. Just include dotenv in your dev dependencies and run your app locally using the node require switch:

$ node -r dotenv/config ./lib/index.js

This is the same way you might load babel-register.

Now your code doesn't care about where the env variables come from. Works with nodemon, etc. too. You can even specify an alternate env file:

$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars

It's all on the npm page for the package.

Upvotes: 0

Related Questions