All Articles

How to load dotenv (.env) file from shell

Hi, there 👋

Today I was doing a microservice crafted on top of TypeScript, gRPC, CockroachDb and got a need to build and run it locally.

For development purposes I use .env which is one of the most popular. It provides a capability to keep env variables in the file and load it in development mode.

Here is an example for using dotenv:

const dotenv = require('dotenv');
dotenv.config();

Where the .env file could look as following:

PORT=50051
API_URL=https://andrew.red

Everything looks smooth and easy for development. However, for production build I don’t really want this to be loaded from a file and instead provided from env variables.

At the same moment for the local run I don’t want to do export variable="value" manually multiple times.

So, I’ve just used the same .env file to load env variables into shell:

set -a; source .env; set +a
node ./index.js

If we go deeper in attempts to understand this code, let’s see commands one by one.

Builtin set allows you to change the values of shell options and set the positional parameters.

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts.

In overall, it does the magic 🧙

Share your thoughts

Happy coding! 🚀

Published Dec 1, 2021

Passionate software engineer with expertise in software development, microservice architecture, and cloud infrastructure.