Documenting .env files for nodejs Projects

The original post is published on my Blog at mrsauravsahu

Note: There’s a video version available where I actually build this project and deploy it to npmjs

Documentation of any sort looks like an overhead at the time, but pays off really well for projects that need to be maintained for a long time, when teams change, when onboarding new members, and a whole lot others.

For nodejs projects, application configuration is usually read from which in turn, come from a place like ENVIRONMENT variables or a configuration file like . During development, this package, is a great tool to set your environment variables.

Documentation is Key

For large projects with even larger teams, code-base changes constantly and so does the configuration. So documentation is key to keep anyone who uses the code-base later.

A typical file looks like this (it’s a collection of key=value pairs)

# The Node environment
NODE_ENV=development
# Url to a third party service
API_SERVICE_URL=https://mrsauravsahu.tech/posts/41/file

Since the value could contain sensitive information, to document this, we should ideally omit the value from each key=value pair and add this template of sorts to source control, which look something like the example below:

# The Node environment
NODE_ENV=
# Url to a third party service
API_SERVICE_URL=

What did I build?

I created an npm package which generates these template files from the real .env file, called [gen-env-template](https://npmjs.com/gen-env-template).
This is a dev tool so you can install it as a devDependency.

# Use your favorite package manager to install this. 
# (You can use npx to run directly as well)
npm i -D gen-env-template

Now that we have the package, we can pass in the `.env` file we’re using and path to the outfile file. For example, if this is our input file -

➜ cat .env
# The Node environment
NODE_ENV=
# Url to a third party service
API_SERVICE_URL=

We can generate our template file with this command

➜ ./node_modules/.bin/gen-env-template .env template.env

Now we get the generated template file

➜ cat template.env
# The Node environment
NODE_ENV=
# Url to a third party service
API_SERVICE_URL=

Now, this file can be safely committed to source control as all secrets have been omitted. You can find the Github repository for this project here — mrsauravsahu/gen-env-template on Github

Opinions are my own. Full Stack Engineer. CEO of “it was just working 🤷‍♂️”