C.W.K.
Stream
Lesson 07 of 10 · published

direnv: Per-Directory Environment

~10 min · direnv, envrc, project

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The problem direnv solves

You want OPENAI_API_KEY set when you're in ~/projects/ai-app and not set when you leave. Manually export-ing and unset-ing is error-prone. direnv automates it: create .envrc in the directory, allow it once, and direnv loads/unloads on every cd.

Setup

brew install direnv
# Add to ~/.zshrc, end of file
eval "$(direnv hook zsh)"

Use

# inside ~/projects/ai-app
echo 'export OPENAI_API_KEY=sk-...' > .envrc
echo 'PATH_add bin' >> .envrc      # adds ./bin to PATH
direnv allow                              # one-time approval
echo $OPENAI_API_KEY                      # set
cd /tmp
echo $OPENAI_API_KEY                      # empty

The direnv allow step is the security gate — random .envrc files don't auto-execute when you cd into them.

Common .envrc patterns

  • export DATABASE_URL=postgres://...
  • PATH_add ./bin — prepend a project bin directory.
  • source_env ../shared.envrc — share a parent's envs.
  • layout python3 — auto-create and activate a venv.
  • use mise — bridge to a project-pinned mise tool stack.

Why this beats alternatives

Compared to manual export, direnv never forgets to unset on exit. Compared to dotfile-loader frameworks, it's tiny (one binary). Compared to docker-compose for env, it's instant — no container start. The Pippa stack uses direnv to auto-activate the conda env when you cd into cwkPippa, for the same reason.

Code

Bootstrap a project envrc·bash
cd ~/projects/myapp
cat > .envrc <<'EOF'
export DATABASE_URL=postgres://localhost/myapp
PATH_add bin
layout python3
EOF
direnv allow
which python3   # should be inside the venv now

External links

Exercise

Install direnv. Hook it in .zshrc. In a sandbox project, write an .envrc with export FOO=bar. direnv allow. Then cd .. and back, and watch the variable load/unload. Add .envrc to .gitignore.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.