DEV Community

Cover image for Better DX for .env
Sibelius Seraphini for Woovi

Posted on

Better DX for .env

Introduction

In the realm of modern software development, managing environment variables is a critical aspect of building secure and robust applications. dotenv-safe, an extension of the popular dotenv module, offers an added layer of security to the process of loading environment variables. In this blog post, we'll explore the significance of dotenv-safe and how it can contribute to bolstering the security posture of your applications.

Making some environment variables required

Some programs require some environment variables to be set to run properly.
We can ensure some environment variables are set using dotenv-safe .env.example file

Here is to code to ensure:

config.ts

import dotenvSafe from 'dotenv-safe';
import path from 'path';

const cwd = process.cwd();

const root = path.join.bind(cwd);

dotenvSafe.config({
  path: root('.env'),
  sample: root('.env.example'),
});
Enter fullscreen mode Exit fullscreen mode

if our .env.example has this content:

MONGO_URI=
Enter fullscreen mode Exit fullscreen mode

dotenv-safe will throw if the environment variable MONGO_URI is not set in the environment or inside .env file.

config.ts pattern

Instead of consuming environment variables directly from process.env.<>, we prefer to create a config variable inside config.ts, like this:

export const config = {
   MONGO_URI: process.env.MONGO_URI as string
} as const,
Enter fullscreen mode Exit fullscreen mode

This provides a few benefits like typesafe environment variables, and also makes sure we loaded the environment variables from .env file before calling process.env.<>.

Production usage

Be careful when adding a new environment variable to .env.example, as this can break your production environment if you didn't set the environment variable in production before the deployment.

In production we only consume environment variables directly from Kubernetes secrets, there are no .env files for production. .env file is a better dx for development.

In short

This tiny improvement in DX can help you avoid undefined environment variables when running the codebase.
Every time a developer is confused or gets in a crypt error, we try to think of ways to avoid this ever happening again, or provide a better error message or invariant.


Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Maria Ziegler on Unsplash

Top comments (0)