A minimal guide to setting up reproducible and isolated development environments using Nix flakes and direnv
.
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.
mkdir -p ~/.config/nix
echo 'experimental-features = nix-command flakes' >> ~/.config/nix/nix.conf
Installs tools to automatically load and unload environment variables based on directory context.
nix profile install nixpkgs#direnv
nix profile install nixpkgs#nix-direnv
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 yourPATH
.
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.
You now have a declarative, reproducible, and isolated development environment.
Explore more templates: