corepack enable modifies installation directories, which means it tries to write to /nix/store/...nodejs-x.y.z/bin/, but that’s not allowed.
It only creates some symlinks, so what you can do is package those symlinks:
stdenv.mkDerivation {
name = "corepack-shims";
buildInputs = [ nodejs-17_x ];
phases = [ "installPhase" ];
installPhase = ''
mkdir -p $out/bin
corepack enable --install-directory=$out/bin
'';
}
You can then use that derivation as a build input for some other derivation, and the corepack shims will be available in $PATH.
Note that corepack downloads package managers to ~/.node/corepack, but $HOME is set to /homeless-shelter inside Nix builds. So when using the corepack shims, you may have to give it a writable home directory by doing something like: export HOME=$TMPDIR
EDIT: You can apparently also set COREPACK_HOME if you don’t want to modify HOME.
EDIT 2: Corepack downloading stuff also makes your build impure. Not sure what the best approach to using corepack is, really.