DEV Community

loading...

dotenv and relative paths

eriesgo profile image Enrique Riesgo ・1 min read

Most of you are using dotenv, the famous "zero-dependency module that loads environment variables from a .env file into process.env".

Although I usually work in serverless environments like the combo node.js/AWS Lambda where dotenv is not required, we use it for running local Express wrappers to the node.js lambdas and to control the environment while doing unit tests.

Unless you have a clear and well know pattern for using it, you can fall into the trap of thinking that dotenv works like the built-in require function and accepts relative paths. Proximity with with require statements doesn't help. Something like:

const { myfunction } = require("../mymodule.js");
require("dotenv").config({ path: `../.env.test` }); 

But, this will not work.

You know why? Dotenv does only accept absolute paths when it is configured. The official docummentation is not very clear on that and you can spend a few hours trying to figure out why your environment variables are not loaded in our unit tests.

So my recommendation is to ellaborate your own working dotenv piece of code, save it safe, and reuse it every time you need to set the environment variables of your node.js apps.

This is an example of the approach I follow.

const { myfunction } = require("../mymodule.js");
require("dotenv").config({ path: __dirname + `/../.env.test` }); 

Notice we use __dirname function to get the path of the current module and then we append the relative path to the .env config file.

I hope this helps you and never get stuck with this trap.

Happy coding!

Discussion (1)

pic
Editor guide
Collapse
mgrachev profile image
Grachev Mikhail

In addition to using environment variables I can recommend the tool github.com/dotenv-linter/dotenv-li... - it’s a lightning-fast linter for .env files.