Software developers frequently juggle multiple projects with conflicting environment requirements: Project A needs NODE_ENV=development and Node 18, while Project B connects to a staging PostgreSQL database with custom credentials. Cluttering your global ~/.bashrc or manually running source .env on every terminal tab is error-prone. direnv hooks into your shell prompt to evaluate a local .envrc file whenever your active working directory changes.
How to Use direnv
# Install via homebrew or apt
brew install direnv
# Hook into zsh (add to ~/.zshrc)
eval "$(direnv hook zsh)"
# In your project folder, create .envrc
echo 'export DATABASE_URL="postgres://localhost:5432/myapp"' > .envrc
# Authorize the file (security check)
direnv allow
direnv Prompt Hook & Environment Diffing
Common `.envrc` Layout Patterns
| Language / Framework | .envrc Directive | Automatic Action |
|---|---|---|
| Python Virtualenv | layout python | Creates and activates local .direnv/python virtualenv |
| Node.js / npm | layout node | Adds ./node_modules/.bin to PATH |
| Standard .env file | dotenv | Loads regular key=value pairs from existing .env |
To protect users from malicious git repositories that bundle destructive shell commands in .envrc, direnv blocks execution by default on newly cloned projects. The shell will display direnv: error .envrc is blocked. Run `direnv allow` to approve its content. Never run direnv allow without first inspecting what commands the .envrc executes.
Learn more at the official project site direnv.net.
Discussion & Issues
Comments
Post a Comment