How to change NIX_PATH

I learned from this thread and from @zimbatm 's excellent Nix Friday that it’s possible to specify the path of configuration.nix in the NIX_PATH environment variable, instead of using soft links to achieve the same effect of not having the config file in the default /etc/nixos. I want to do this but I am unsure where to set the environment variable. If I understand correctly, I have to modify the root user’s NIX_PATH, not my regular user’s. In a NixOS distribution, what would be the best place to alter NIX_PATH?

One option is to set it in the configuration itself. For example:

{ ... }:
{
  nix.nixPath = [ "nixpkgs=/home/myuser/nixpkgs" ];
}

One thing to be aware of is that the change will only apply after the nixos-rebuild switch, and after creating a new user login. It’s still convenient to have that as a day-to-day usage though.

Once you have your configuration.nix files in a git repo, I would recommend adding a little wrapper script that sets the configuration and nixpkgs in the same repository.

For example ./nixos-rebuild would contain:

#!/usr/bin/env bash
cd "$(dirname "$0")"
exec nixos-rebuild -I nixpkgs=../nixpkgs -I nixos-config=machines/$(hostname).nix "$@"

This assumes that nixpkgs is checked out alongside the repo in the same parent folder. You can also manage nixpkgs as a git submodule or however you like.

Then when it comes to applying the configuration changes, first cd into the repository, edit the machines/myhostname.nix file and then run sudo ./nixos-rebuild switch.

3 Likes