iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
❄️

Understanding Fixed-Output Derivations (FOD) in Nix

に公開
2025/12/01

What this article covers

  • Introduction
  • Look for official/unofficial fetchers before using FOD
  • To make a Nix derivation a Fixed Output Derivation (FOD), specify outputHashAlgo, outputHashMode, and outputHash
  • Usage examples
  • Notes on handling FODs and their wrappers

Introduction

While using Nix, you might rarely encounter a situation where you absolutely need to perform an impure operation within a builder. 99.98% of the time, existing fetchers are sufficient, but for the remaining 0.02%, since there was almost no information in Japanese on how to directly use a "Fixed Output Derivation" (FOD), I have written this guide.

If you don't know what a derivation is, you might not get much out of this article, so I recommend reading Asahi-sensei's Nix Introduction first.

Before using FOD

99.98% of problems can be solved without the user touching FODs directly. Before resorting to FODs, try to solve the issue using the following methods:

  • builtins or lib fetchers - such as fetchTarball, fetchurl, fetchFromGitHub, etc.
  • *2nix family tools - such as bun2nix.

Also, even if you do use one, it is better to define it as a custom fetcher due to the limitations described later.

In the following example, I use an FOD for a trivial network fetch for clarity, but this is not a recommendation. If you simply want to fetch a file, use an existing fetcher.

Making a derivation Fixed-Output

If you try to write a normal derivation, it will look like this. Since derivation builders generally cannot access the network, this derivation cannot be built.

normal.nix
# Note: Cannot be built
{pkgs ? import <nixpkgs> {}}: let
  inherit (pkgs) stdenv wget cacert;
in
  stdenv.mkDerivation {
    name = "normal-derivation";
    nativeBuildInputs = [
      wget
      cacert
    ];
    dontUnpack = true;
    buildPhase = ''
      runHook preBuild

      mkdir -p $out
      wget "https://example.com" -O $out/index.html

      runHook postBuild
    '';
  }

To enable Fixed-Output mode, specify outputHashAlgo, outputHashMode, and outputHash. This relaxes the builder sandbox restrictions, allowing access to the network.

fod.nix
{pkgs ? import <nixpkgs> {}}: let
  inherit (pkgs) stdenv wget cacert;
in
  stdenv.mkDerivation {
    name = "fixed-output-derivation";
    nativeBuildInputs = [
      wget
      cacert
    ];
    dontUnpack = true;
    buildPhase = ''
      runHook preBuild

      mkdir -p $out
      wget "https://example.com" -O $out/index.html

      runHook postBuild
    '';
    outputHashAlgo = "sha256";
    outputHashMode = "recursive"; # Specify "recursive" for directories, "flat" for files
    outputHash = ""; # Leave empty at first; let Nix determine the hash
  }

Since it outputs an error, set the hash to the correct value.

$ nix-build ./fod.nix
error: hash mismatch in fixed-output derivation '/nix/store/v2825b7b6rpksfi9nsji8w7b5v5w1l2n-fixed-output-derivation.drv':
         specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
            got:    sha256-7Sqe1vePBqur6jFcJ6mejWyx4CGVOI9jy52fOT8DOWA=
fod.nix
-  outputHash = "";
+  outputHash = "sha256-7Sqe1vePBqur6jFcJ6mejWyx4CGVOI9jy52fOT8DOWA=";

With this, you can build a Fixed-Output mode derivation.

$ nix-build ./fod.nix
/nix/store/fhxk6vsa7h1l10fa99c2d7iwbin4h3ay-fixed-output-derivation

$ ls result
index.html

$ cat result/index.html
<!doctype html><html lang="en"><head><title>Example Domain</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{background:#eee;width:60vw;margin:15vh auto;font-family:system-ui,sans-serif}h1{font-size:1.5em}div{opacity:0.8}a:link,a:visited{color:#348}</style><body><div><h1>Example Domain</h1><p>This domain is for use in documentation examples without needing permission. Avoid use in operations.<p><a href="https://iana.org/domains/example">Learn more</a></div></body></html>

Usage examples

Most fetchers, excluding those using builtins, are implemented this way. For example, pnpm.fetchDeps is implemented roughly as follows. (Collapsed as it is long)

pnpm.fetchDeps
pkgs/development/tools/pnpm/fetch-deps/default.nix
# (modified) source: https://github.com/NixOS/nixpkgs/blob/c8d4dabc4357a22d1c249a9363998bdb00122544/pkgs/development/tools/pnpm/fetch-deps/default.nix
{
  lib,
  stdenvNoCC,
  jq,
  moreutils,
  cacert,
  pnpm,
  yq,
}: {
  fetchDeps = lib.makeOverridable (
    {
      hash ? "",
      pname,
      ...
    }:
      stdenvNoCC.mkDerivation (
        finalAttrs: {
          name = "${pname}-pnpm-deps";

          nativeBuildInputs = [
            cacert
            jq
            moreutils
            pnpm
            yq
          ];

          installPhase = ''
            runHook preInstall

            export HOME=$(mktemp -d)

            pnpm config set store-dir $out
            pnpm install \
                --force \
                --ignore-scripts \
                --registry= \
                --frozen-lockfile

            runHook postInstall
          '';

          fixupPhase = ''
            runHook preFixup

            # Remove timestamp and sort the json files
            rm -rf $out/{v3,v10}/tmp
            for f in $(find $out -name "*.json"); do
              jq --sort-keys "del(.. | .checkedAt?)" $f | sponge $f
            done

            runHook postFixup
          '';

          dontConfigure = true;
          dontBuild = true;
          outputHashMode = "recursive";
          outputHash = hash;
          outputHashAlgo = "sha256";
        }
      )
  );
}

It is also recommended to use this when you have a dedicated package manager and you want that manager to perform the download (i.e., when downloading dependencies directly is difficult). (For example: npm, cargo, go mod, git clone, etc.)

Notes

1. Builds are skipped if already in the store

If a derivation with the same store path already exists in the store, FODs will skip the build even if the input has changed.
The same applies to fetchers, so after changing a URL in fetchurl or similar, you must always set the hash to empty to force a new fetch. Otherwise, you may encounter inconsistencies where the build succeeds on one device but fails with a hash mismatch on another.

2. No integrity check of the hash

Due to the point above, Nix does not check if the output of an FOD derivation is truly fixed. Therefore, even a derivation like this will build successfully if you provide a hash. Of course, this will not build on other devices, leading to inconsistent behavior across environments.

random.nix
{pkgs ? import <nixpkgs> {}}:
pkgs.stdenv.mkDerivation {
  name = "random";
  dontUnpack = true;
  buildPhase = ''
    echo $RANDOM > $out
  '';

  outputHashAlgo = "sha256";
  outputHashMode = "flat";
  outputHash = "";
}

It is obvious that the hash will fluctuate in this example, but various other types of non-determinism can exist, such as JSON key ordering fluctuations or timestamps included in the output. In such cases, you must manually normalize the output. (In the pnpm.fetchDeps example above, jq --sort-keys is used to normalize it.)

Also, fetching from time-dependent sources like https://example.com/releases/latest is technically possible. You should avoid doing this as it makes the build time-dependent.

3. Cannot depend on other derivations

FODs cannot hold references to other derivations. Specifically, you cannot include a file that contains a derivation path within an FOD. If you need this for things like ELF files, it is best to create the derivation in two stages: source acquisition and patching.

deps.nix
# Note: Cannot be built
{pkgs ? import <nixpkgs> {}}: let
  inherit (pkgs) stdenv which hello;
in
  stdenv.mkDerivation {
    name = "fod-deps";
    nativeBuildInputs = [
      which
      hello
    ];
    dontUnpack = true;
    buildPhase = ''
      runHook preBuild

      mkdir -p $out
      echo $(which hello) > $out/hello-path.txt

      runHook postBuild
    '';
    outputHashAlgo = "sha256";
    outputHashMode = "recursive";
    outputHash = "";
  }
$ nix-build ./deps.nix
error: fixed-output derivations must not reference store paths: '/nix/store/b5jk6ba2ab1x6aqch7fz5kfyh1v3905c-fod-deps.drv' references 1 distinct paths, e.g. '/nix/store/2bcv91i8fahqghn8dmyr791iaycbsjdd-hello-2.12.2'

Afterword

This is my first article.
Please leave a comment if there are any inaccuracies or points that are difficult to understand!

Discussion