Working with Nix
A Nix build has no network access, so Nix has to fetch a project's dependencies before the build starts. This page shows how to fetch each tarball in pnpm-lock.yaml as a Nix download of its own and install from those tarballs.
- The Nix files hold no hash for the dependencies. Nix takes each hash from the lockfile.
- After a lockfile change, Nix downloads only the tarballs that changed.
The recipe needs pnpm v12.19.0 or later. See Getting pnpm when nixpkgs has an older one.
How it works#
pnpm sbom --lockfile-onlylists the URL and sha512 of every tarball the lockfile pins.- Nix fetches each tarball with
fetchurl. - In the build,
pnpm store addreads the tarballs into a store, andpnpm install --offlineinstalls from it.
Fetching the tarballs#
Save this file in the project:
{ lib, fetchurl, linkFarm, runCommand, pnpm }:
rec {
# The list of tarballs the lockfile in `src` pins. `src` needs
# pnpm-lock.yaml, each project's package.json, and the files pnpm reads
# its settings from.
sbom = src: runCommand "pnpm-sbom.json" { nativeBuildInputs = [ pnpm ]; } ''
export HOME=$TMPDIR
export pnpm_config_pm_on_fail=ignore
cd ${src}
pnpm sbom --sbom-format cyclonedx --lockfile-only > $out
'';
# A directory of the tarballs that list names, each named by its hash.
tarballs = sbomFile:
let
# The lockfile pins a sha1 for a package published before npm recorded
# a sha512.
algorithms = { "SHA-512" = "sha512"; "SHA-1" = "sha1"; };
hashOf = reference:
lib.findFirst (hash: algorithms ? ${hash.alg}) null (reference.hashes or [ ]);
components = (lib.importJSON sbomFile).components;
distributions = lib.concatMap
(component: lib.filter
(reference: reference.type == "distribution" && hashOf reference != null)
(component.externalReferences or [ ]))
components;
in
linkFarm "pnpm-tarballs" (lib.listToAttrs (map
(distribution:
let hash = hashOf distribution; in {
name = "${hash.content}.tgz";
value = fetchurl {
inherit (distribution) url;
${algorithms.${hash.alg}} = hash.content;
};
})
distributions));
}
Building a project#
{ pkgs ? import <nixpkgs> { } }:
let
inherit (pkgs) lib;
pnpmOffline = pkgs.callPackage ./nix/pnpm-offline.nix { };
tracked = lib.fileset.gitTracked ./.;
# Only the files that decide the dependencies, so that editing source code
# does not compute the list again.
manifests = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.intersection tracked (lib.fileset.unions [
./pnpm-lock.yaml
(lib.fileset.maybeMissing ./pnpm-workspace.yaml)
(lib.fileset.maybeMissing ./.npmrc)
(lib.fileset.fileFilter (file: file.name == "package.json") ./.)
]);
};
tarballs = pnpmOffline.tarballs (pnpmOffline.sbom manifests);
in
pkgs.stdenv.mkDerivation {
name = "app";
src = lib.fileset.toSource { root = ./.; fileset = tracked; };
nativeBuildInputs = [ pkgs.pnpm pkgs.nodejs ];
configurePhase = ''
export HOME=$TMPDIR/home
export pnpm_config_pm_on_fail=ignore
cp --recursive --dereference ${tarballs} $TMPDIR/tarballs
[ -z "$(ls $TMPDIR/tarballs)" ] || pnpm store add $TMPDIR/tarballs
pnpm install --offline --frozen-lockfile --trust-lockfile
'';
buildPhase = ''
pnpm run build
'';
installPhase = ''
cp --recursive dist $out
'';
}
Why configurePhase runs these commands:
HOMEmust be a directory the build can write to. pnpm keeps its store there.pmOnFailisignorebecause the build runs the pnpm that Nix provides. Without it, a project that pins another pnpm version makes pnpm try to download that version.- The build copies the tarballs for pnpm older than v12.25.0, which skips a symlinked tarball that points out of the directory. Nix links each tarball from its own store path. With pnpm v12.25.0 or later, pass
${tarballs}topnpm store adddirectly. - The build skips
pnpm store addfor a project with no dependencies, because the command rejects a directory with no tarballs. --trust-lockfileis needed because pnpm otherwise checks the lockfile againstminimumReleaseAgeandtrustPolicy, which takes registry metadata the build cannot fetch. Those settings still apply wherever pnpm writes the lockfile. The build does not check a lockfile someone edited by hand, so runpnpm install --frozen-lockfilewith network access in CI as well.
lib.fileset.gitTracked keeps node_modules and other untracked files out of the build. It needs the project to be the root of a Git repository.
manifests must hold every file pnpm reads its settings from, because the registry settings decide the tarball URLs. Add any file that pnpm-workspace.yaml includes. The files land in the Nix store, which every user of the machine can read, so keep credentials out of them.
Getting pnpm#
When pkgs.pnpm is older than v12.19.0, use the static Linux build that pnpm publishes to npm. This one is for x64. The ARM build is @pnpm/exe.linux-arm64-musl.
pnpm = pkgs.stdenv.mkDerivation {
pname = "pnpm";
version = "12.24.0";
src = pkgs.fetchurl {
url = "https://registry.npmjs.org/@pnpm/exe.linux-x64-musl/-/exe.linux-x64-musl-12.24.0.tgz";
hash = "sha512-NeIW64Azg/b+QFj6Z14BYb84pUKVIrvf15JhhuV7YmouaZbiMRG/8nDwIvEIRvwLqXacd4gVdcsGqUcO7oIYhQ==";
};
dontStrip = true;
installPhase = "install -Dm755 pnpm $out/bin/pnpm";
};
Pass it to the recipe with pkgs.callPackage ./nix/pnpm-offline.nix { inherit pnpm; }, and put it in nativeBuildInputs in place of pkgs.pnpm.
For another version, change the version in both places and take the hash from the registry:
pnpm view @pnpm/exe.linux-x64-musl@12.24.0 dist.integrity
Committing the list#
pnpmOffline.sbom runs pnpm while Nix evaluates the project, which Nix calls import from derivation. Where a Nix setup forbids that, write the list to a file and commit it:
pnpm sbom --sbom-format cyclonedx --lockfile-only > pnpm-sbom.json
tarballs = pnpmOffline.tarballs ./pnpm-sbom.json;
Write the file again after every lockfile change. The build fails when the lockfile pins a tarball the file does not list.
Downloading in parallel#
Nix builds one derivation at a time unless max-jobs says otherwise, and each tarball is a derivation. Raise it for the first build of a large project:
nix-build --max-jobs 16
Limitations#
- Nix fetches the optional dependencies of every platform, not only the ones the build installs.
- A registry that needs credentials is not covered. Nix fetches each tarball without pnpm's registry credentials.
- The recipe fetches a Git dependency when its lockfile entry has a
tarballand anintegrity, as one from GitHub has. It does not fetch other Git dependencies. - A lockfile written with
lockfile.integrityTarget: taris not covered. Its hashes are of the uncompressed tar, and Nix checks the file it downloads. - A runtime the project declares in
devEngines.runtimeis not covered. pnpm downloads it during the install, which the build cannot do.