Skip to content

Instantly share code, notes, and snippets.

@jcajuab
Last active July 7, 2025 16:09
Show Gist options
  • Save jcajuab/69d69a26c6a3f1bd41219f8c90336c51 to your computer and use it in GitHub Desktop.
Save jcajuab/69d69a26c6a3f1bd41219f8c90336c51 to your computer and use it in GitHub Desktop.

Effortless Dev Environments with Nix Flakes + direnv

A minimal guide to setting up reproducible and isolated development environments using Nix flakes and direnv.

1. Install Nix (Single-user)

Installs the Nix package manager in single-user mode.

sh <(curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install) --no-daemon

For multi-user installation, see the official guide.

2. Enable Nix Flakes

mkdir -p ~/.config/nix
echo 'experimental-features = nix-command flakes' >> ~/.config/nix/nix.conf

3. Install direnv and nix-direnv

Installs tools to automatically load and unload environment variables based on directory context.

nix profile install nixpkgs#direnv
nix profile install nixpkgs#nix-direnv

4. Configure direnv for Your Shell

Integrates direnv with your shell so it runs automatically when entering/exiting directories.

# Bash (~/.bashrc)
eval "$(direnv hook bash)"

# Zsh (~/.zshrc)
eval "$(direnv hook zsh)"

# Fish (~/.config/fish/config.fish)
direnv hook fish | source

Note: Ensure $HOME/.nix-profile/bin is in your PATH.

5. Try It Out

Creates a simple project to demonstrate your new setup.

mkdir flake-test
cd flake-test

Create a flake.nix file:

{
  inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; };

  outputs = { self, nixpkgs }:
    let
      supportedSystems =
        [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
      forEachSupportedSystem = f:
        nixpkgs.lib.genAttrs supportedSystems
        (system: f { pkgs = import nixpkgs { inherit system; }; });
    in {
      devShells = forEachSupportedSystem ({ pkgs }: {
        default = pkgs.mkShell {
          packages = with pkgs; [ nodejs ];
          shellHook = ''
            node --version
          '';
        };
      });
    };
}

Then initialize direnv:

echo 'use flake' > .envrc
direnv allow

This command sets up direnv to use the flake-defined environment automatically.

6. Done! πŸŽ‰

You now have a declarative, reproducible, and isolated development environment.

Explore more templates:

πŸ‘‰ https://github.com/the-nix-way/dev-templates

Comments are disabled for this gist.