Hello! I’m trying to package a fastify server using node2nix. I’m following this article’s Node2Nix section for reference.
Here’s my project flake:
{...}: {
imports = [
./nix/docker.nix
];
config = {
perSystem = {
system,
pkgs,
...
}: let
nodejs = pkgs.nodejs-18_x;
node2nixOutput = import ./nix {inherit system nodejs pkgs;};
nodeDeps = node2nixOutput.nodeDependencies;
in {
packages = {
marco = pkgs.stdenv.mkDerivation {
name = "marco";
src = ./.;
propagatedBuildInputs = [nodejs];
buildPhase = ''
runHook preBuild
# this line removes a bug where value of $HOME is set to a non-writable /homeless-shelter dir
export HOME=$(pwd)
# symlink the generated node deps to the current directory for building
ln -sf ${nodeDeps}/lib/node_modules ./node_modules
export PATH="${nodeDeps}/bin:$PATH"
npm run build
runHook postBuild
'';
installPhase = ''
runHook preInstall
# Note: you need some sort of `mkdir` on $out for any of the following commands to work
mkdir -p $out/bin
# copy only whats needed for running the built app
cp package.json $out/package.json
cp -r dist $out/dist
ln -sf ${nodeDeps}/lib/node_modules $out/node_modules
# copy entry point, in this case our index.ts has the node shebang
# nix will patch the shebang to be the node version specified in buildInputs
# you could also copy in a script that is basically `npm run start`
cp -r dist/index.js $out/bin/marco
chmod a+x $out/bin/marco
runHook postInstall
'';
};
};
};
};
}
#!/usr/bin/env node
import fastify from 'fastify';
# relative import causes error without this the built instance runs fine
import DbPlugin from './plugins/db';
const server = fastify();
server.register(DbPlugin);
server.get('/ping', async (request, reply) => {
return 'pong\n';
});
server.listen({ host: '0.0.0.0', port: 8080 }, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
Error I get when running nix run .#marco
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/nix/store/f2wvbx0jzng243w5izm8lqslkh03aa6g-marco/bin/plugins/db
I also tried copying the whole dist folder to bin on installPhase, but then I’m met with:
error: unable to execute '/nix/store/r98aw9b513k2giah846spg0kwiafcag3-marco/bin/marco': Permission denied