Built with custom store, every package install fails with error: path is not in the Nix store

I cannot use /nix for various reasons so I built Nix from source using --with-store-dir=/opt/nix/store and --localstatedir=/opt/nix/var.

Although the install succeeded, anything I try to install errors with BadStorePath and NotInStore. The message is error: path ‘[thepath] is not in the Nix store’

You need a bit more than that, see this post for an example.

I encounted the same problem, both nix-env and flake don’t work after building nix with custom store path. I have changed the path of nix store, but nix still refer to /nix/store while evaluating nix-expr.

The blog in @rohit post is confusing and not helpful for me.It only list lots of steps but doesn’t explain why I need to them, such as patching the souce code and adding a configuration file in ~/.config/nix/nixpkgs

Generally running nix with different store path than /nix/store is quite difficult, as all the paths encoded in binaries etc… refer to there. You basically won’t ever hit the binary cache and have to rebuild everything.
https://github.com/NixOS/nix/issues/1971

I’m not sure if this is possible to solve even with content addressed nix due to the paths being hardcoded into binaries Towards a content-addressed model for Nix

You best bet would be to some sort of namespacing, so that the programs see /nix in their namespace, but in reality it resides somewhere else.

The first step is correct. Were you able to install the nix from nixpkgs? You’d need to either define it with an overlay:

final: prev: {
  nix = prev.nix.override {
    storeDir = "$NIX_PREFIX/nix/store";
    stateDir = "$NIX_PREFIX/nix/var";
  };
}

or use the correct environment variables at runtime.