Managing development environments can be annoying when switching between projects, and you don’t always want to install your devtools system-wide. direnv helps by automatically loading and unloading environment variables when you enter or leave a project directory.

If you’re using Nix flakes, direnv integrates seamlessly with your flake.nix (or legacy shell.nix) so you always have the right tools in your shell without extra commands. And as a bonus, I’ll show you how to hook it up with Doom Emacs, so your editor picks up the same environment too.

Step 1: Install direnv Link to heading

Install direnv on NixOS by adding the following to your configuration.nix:

environment.systemPackages = with pkgs; [
    direnv
    nix-direnv
];

Step 2: Hook direnv into your shell Link to heading

Choose one of the following options based on your shell:

bash Link to heading

Paste the following into your ~/.bashrc

eval "$(direnv hook bash)"

zsh Link to heading

Paste the following into your ~/.zshrc

eval "$(direnv hook zsh)"

fish Link to heading

Paste the following into your ~/.config/fish/config.fish

direnv hook fish | source

Step 3: Initialise direnv in your project Link to heading

Navigate to your project. I won’t cover how to set up a devshell in this guide but you can follow this guide to set one up.

Using shell.nix or default.nix Link to heading

Execute the following in your terminal:

echo "use nix" > .envrc
direnv allow

Using flake.nix with a devshell Link to heading

Execute the following in your terminal:

echo "use flake" > .envrc
direnv allow

You should now be able to use any commands available in your devshell from your terminal, as long as you are in the directory if your project. If it doesn’t work, try renavigating to your project (cd .. && cd project_dir)

Optional step 4: Doom emacs Link to heading

Simply navigate to init.el, and uncomment direnv. Reopen doom emacs (or restart the daemon if necessary), it should now pick up your dev environment once you enter the directory.

That’s it! Link to heading

That’s all you need to get direnv working with Nix flakes (and Doom Emacs, if you use it). Your shell and editor should now pick up the right environment automatically whenever you enter your project.

If you run into trouble or have questions, feel free to reach out, you can find my Discord linked on the homepage. Always happy to help ;3