Direnv has become a very important part of my development environments.
Direnv reads .envrc files and sets up your environment accordingly.
# shellcheck shell=bash
# .envrc file for direnv.
# If you use VS Code, please use the `direnv` extension.
# https://marketplace.visualstudio.com/items?itemName=mkhl.direnv
# Use nix-direnv
# https://github.com/nix-community/nix-direnv
# Ensures that flake.nix gets evaluated.
use flake
PATH_add scripts
PATH_add node_modules/.bin
# Load variables from .env
dotenv_if_existsWhen you have direnv installed and you enter the directory containing the .envrc file, the lines
above get executed.
I recommend the VS Code Direnv Extension if you use VS Code. It enables your custom environment for tasks started by VS Code (for example, AI coding agents).
The example above uses Nix Flakes via use flake, but that’s just an example. Ignore it if you
don’t use Nix (yet).
Next, I update PATH so executables from the environment are found first.
In the last line (dotenv_if_exists), I load secrets from a .env file. If you keep secrets out of .envrc,
you can commit .envrc to Git so all team members get the same environment.
My ~/.config/direnv/direnv.toml:
[global]
hide_env_diff = true
log_filter = "^$"
[whitelist]
prefix = [ "/home/guettli/projects", "/home/guettli/syself" ]There are two directories I trust, because they contain trusted Git repos. Changes to .envrc files
in those directories need no manual approval.
It is common to store secrets in a .env file. This is easy to set up, but it has drawbacks:
- Several developers need to sync the .env files.
- In CI config you often need these values, too.
- No version control. You don't see when a value was updated.
A pragmatic solution: Only store SOPS_AGE_KEY in .env and in CI. SOPS
enables you to keep the keys readable, and only encrypt the values. The encrypted values get stored
in git, so that changes to that file are visible. This means, you have only one place where
the credentials are stored: in your git repo. No worries, the secrets are encrypted. All you need is
SOPS_AGE_KEY.
Direnv works well together with Nix. I describe that here: guettli/switching-to-nix: Switching to Nix
Feedback is welcome. Just open an issue and tell me what you think.