mktemp -d is definitely the way to go! Most notably mktemp -d ensures that it’s a fresh directory. So you don’t have to worry about the path potentially being polluted already.
Does Nix do anything to ensure that mktemp -d directories are cleaned up after a build? Or are package authors responsible for putting a trap 'rm -rf $whatever' EXIT in the relevant phase script?
nix-shell doesn’t have any clean-up phase like nix-build, so I think it’s best if temporary directories are created inside the build directory/current working directory and/or using trap 'rm -rf...' EXIT.
Do nix-shell and nix-build have the same value for TMPDIR? Because if nix-shell sets it to a tmpfs partition — e. g., /run —, the created directory would be cleaned up after a reboot and, thus, there would be no need for the trap call.