Skip Navigation

Scott Spence

Notes on direnv

2 min read
Hey! Thanks for stopping by! Just a word of warning, this post is about 3 years old, . If there's technical information in here it's more than likely out of date.

I was directed to direnv by Chris Biscardi when I was trying to use some environment variables in my Toast site.

In the past I have always reached for dotenv so taking a look at other Toast sites I couldn’t find any that used it so I reached out to Chris and he mentioned direnv.

I found a really useful video from Vlad detailing the setup which I’ve adopted and started using.

Install

Install for me (using Fedora 33) was a package manager install, there are many supported platforms.

sudo dnf -y install direnv

Setup

To hook direnv into my Zsh shell I added the direnv hook from the documentation and wrapped it in an if as detailed in Vlad’s video.

# .zshrc
if [ $(command -v direnv) ]; then
  eval "$(direnv hook zsh)"
fi

In the project I want to use direnv in I created a .envrc file then added dotenv to that file:

# .envrc
dotenv

This lets direnv know that you want to use the environment variables in you .env file.

Lastly I need to tell direnv that it can run in this directory with the allow command:

direnv allow

Vlad also provided a handy alias for initialising direnv in a new project, I added this to my Zsh aliases file:

# direnv
alias -g di='echo dotenv > .envrc && touch .env && direnv allow'```

Now each time I cd into a directory with a .env file where I have allowed direnv I’m prompted on what environment variables are available.

There's a reactions leaderboard you can check out too.

Copyright © 2017 - 2024 - All rights reserved Scott Spence