Jump to content

Flakes: Difference between revisions

From NixOS Wiki
imported>Bqv
mNo edit summary
Marked this version for translation
 
(237 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
'''Nix Flakes''' are an upcoming feature of the Nix package manager.
<languages />


Flakes allow you to specify your code's dependencies (e.g. remote Git repositories) in a declarative way, simply by listing them inside a <code>flake.nix</code> file:
<translate>
<!--T:1-->
{{Cleanup}}


<!--T:182-->
'''Nix flakes''' are an [[Experimental Nix features|experimental feature]] first introduced in the 2.4 [[Nix]] release,{{Cite manual|nix|development/experimental-features|number=13.8|title=Experimental Features|subsection=xp-feature-flakes|subtitle=flakes}}{{Cite manual|nix|release-notes/rl-2.4|number=14.27|title=Release 2.4 (2021-11-01)}} aiming to address a number of areas of improvement for the Nix ecosystem: they provide a uniform structure for Nix projects, allow for pinning specific versions of each dependencies, and sharing these dependencies via lock files, and overall make it more convenient to write reproducible Nix expressions.
<!--T:183-->
A flake is a directory which directly contains a Nix file called <code>flake.nix</code>, that follows a very specific structure. Flakes introduce a URL-like syntax{{Cite manual|nix|command-ref/new-cli/nix3-flake|number=8.5.17|title=nix flake|subsection=url-like-syntax|subtitle=URL-like syntax}} for specifying remote resources. To simplify the URL syntax, flakes use a registry of symbolic identifiers,{{Cite manual|nix|command-ref/new-cli/nix3-registry|number=8.5.62|title=nix registry}} allowing the direct specification of resources through syntax such as <code>github:NixOS/nixpkgs</code>.
<!--T:184-->
Flakes also allow for locking references and versions, which can then be queried and updated programatically via the inputs {{cite manual|nix|command-ref/new-cli/nix3-flake-lock|number=7.5.19|title=nix flake lock}}{{cite manual|nix|command-ref/new-cli/nix3-flake-info|number=7.5.17|title=nix flake info}}. Additionally, an experimental CLI utility accepts flake references for expressions that build, run, and deploy packages.{{Cite manual|nix|command-ref/new-cli/nix|number=8.5.1|title=nix}}
<!--T:185-->
== Flake file structure ==
Minimally, a flake file contains a description of the flake, a set of input dependencies and an output. You can generate a very basic flake file at any time using nix flake init. This will populate the current directory with a file called flake.nix that will contain something akin to:
{{File|3=<nowiki>{
  description = "A very basic flake";
  <!--T:186-->
inputs = {
    nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  };
  <!--T:187-->
outputs = { self, nixpkgs }: {
    <!--T:188-->
packages.x86_64-linux.hello = nixpkgs.legacyPackages.x86_64-linux.hello;
    <!--T:189-->
packages.x86_64-linux.default = self.packages.x86_64-linux.hello;
  <!--T:190-->
};
}</nowiki>|name=flake.nix|lang=nix}}
In the example above, you can see the description, the input specified as a GitHub repository with a specific branch (here <code>nixos/nixpkgs</code> on the <code>nixos-unstable</code> branch), and an output that makes use of the input. The output simply specifies that the flake contains one package for the x86_64 architecture called <code>hello</code>. Even if your flake's output wouldn't use its input (however, in practice, that is highly unlikely), the output still needs to be a Nix function.
{{Note|Flakes require you to specify its outputs for each architecture separately. For more information, read the related section below.}}
<!--T:191-->
=== Nix configuration ===
It is possible to override the global Nix configuration set in your <code>nix.conf</code> file for the purposes of evaluating a flake. This can be useful, for example, for setting up binary caches specific to certain projects, while keeping the global configuration untouched. The flake file can contain a nixConfig attribute with any relevant configuration settings supplied. For example, enabling the nix-community binary cache would be achieved by:
{{File|3=<nowiki>{
  ...
  nixConfig = {
    extra-substituters = [
      "https://nix-community.cachix.org"
    ];
    extra-trusted-public-keys = [
      "nix-community.cachix.org-1:...="
    ];
  }
}</nowiki>|name=flake.nix|lang=nix}}{{Note|If you are used to configuring your Nix settings via the NixOS configuration, these options are under <code>nix.settings</code> and not <code>nix</code>. For example, you cannot specify the automatic storage optimisation under <code>nix.optimisation.enable</code>.}}
== Setup == <!--T:192-->
=== Enabling flakes temporarily === <!--T:5-->
<!--T:6-->
When using any [[Nix command|<code>nix</code> command]], add the following command-line options:
</translate>
<syntaxhighlight lang="shell">
--experimental-features 'nix-command flakes'
</syntaxhighlight>
<translate>
=== Enabling flakes permanently === <!--T:193-->
==== NixOS ==== <!--T:7-->
<!--T:8-->
Add the following to the [[Overview_of_the_NixOS_Linux_distribution#Declarative_Configuration system configuration |NixOS configuration]]:
</translate>
<syntaxHighlight lang=nix>
<syntaxHighlight lang=nix>
{
   nix.settings.experimental-features = [ "nix-command" "flakes" ];
   inputs = {
    home-manager.url = "github:rycee/home-manager";
  };
}
</syntaxHighlight>
</syntaxHighlight>
<translate>
====Home Manager==== <!--T:10-->
<!--T:11-->
Add the following to your [[Home Manager|home manager]] config:
</translate>
<syntaxhighlight lang="nix">
  nix.settings.experimental-features = [ "nix-command" "flakes" ];
</syntaxhighlight>
<translate>
====Nix standalone==== <!--T:13-->
<!--T:14-->
{{Note | The  [https://github.com/DeterminateSystems/nix-installer Determinate Nix Installer] enables flakes by default.}}


Each dependency gets then pinned, that is: its commit hash gets automatically stored into a file - named <code>flake.lock</code> - making it easy to, say, upgrade it:
<!--T:15-->
Add the following to <code>~/.config/nix/nix.conf</code> or <code>/etc/nix/nix.conf</code>:


<syntaxHighlight lang=console>
</translate>
$ nix flake update --update-input home-manager
<syntaxHighlight lang=text>
experimental-features = nix-command flakes
</syntaxHighlight>
</syntaxHighlight>
<translate>
== Usage == <!--T:17-->
<!--T:20-->
{{Warning | Since contents of flake files are copied to the world-readable [[Nix_package_manager#Nix_store|Nix store]] folder, do not put any unencrypted secrets in flake files. You should instead use a [[Comparison of secret managing schemes|secret managing scheme]].}}
<!--T:146-->
{{Note | For flakes in [[git]] repositories, only files in the working tree will be copied to the store.
<!--T:22-->
Therefore, if you use <code>git</code> for your flake, ensure to <code>git add</code> any project files after you first create them.}}
<!--T:64-->
=== The nix flakes command ===
{{Main|Nix (command)}}
<!--T:65-->
The {{ic|nix flake}} subcommand is described in {{Nix Manual|name=command reference page of the Nix manual|anchor=command-ref/new-cli/nix3-flake}}.
<!--T:194-->
This flake produces a single flake output <code>packages</code>. And within that, <code>x86_64-linux</code> is a system-specifc attribute set. And within that, two package [[derivations]] <code>default</code> and <code>hello</code>. You can find outputs with the {{Nix Manual|name=show command|anchor=command-ref/new-cli/nix3-flake-show}} of a flake as shown below:


''(if you're familiar with modern packages managers like <code>cargo</code> or <code>npm</code>, then the overall mechanism shouldn't surprise you - Nix works in a similar way, although without a centralized repository.)''
<!--T:195-->
<syntaxhighlight lang="console">
$ nix flake show
└───packages
    └───x86_64-linux
        ├───default: package 'hello-2.12.2'
        └───hello: package 'hello-2.12.2'
</syntaxhighlight>


Flakes are meant as a replacement for '''channels''' and things like ad-hoc invocations of <code>builtins.fetchgit</code> - no more worrying about keeping your channels in sync, no more worrying about forgetting about a dependency deep down in your tree: everything's at hand right inside <code>flake.lock</code>.
==== Development shells ==== <!--T:196-->


== Installing flakes ==
<!--T:197-->
A <code>devShell</code> is a Nix-provided [[Development_environment_with_nix-shell#nix develop|development environment]] defined within a flake. It lets you declare a reproducible shell environment with the tools, libraries, and environment variables you need for the development of a specific project. This is flake equivalent to defining a <code>nix-shell</code>.


Currently flakes are available only in the '''unstable''' version of Nix and so they need to be explicitly enabled inside '''nix.conf'''.
<!--T:198-->
<syntaxhighlight lang="nix">
{
  description = "Example flake with a devShell";


=== NixOS ===
  <!--T:199-->
In NixOS this can be achieved with the following options in <code>configuration.nix</code>
inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";


<syntaxHighlight lang=nix>
  <!--T:200-->
{ pkgs, ... }: {
outputs = { self, nixpkgs}:
  nix = {
    let
     package = pkgs.nixFlakes;
      system = "x86_64-linux";
    extraOptions = ''
      pkgs = import nixpkgs { inherit system; };
      experimental-features = nix-command flakes
     in {
    '';
      devShells.x86_64-linux.default = pkgs.mkShell {
  };
        buildInputs = with pkgs; [
          hello
        ];
        shellHook = ''
          echo "Welcome to the devShell!"
        '';
      };
    };
}
}
</syntaxHighlight>
</syntaxhighlight>
 
<!--T:201-->
To enter the development shell environment:
 
<!--T:202-->
<syntaxhighlight lang="console">
$ nix develop
</syntaxhighlight>
 
<!--T:203-->
{{note|You don’t need to define a devShell to enter a development shell using nix develop.
If no devShell is defined, nix develop will drop you into an environment containing the default build dependencies of the flake (if any).}}
 
==== Build specific attributes in a flake repository ==== <!--T:102-->


=== Non-NixOS ===
<!--T:103-->
On non-nixos systems, install `nixUnstable` in your environment:
Running <code>nix build</code> will look in the <code>legacyPackages</code> and <code>packages</code> output attributes for the corresponding [[derivation]] and then your system architecture and build the default output. If you want to specify a build attribute in a flake repository, you can run <code>nix build .#<attr></code>. In the example above, if you wanted to build the <code>packages.x86_64-linux.hello</code> attribute, run:


<!--T:204-->
<syntaxHighlight lang=console>
<syntaxHighlight lang=console>
$ nix-env -iA nixpkgs.nixFlakes
$ nix build .#hello
</syntaxHighlight>
</syntaxHighlight>


Edit either <code>~/.config/nix/nix.conf</code> or <code>/etc/nix/nix.conf</code> and add:
<!--T:205-->
Likewise, you can specify an attribute with the run command: <code>nix run .#hello</code> and the develop command: <code>nix develop .#hello</code>.
 
== Flake schema == <!--T:27-->
 
<!--T:28-->
The flake.nix file is a Nix file but that has special restrictions (more on that later).
 
<!--T:29-->
It has 4 top-level attributes:
 
<!--T:30-->
* <code>description</code> is a string describing the flake.
 
<!--T:147-->
* <code>inputs</code> is an attribute set of all the dependencies of the flake. The schema is described below.
 
<!--T:148-->
* <code>outputs</code> is a function of one argument that takes an attribute set of all the realized inputs, and outputs another attribute set whose schema is described below.


<syntaxHighlight>
<!--T:149-->
experimental-features = nix-command flakes
* <code>nixConfig</code> is an attribute set of values which reflect the [https://nixos.org/manual/nix/stable/command-ref/conf-file.html values given to nix.conf]. This can extend the normal behavior of a user's nix experience by adding flake-specific configuration, such as a [[Binary Cache|binary cache]].
</syntaxHighlight>
 
=== Input schema === <!--T:31-->
 
<!--T:32-->
[https://nixos.org/manual/nix/stable/command-ref/new-cli/nix3-flake.html#flake-inputs The nix flake inputs manual].
 
<!--T:150-->
[https://nixos.org/manual/nix/stable/command-ref/new-cli/nix3-flake.html#flake-references The nix flake references manual].
 
<!--T:33-->
The inputs attribute defines the dependencies of the flake. For example, nixpkgs has to be defined as a dependency for a system flake in order for the system to build properly.
 
<!--T:34-->
[[Nixpkgs]] can be defined using the following code:


This is needed to expose the Nix 2.0 CLI and flakes support that are hidden behind feature-flags.
</translate>
<code>inputs.nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";</code>


Finally, if the Nix installation is in multi-user mode, don’t forget to restart the nix-daemon.
Nixpkgs can alternatively also point to an url cached by the NixOS organization:


There is no official installer yet, but you can use the [https://github.com/numtide/nix-flakes-installer nix-flake-installer]:
<code>inputs.nixpkgs.url = "<nowiki>https://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz</nowiki>";</code>


<syntaxHighlight lang=console>
In this example the input would point to the `nixpkgs-unstable` channel.
$ sh <(curl -L https://github.com/numtide/nix-flakes-installer/releases/download/nix-3.0pre20200804_ed52cf6/install)
</syntaxHighlight>


== Basic project usage ==
<translate>
{{warning|flake makes a strong assumption that the folder is a git or mercurial repository. It doesn’t work outside of them.}}


In your repo, run <code>nix flake init</code> to generate the flake.nix file. Then run <code>git add flake.nix</code> to add it to the git staging area, otherwise nix will not recognize that the file exists.
<!--T:36-->
For any repository with its own flake.nix file, the website must also be defined. Nix knows where the nixpkgs repository is, so stating that it's on GitHub is unnecessary.


See also https://www.tweag.io/blog/2020-05-25-flakes/
<!--T:37-->
For example, adding [[Hyprland]] as an input would look something like this:


== Flake schema ==
</translate>
<code>inputs.hyprland.url = "github:hyprwm/Hyprland";</code>
<translate>


The flake.nix file is a Nix file but that has special restrictions (more on that later).
<!--T:39-->
If you want to make Hyprland follow the nixpkgs input to avoid having multiple versions of nixpkgs, this can be done using the following code:


It has 3 top-level attributes:
</translate>
<code>inputs.hyprland.inputs.nixpkgs.follows = "nixpkgs";</code>
<translate>


* <code>description</code> which is self…describing
<!--T:41-->
* <code>inputs</code> is an attribute set of all the dependencies of the flake. The schema is described below.
Using curly brackets({}), we can shorten all of this and put it in a table. The code will look something like this:
* <code>outputs</code> is a function of one argument that takes an attribute set of all the realized inputs, and outputs another attribute set which schema is described below.


== Input schema ==
</translate>
<syntaxhighlight lang="nix">
inputs = {
  nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";
  hyprland = {
    url = "github:hyprwm/Hyprland";
    inputs.nixpkgs.follows = "nixpkgs";
  };
};
</syntaxhighlight>
<translate>


This is not a complete schema but should be enough to get you started:
<!--T:206-->
By default, Git submodules in package <code>src</code>'s won't get copied to the nix store, this may cause the build to fail. Flakes in Git repositories can declare that they need Git submodules to be enabled. Since Nix version [https://discourse.nixos.org/t/nix-2-27-0-released/62003 2.27], you can enable submodules by:


<syntaxHighlight lang=nix>
<!--T:207-->
{
<syntaxhighlight lang="nix">
  # github example, also supported gitlab:
   inputs.self.submodules = true;
  inputs.nixpkgs.url = "github:Mic92/nixpkgs/master";
</syntaxhighlight>
  # git urls
  inputs.git-example.url = "git+https://git.somehost.tld/user/path";
  # local directories (needs to be a repository?)
  inputs.directory-example.url = "/path/to/repo";
  # Use this for non-flakes
  inputs.bar.url = "github:foo/bar/branch";
  inputs.bar.flake = false;
  # Overwrite inputs in a flake
  # This is useful to use the same nixpkgs version in both flakes
  inputs.sops-nix.url = "github:Mic92/sops-nix";
  inputs.sops-nix.inputs.nixpkgs.follows = "nixpkgs";
  # Pin flakes to a specific revision
  inputs.nix-doom-emacs.url = "github:vlaci/nix-doom-emacs?rev=238b18d7b2c8239f676358634bfb32693d3706f3";
   inputs.nix-doom-emacs.flake = false;
}
</syntaxHighlight>


The bar input is then passes to the output schema
=== Output schema === <!--T:42-->


== Output schema ==
<!--T:151-->
This is described in the nix package manager [https://github.com/NixOS/nix/blob/master/src/nix/flake-check.md src/nix/flake-check.md].


This is described in the nix package manager [https://github.com/NixOS/nix/blob/master/src/nix/flake.cc src/nix/flake.cc] in CmdFlakeCheck.
<!--T:43-->
Once the inputs are resolved, they're passed to the function `outputs` along with with `self`, which is the directory of this flake in the store. `outputs` returns the outputs of the flake, according to the following schema.


<!--T:44-->
Where:
Where:
 
<!--T:45-->
* <code><system></code> is something like "x86_64-linux", "aarch64-linux", "i686-linux", "x86_64-darwin"
* <code><system></code> is something like "x86_64-linux", "aarch64-linux", "i686-linux", "x86_64-darwin"
* <code><attr></code> is an attribute name like "hello".
 
<!--T:152-->
* <code><name></code> is an attribute name like "hello".
 
<!--T:153-->
* <code><flake></code> is a flake name like "nixpkgs".
* <code><flake></code> is a flake name like "nixpkgs".
<!--T:154-->
* <code><store-path></code> is a <code>/nix/store..</code> path
* <code><store-path></code> is a <code>/nix/store..</code> path


</translate>
<syntaxHighlight lang=nix>
<syntaxHighlight lang=nix>
{ self, ... }@inputs:
{ self, ... }@inputs:
{
{
  # This will be shown in `nix flake info`
  description = "A description of what this flake provides";
   # Executed by `nix flake check`
   # Executed by `nix flake check`
   checks."<system>"."<attr>" = derivation;
   checks."<system>"."<name>" = derivation;
   # Executed by `nix build .#<name>`
   # Executed by `nix build .#<name>`
   packages."<system>"."<attr>" = derivation;
   packages."<system>"."<name>" = derivation;
   # Executed by `nix build .`
   # Executed by `nix build .`
   defaultPackage."<system>" = derivation;
   packages."<system>".default = derivation;
   # Executed by `nix run .#<name>`
   # Executed by `nix run .#<name>`
   apps."<system>"."<attr>" = {
   apps."<system>"."<name>" = {
     type = "app";
     type = "app";
     program = "<store-path>";
     program = "<store-path>";
   };
   };
   # Executed by `nix run . -- <args?>`
   # Executed by `nix run . -- <args?>`
   defaultApp."<system>" = { type = "app"; program = "..."; };
   apps."<system>".default = { type = "app"; program = "..."; };
    
 
  # Formatter (alejandra, nixfmt or nixpkgs-fmt)
   formatter."<system>" = derivation;
   # Used for nixpkgs packages, also accessible via `nix build .#<name>`
   # Used for nixpkgs packages, also accessible via `nix build .#<name>`
   legacyPackages."<system>"."<attr>" = derivation;
   legacyPackages."<system>"."<name>" = derivation;
   # Default overlay, for use in dependent flakes
   # Overlay, consumed by other flakes
   overlay = final: prev: { };
   overlays."<name>" = final: prev: { };
   # Same idea as overlay but a list or attrset of them.
   # Default overlay
   overlays = {};
   overlays.default = final: prev: { };
   # Default module, for use in dependent flakes
   # Nixos module, consumed by other flakes
   nixosModule = { config }: { options = {}; config = {}; };
   nixosModules."<name>" = { config, ... }: { options = {}; config = {}; };
   # Same idea as nixosModule but a list or attrset of them.
   # Default module
   nixosModules = {};
   nixosModules.default = { config, ... }: { options = {}; config = {}; };
   # Attrset of nixos configurations by hostname.
   # Used with `nixos-rebuild switch --flake .#<hostname>`
  # nixosConfigurations."<hostname>".config.system.build.toplevel must be a derivation
   nixosConfigurations."<hostname>" = {};
   nixosConfigurations."<hostname>" = {};
  # Used by `nix develop .#<name>`
  devShells."<system>"."<name>" = derivation;
  # Used by `nix develop`
  devShells."<system>".default = derivation;
   # Hydra build jobs
   # Hydra build jobs
   hydraJobs."<attr>"."<system>" = derivation;
   hydraJobs."<attr>"."<system>" = derivation;
   # Used by `nix flake init -t <flake>`
   # Used by `nix flake init -t <flake>#<name>`
   defaultTemplate = {
   templates."<name>" = {
     path = "<store-path>";
     path = "<store-path>";
     description = "template description goes here?";
     description = "template description goes here?";
   };
   };
   # Used by `nix flake init -t <flake>#<attr>`
   # Used by `nix flake init -t <flake>`
   templates."<attr>" = { path = "<store-path>"; description = ""; );
   templates.default = { path = "<store-path>"; description = ""; };
}
}
</syntaxHighlight>
</syntaxHighlight>
<translate>
<!--T:48-->
You can also define additional arbitrary attributes, but these are the outputs that Nix knows about.
== Core usage patterns == <!--T:208-->
=== Making your evaluations pure === <!--T:60-->
<!--T:61-->
Nix flakes are evaluated in a pure evaluation mode, meaning that access to the external environment is restricted to ensure reproducibility. To maintain purity when working with flakes, consider the following:


== Using flakes project from a legacy Nix ==
<!--T:62-->
There is a [https://github.com/edolstra/flake-compat flake-compat] library you can use to shim legacy <code>default.nix</code> and <code>shell.nix</code> files. It will download the inputs of the flake, pass them to the flake’s <code>outputs</code> function and return an attribute set containing <code>defaultNix</code> and <code>shellNix</code> attributes. The attributes will contain the output attribute set with an extra <code>default</code> attribute pointing to current platform’s <code>defaultPackage</code> (resp. <code>devShell</code> for <code>shellNix</code>).
* {{Nixpkgs Manual|name=fetchurl|anchor=#sec-pkgs-fetchers-fetchurl-inputs}} and {{Nixpkgs Manual|name=fetchzip|anchor=#sec-pkgs-fetchers-fetchzip-inputs}} require a <code>sha256</code> argument to be considered pure.


Place the following into <code>default.nix</code> (for <code>shell.nix</code>, replace <code>defaultNix</code> with <code>shellNix</code>) to use the shim:
<!--T:156-->
* <code>builtins.currentSystem</code> is non-hermetic and impure as it reflects the host system performing the evauluation. This can usually be avoided by passing the system (i.e., x86_64-linux) explicitly to derivations requiring it.


<syntaxHighlight lang=nix>
<!--T:209-->
(import (
* <code>builtins.getEnv</code> is also impure. Avoid reading from environment variables and likewise, do not reference files outside of the flake's directory.
  fetchTarball {
    url = "https://github.com/edolstra/flake-compat/archive/c75e76f80c57784a6734356315b306140646ee84.tar.gz";
    sha256 = "071aal00zp2m9knnhddgr2wqzlx6i6qa1263lv1y7bdn2w20h10h"; }
) {
  src = ./.;
}).defaultNix
</syntaxHighlight>


You can also use the lockfile to make updating the hashes easier using <code>nix flake update --update-input flake-compat</code>. Add the following to your <code>flake.nix</code>:
=== Defining a flake for multiple architectures === <!--T:210-->


<syntaxHighlight lang=nix>
<!--T:211-->
  inputs.flake-compat = {
Flakes force you to specify a program for each supported architecture. An example below shows how to write a flake that targets multiple architectures.
    url = "github:edolstra/flake-compat";
    flake = false;
  };
</syntaxHighlight>


and add <code>flake-compat</code> to the arguments of <code>outputs</code> attribute. Then you will be able to use <code>default.nix</code> like the following:
<!--T:212-->
<syntaxhighlight lang="nix">
{
  description = "A flake targeting multiple architectures";


<syntaxHighlight lang=nix>
  <!--T:213-->
(import (
inputs = {
  let
     nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
    lock = builtins.fromJSON (builtins.readFile ./flake.lock);
  };
  in fetchTarball {
     url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz";
    sha256 = lock.nodes.flake-compat.locked.narHash; }
) {
  src =  ./.;
}).defaultNix
</syntaxHighlight>


  <!--T:214-->
outputs = { self, nixpkgs }: let
    systems = [ "x86_64-linux" "aarch64-linux" ];
    forAllSystems = f: builtins.listToAttrs (map (system: {
      name = system;
      value = f system;
    }) systems);
  in {
    packages = forAllSystems (system: let
      pkgs = nixpkgs.legacyPackages.${system};
    in {
      hello = pkgs.hello;
      default = pkgs.hello;
    });
  };
}
</syntaxhighlight>


== The nix flakes command ==
<!--T:215-->
You can also use third-parties projects like [[Flake Utils|flake-utils]] or [[Flake Parts|flake-parts]] that automatically provide code to avoid this boilerplate. To avoid re-defining the program multiple times, refer to [[Flake Utils#Defining a flake for multiple architectures]]


The nix flake subcommand is described [[Nix command/flake|here]].
=== Using overlays === <!--T:216-->


== Using nix flakes with NixOS ==
<!--T:217-->
To use [[Overlays]] with flakes, refer to [[Overlays#In a Nix flake]] page.


nixos-rebuild switch will reads its configuration from <code>/etc/nixos/flake.nix</code> if is present.
=== Enable unfree software === <!--T:129-->


A basic nixos flake.nix could look like this:
<!--T:218-->
To allow for [[Unfree software|unfree software]] in a flake project, you need to explicitly allow it by setting <code>config.allowUnree = true;</code> when importing Nixpkgs.


<syntaxHighlight lang=nix>
<!--T:219-->
<syntaxhighlight lang="nix">
{
{
   outputs = { self, nixpkgs }: {
  inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
    # replace 'joes-desktop' with your hostname here.
   outputs = { self, nixpkgs, flake-compat }:
    nixosConfigurations.joes-desktop = nixpkgs.lib.nixosSystem {
    let
      system = "x86_64-linux";
      system = "x86_64-linux";
      modules = [ ./configuration.nix ];
      pkgs = import nixpkgs { inherit system; config.allowUnfree = true;};
    };
    in {
  };
      ...
    };
}
}
</syntaxHighlight>
</syntaxhighlight>  
 
== NixOS configuration with flakes == <!--T:220-->
 
<!--T:221-->
It is possible to manage a [[NixOS]] system configuration using flakes, gaining the benefits of reproducible, declarative inputs and streamlined updates.


nixos-rebuild also allows to specify different flake using the <code>--flake</code> flag (# is optional):
<!--T:222-->
For details and examples, see [[NixOS system configuration#Defining NixOS as a flake]].


<syntaxHighlight lang=console>
== Development tricks == <!--T:131-->
$ sudo nixos-rebuild switch --flake '.#'
</syntaxHighlight>


By default nixos-rebuild will use the currents system hostname to lookup the right nixos configuration in <code>nixosConfigurations</code>. You can also override this by using appending it to the flake parameter:
=== Automatically switch nix shells with direnv === <!--T:97-->


<syntaxHighlight lang=console>
<!--T:98-->
$ sudo nixos-rebuild switch --flake '/etc/nixos#joes-desktop'
It is possible to automatically activate different Nix shells when navigating between project directories by using [[Direnv]]. Additional Nix integration with Direnv can be achieved with [https://github.com/nix-community/nix-direnv nix-direnv].
</syntaxHighlight>


To switch a remote configuration, use:
=== Pushing Flakes to Cachix === <!--T:99-->
<syntaxHighlight lang=console>
$ nixos-rebuild --flake .#mymachine \
  --target-host mymachine-hostname --build-host localhost \
  switch
</syntaxHighlight>
{{warning|Remote building seems to be broken at the moment, which is why the build host is set to “localhost”.}}


== Super fast nix-shell ==
</translate>
https://docs.cachix.org/pushing#flakes
<translate>


One of the nix feature of the Flake edition is that Nix evaluations are cached.
=== Flake support in projects without flakes === <!--T:50-->


Let’s say that your project has a <code>shell.nix</code> file that looks like this:
<!--T:51-->
The [https://github.com/edolstra/flake-compat flake-compat] library provides a compatibility layer that allows projects using traditional <code>default.nix</code> and <code>shell.nix</code> files to operate with flakes. For more details and usage examples, see the [[Flake Compat]] page.


<syntaxHighlight lang=nix>
<!--T:223-->
{ pkgs ? import <nixpkgs> { } }:
Another project that allows consuming flakes from non-flake projects is [https://github.com/fricklerhandwerk/flake-inputs flake-inputs].
with pkgs;
mkShell {
  buildInputs = [
    nixpkgs-fmt
  ];


  shellHook = ''
=== Accessing flakes from Nix expressions === <!--T:58-->
    # ...
  '';
}
</syntaxHighlight>


Running nix-shell can be a bit slow and take 1-3 seconds.
<!--T:59-->
If you want to access a flake from within a regular Nix expression on a system that has flakes enabled, you can use something like <code>(builtins.getFlake "/path/to/directory").packages.x86_64-linux.default</code>, where 'directory' is the directory that contains your <code>flake.nix</code>.


Now create a <code>flake.nix</code> file in the same repository:
=== Efficiently build multiple flake outputs === <!--T:224-->


<syntaxHighlight lang=nix>
<!--T:101-->
{
To push ''all'' flake outputs automatically, checkout [https://github.com/srid/devour-flake#usage devour-flake].
  description = "my project description";


  inputs.flake-utils.url = "github:numtide/flake-utils";
=== Build a package added in a PR === <!--T:161-->


  outputs = { self, nixpkgs, flake-utils }:
</translate>
    flake-utils.lib.eachDefaultSystem
<syntaxHighlight>
      (system:
nix build github:nixos/nixpkgs?ref=pull/<PR_NUMBER>/head#<PACKAGE>
        let pkgs = nixpkgs.legacyPackages.${system}; in
        {
          devShell = import ./shell.nix { inherit pkgs; };
        }
      );
}
</syntaxHighlight>
</syntaxHighlight>
<translate>


Run git add flake.nix so that Nix recognizes it.
<!--T:162-->
this allows building a package that has not yet been added to nixpkgs.


And finally, run <code>nix develop</code>. This is what replaces the old nix-shell invocation.
<!--T:132-->
note that this will download a full source tarball of nixpkgs. if you already have a local clone, using that may be faster due to delta compression:


Exit and run again, this command should now be super fast.
</translate>
<syntaxHighlight>
git fetch upstream pull/<PR_NUMBER>/head && git checkout FETCH_HEAD && nix build .#PACKAGE
</syntaxHighlight>
<translate>


{{warning|TODO: there is an alternative version where the defaultPackage is a pkgs.buildEnv that contains all the dependencies. And then nix shell is used to open the environment.}}
<!--T:163-->
this allows building a package that has not yet been added to nixpkgs.


=== Direnv integration ===
=== How to add a file locally in git but not include it in commits === <!--T:164-->


Assuming that the flake defines a <code>devShell</code> output attribute and that you are using direnv. Here is how to replace the old use nix stdlib function with the faster flake version:
<!--T:133-->
When a [[git]] folder exists, flake will only copy files added in git to maximize reproducibility (this way if you forgot to add a local file in your repo, you will directly get an error when you try to compile it). However, for development purpose you may want to create an alternative flake file, for instance containing configuration for your preferred editors as described [https://discourse.nixos.org/t/local-personal-development-tools-with-flakes/22714/8 here]… of course without committing this file since it contains only your own preferred tools. You can do so by doing something like that (say for a file called <code>extra/flake.nix</code>):


<syntaxHighlight lang=sh>
</translate>
use_flake() {
<syntaxHighlight>
  watch_file flake.nix
git add --intent-to-add extra/flake.nix
  watch_file flake.lock
git update-index --skip-worktree --assume-unchanged extra/flake.nix
  eval "$(nix print-dev-env --profile "$(direnv_layout_dir)/flake-profile")"
}
</syntaxHighlight>
</syntaxHighlight>
<translate>
=== Rapid iteration of a direct dependency === <!--T:135-->
<!--T:165-->
One common pain point with using Nix as a development environment is the need to completely rebuild dependencies and re-enter the dev shell every time they are updated. The <code>nix develop --redirect <flake> <directory></code> command allows you to provide a mutable dependency to your shell as if it were built by Nix.
<!--T:136-->
Consider a situation where your executable, <code>consumexe</code>, depends on a library, <code>libdep</code>. You're trying to work on both at the same time, where changes to <code>libdep</code> are reflected in real time for <code>consumexe</code>. This workflow can be achieved like so:


Copy this in <code>~/.config/direnv/lib/use_flake.sh</code> or in <code>~/.config/direnv/direnvrc</code>
</translate>
or directly in your project specific <code>.envrc</code>.
<syntaxHighlight lang=bash>
cd ~/libdep-src-checkout/
nix develop # Or `nix-shell` if applicable.
export prefix="./install" # configure nix to install it here
buildPhase  # build it like nix does
installPhase # install it like nix does
</syntaxHighlight>
<translate>


With this in place, you can now replace the use nix invocation in the <code>.envrc</code> file with <code>use flake</code>:
<!--T:166-->
Now that you've built the dependency, <code>consumexe</code> can take it as an input. '''In another terminal''':


<syntaxHighlight>
</translate>
# .envrc
<syntaxHighlight lang=bash>
use flake
cd ~/consumexe-src-checkout/
nix develop --redirect libdep ~/libdep-src-checkout/install
echo $buildInputs | tr " " "\n" | grep libdep
# Output should show ~/libdep-src-checkout/ so you know it worked
</syntaxHighlight>
</syntaxHighlight>
<translate>
<!--T:167-->
If Nix warns you that your redirected flake isn't actually used as an input to the evaluated flake, try using the <code>--inputs-from .</code> flag. If all worked well you should be able to <code>buildPhase && installPhase</code> when the dependency changes and rebuild your consumer with the new version ''without'' exiting the development shell.
== See also == <!--T:138-->
=== Official sources === <!--T:225-->
<!--T:139-->
* [https://nix.dev/concepts/flakes Flakes] - nix.dev
<!--T:176-->
* [https://nixos.org/manual/nix/unstable/command-ref/new-cli/nix3-flake.html Nix flake command reference manual] - Many additional details about flakes, and their parts.
<!--T:178-->
* [https://github.com/NixOS/nix/blob/master/src/nix/flake.md spec describing flake inputs in more detail]


The nice thing about this approach is that evaluation is cached.
<!--T:168-->
* [https://github.com/NixOS/rfcs/pull/49 RFC 49] (2019) - Original flakes specification


==== Optimize the reloads ====  
=== Guides === <!--T:226-->


Nix Flakes has a Nix evaluation caching mechanism. Is it possible to expose that somehow to automatically trigger direnv reloads?
<!--T:169-->
* [https://jade.fyi/blog/flakes-arent-real/ Flakes aren't real and can't hurt you] (Jade Lovelace, 2024)


With the previous solution, direnv would only reload iff the flake.nix or flake.lock files have changed. This is not completely precise as the flake.nix file might import other files in the repository.
<!--T:170-->
* [https://github.com/ryan4yin/nixos-and-flakes-book NixOS & Flakes Book](Ryan4yin, 2023) - 🛠️ ❤️ An unofficial NixOS & Flakes book for beginners.


== Pushing Flake inputs to Cachix ==
<!--T:171-->
* [https://xeiaso.net/blog/nix-flakes-1-2022-02-21 Nix Flakes: an Introduction] (Xe Iaso, 2022)


Flake inputs can also be cached in the Nix binary cache!
<!--T:172-->
* [https://serokell.io/blog/practical-nix-flakes Practical Nix Flakes] (Alexander Bantyev, 2021) - Intro article on working with Nix and Flakes


<syntaxHighlight lang=console>
<!--T:173-->
$ nix flake archive --json \
* [https://www.tweag.io/blog/2020-05-25-flakes/ Nix Flakes, Part 1: An introduction and tutorial] (Eelco Dolstra, 2020)
  | jq -r '.path,(.inputs|to_entries[].value.path)' \
  | cachix push $cache_name
</syntaxHighlight>


== Build specific attributes in a flake repository ==
<!--T:174-->
* [https://www.tweag.io/blog/2020-06-25-eval-cache/ Nix Flakes, Part 2: Evaluation caching] (Eelco Dolstra, 2020)


When in the repository top-level, run <code>nix build .#<attr></code>. It will look in the <code>legacyPackages</code> and <code>packages</code> output attributes for the corresponding derivation.
<!--T:175-->
* [https://www.tweag.io/blog/2020-07-31-nixos-flakes/ Nix Flakes, Part 3: Managing NixOS systems] (Eelco Dolstra, 2020)


Eg, in nixpkgs:
<!--T:177-->
* [https://www.youtube.com/watch?v=QXUlhnhuRX4&list=PLgknCdxP89RcGPTjngfNR9WmBgvD_xW0l Nix flakes 101: Introduction to nix flakes] (Jörg Thalheim, 2020) YouTube video


<syntaxHighlight lang=console>
=== Useful flake modules === <!--T:227-->  
$ nix build .#hello
</syntaxHighlight>


== Importing packages from multiple channels ==
<!--T:179-->
* [[Flake Utils|flake-utils]]: Library to avoid some boiler-code when writing flakes


You can import packages from different channels by creating an overlay on the ''pkgs'' attribute :
<!--T:228-->
<syntaxHighlight lang=nix>
* [[Flake Parts|flake-parts]]: Library to help write modular and organized flakes
let
  overlay-unstable = final: prev: {
    unstable = nixpkgs-unstable.legacyPackages.${system}; # considering nixpkgs-unstable is an input registered before.
  };
in nixpkgs.overlays = [ overlay-unstable ]; # we assign the overlay created before to the overlays of nixpkgs.
</syntaxHighlight>
should make a package accessible through <syntaxHighlight>pkgs.unstable.package</syntaxHighlight>
Same can be done with the NURs, as it already has an ''overlay'' attribute in the flake.nix of the project, you can just add <syntaxHighlight>nixpkgs.overlays = [ nur.overlay ];</syntaxHighlight>


== Enable unfree software ==
<!--T:229-->
* [[Flake Compat|flake-compat]]: A compatibility layer for flakes


Follow the instructions at
<!--T:181-->
https://discourse.nixos.org/t/using-non-free-libraries-in-flakes/8632/5
* [https://github.com/nix-community/todomvc-nix building Rust and Haskell flakes]


== See also ==
<!--T:230-->
{{references}}


* [https://github.com/numtide/flake-utils flake-utils: Library to avoid some boiler-code when writing flakes]
</translate>
* [https://zimbatm.com/NixFlakes/#direnv-integration zimbat's direnv article]
[[Category:Software]]
* [https://www.tweag.io/blog/2020-05-25-flakes/ Nix Flakes, Part 1: An introduction and tutorial]
[[Category:Nix]]
* [https://www.tweag.io/blog/2020-06-25-eval-cache/ Nix Flakes, Part 2: Evaluation caching]
[[Category:Nix Language]]
* [https://www.tweag.io/blog/2020-07-31-nixos-flakes/ Nix Flakes, Part 3: Managing NixOS systems]
[[Category:Flakes]]

Latest revision as of 12:07, 24 July 2025

⚟︎
This article or section needs cleanup. Please edit the article, paying special attention to fixing any formatting issues, inconsistencies, grammar, or phrasing. Make sure to consult the Manual of Style for guidance.

Nix flakes are an experimental feature first introduced in the 2.4 Nix release,[1][2] aiming to address a number of areas of improvement for the Nix ecosystem: they provide a uniform structure for Nix projects, allow for pinning specific versions of each dependencies, and sharing these dependencies via lock files, and overall make it more convenient to write reproducible Nix expressions.

A flake is a directory which directly contains a Nix file called flake.nix, that follows a very specific structure. Flakes introduce a URL-like syntax[3] for specifying remote resources. To simplify the URL syntax, flakes use a registry of symbolic identifiers,[4] allowing the direct specification of resources through syntax such as github:NixOS/nixpkgs.

Flakes also allow for locking references and versions, which can then be queried and updated programatically via the inputs [5][6]. Additionally, an experimental CLI utility accepts flake references for expressions that build, run, and deploy packages.[7]

Flake file structure

Minimally, a flake file contains a description of the flake, a set of input dependencies and an output. You can generate a very basic flake file at any time using nix flake init. This will populate the current directory with a file called flake.nix that will contain something akin to:

❄︎ flake.nix
{
  description = "A very basic flake";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  };

  outputs = { self, nixpkgs }: {

    packages.x86_64-linux.hello = nixpkgs.legacyPackages.x86_64-linux.hello;

    packages.x86_64-linux.default = self.packages.x86_64-linux.hello;

  };
}

In the example above, you can see the description, the input specified as a GitHub repository with a specific branch (here nixos/nixpkgs on the nixos-unstable branch), and an output that makes use of the input. The output simply specifies that the flake contains one package for the x86_64 architecture called hello. Even if your flake's output wouldn't use its input (however, in practice, that is highly unlikely), the output still needs to be a Nix function.

Note: Flakes require you to specify its outputs for each architecture separately. For more information, read the related section below.

Nix configuration

It is possible to override the global Nix configuration set in your nix.conf file for the purposes of evaluating a flake. This can be useful, for example, for setting up binary caches specific to certain projects, while keeping the global configuration untouched. The flake file can contain a nixConfig attribute with any relevant configuration settings supplied. For example, enabling the nix-community binary cache would be achieved by:

❄︎ flake.nix
{
  ...
  nixConfig = {
    extra-substituters = [
      "https://nix-community.cachix.org"
    ];
    extra-trusted-public-keys = [
      "nix-community.cachix.org-1:...="
    ];
  }
}
Note: If you are used to configuring your Nix settings via the NixOS configuration, these options are under nix.settings and not nix. For example, you cannot specify the automatic storage optimisation under nix.optimisation.enable.

Setup

Enabling flakes temporarily

When using any nix command, add the following command-line options:

 --experimental-features 'nix-command flakes'

Enabling flakes permanently

NixOS

Add the following to the NixOS configuration:

  nix.settings.experimental-features = [ "nix-command" "flakes" ];

Home Manager

Add the following to your home manager config:

  nix.settings.experimental-features = [ "nix-command" "flakes" ];

Nix standalone

Note: The Determinate Nix Installer enables flakes by default.

Add the following to ~/.config/nix/nix.conf or /etc/nix/nix.conf:

experimental-features = nix-command flakes

Usage

⚠︎
Warning: Since contents of flake files are copied to the world-readable Nix store folder, do not put any unencrypted secrets in flake files. You should instead use a secret managing scheme.
Note: For flakes in git repositories, only files in the working tree will be copied to the store. Therefore, if you use git for your flake, ensure to git add any project files after you first create them.

The nix flakes command

Main article: Nix (command)

The nix flake subcommand is described in command reference page of the Nix manual.

This flake produces a single flake output packages. And within that, x86_64-linux is a system-specifc attribute set. And within that, two package derivations default and hello. You can find outputs with the show command of a flake as shown below:

$ nix flake show
└───packages
    └───x86_64-linux
        ├───default: package 'hello-2.12.2'
        └───hello: package 'hello-2.12.2'

Development shells

A devShell is a Nix-provided development environment defined within a flake. It lets you declare a reproducible shell environment with the tools, libraries, and environment variables you need for the development of a specific project. This is flake equivalent to defining a nix-shell.

{
  description = "Example flake with a devShell";

  inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";

  outputs = { self, nixpkgs}:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { inherit system; };
    in {
      devShells.x86_64-linux.default = pkgs.mkShell {
        buildInputs = with pkgs; [
          hello
        ];
        shellHook = ''
          echo "Welcome to the devShell!"
        '';
      };
    };
}

To enter the development shell environment:

$ nix develop
Note: You don’t need to define a devShell to enter a development shell using nix develop. If no devShell is defined, nix develop will drop you into an environment containing the default build dependencies of the flake (if any).

Build specific attributes in a flake repository

Running nix build will look in the legacyPackages and packages output attributes for the corresponding derivation and then your system architecture and build the default output. If you want to specify a build attribute in a flake repository, you can run nix build .#<attr>. In the example above, if you wanted to build the packages.x86_64-linux.hello attribute, run:

$ nix build .#hello

Likewise, you can specify an attribute with the run command: nix run .#hello and the develop command: nix develop .#hello.

Flake schema

The flake.nix file is a Nix file but that has special restrictions (more on that later).

It has 4 top-level attributes:

  • description is a string describing the flake.
  • inputs is an attribute set of all the dependencies of the flake. The schema is described below.
  • outputs is a function of one argument that takes an attribute set of all the realized inputs, and outputs another attribute set whose schema is described below.
  • nixConfig is an attribute set of values which reflect the values given to nix.conf. This can extend the normal behavior of a user's nix experience by adding flake-specific configuration, such as a binary cache.

Input schema

The nix flake inputs manual.

The nix flake references manual.

The inputs attribute defines the dependencies of the flake. For example, nixpkgs has to be defined as a dependency for a system flake in order for the system to build properly.

Nixpkgs can be defined using the following code:

inputs.nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";

Nixpkgs can alternatively also point to an url cached by the NixOS organization:

inputs.nixpkgs.url = "https://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz";

In this example the input would point to the `nixpkgs-unstable` channel.


For any repository with its own flake.nix file, the website must also be defined. Nix knows where the nixpkgs repository is, so stating that it's on GitHub is unnecessary.

For example, adding Hyprland as an input would look something like this:

inputs.hyprland.url = "github:hyprwm/Hyprland";

If you want to make Hyprland follow the nixpkgs input to avoid having multiple versions of nixpkgs, this can be done using the following code:

inputs.hyprland.inputs.nixpkgs.follows = "nixpkgs";

Using curly brackets({}), we can shorten all of this and put it in a table. The code will look something like this:

inputs = {
  nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";
  hyprland = {
    url = "github:hyprwm/Hyprland";
    inputs.nixpkgs.follows = "nixpkgs";
  };
};

By default, Git submodules in package src's won't get copied to the nix store, this may cause the build to fail. Flakes in Git repositories can declare that they need Git submodules to be enabled. Since Nix version 2.27, you can enable submodules by:

  inputs.self.submodules = true;

Output schema

This is described in the nix package manager src/nix/flake-check.md.

Once the inputs are resolved, they're passed to the function `outputs` along with with `self`, which is the directory of this flake in the store. `outputs` returns the outputs of the flake, according to the following schema.

Where:

  • <system> is something like "x86_64-linux", "aarch64-linux", "i686-linux", "x86_64-darwin"
  • <name> is an attribute name like "hello".
  • <flake> is a flake name like "nixpkgs".
  • <store-path> is a /nix/store.. path
{ self, ... }@inputs:
{
  # Executed by `nix flake check`
  checks."<system>"."<name>" = derivation;
  # Executed by `nix build .#<name>`
  packages."<system>"."<name>" = derivation;
  # Executed by `nix build .`
  packages."<system>".default = derivation;
  # Executed by `nix run .#<name>`
  apps."<system>"."<name>" = {
    type = "app";
    program = "<store-path>";
  };
  # Executed by `nix run . -- <args?>`
  apps."<system>".default = { type = "app"; program = "..."; };

  # Formatter (alejandra, nixfmt or nixpkgs-fmt)
  formatter."<system>" = derivation;
  # Used for nixpkgs packages, also accessible via `nix build .#<name>`
  legacyPackages."<system>"."<name>" = derivation;
  # Overlay, consumed by other flakes
  overlays."<name>" = final: prev: { };
  # Default overlay
  overlays.default = final: prev: { };
  # Nixos module, consumed by other flakes
  nixosModules."<name>" = { config, ... }: { options = {}; config = {}; };
  # Default module
  nixosModules.default = { config, ... }: { options = {}; config = {}; };
  # Used with `nixos-rebuild switch --flake .#<hostname>`
  # nixosConfigurations."<hostname>".config.system.build.toplevel must be a derivation
  nixosConfigurations."<hostname>" = {};
  # Used by `nix develop .#<name>`
  devShells."<system>"."<name>" = derivation;
  # Used by `nix develop`
  devShells."<system>".default = derivation;
  # Hydra build jobs
  hydraJobs."<attr>"."<system>" = derivation;
  # Used by `nix flake init -t <flake>#<name>`
  templates."<name>" = {
    path = "<store-path>";
    description = "template description goes here?";
  };
  # Used by `nix flake init -t <flake>`
  templates.default = { path = "<store-path>"; description = ""; };
}

You can also define additional arbitrary attributes, but these are the outputs that Nix knows about.

Core usage patterns

Making your evaluations pure

Nix flakes are evaluated in a pure evaluation mode, meaning that access to the external environment is restricted to ensure reproducibility. To maintain purity when working with flakes, consider the following:

  • builtins.currentSystem is non-hermetic and impure as it reflects the host system performing the evauluation. This can usually be avoided by passing the system (i.e., x86_64-linux) explicitly to derivations requiring it.
  • builtins.getEnv is also impure. Avoid reading from environment variables and likewise, do not reference files outside of the flake's directory.

Defining a flake for multiple architectures

Flakes force you to specify a program for each supported architecture. An example below shows how to write a flake that targets multiple architectures.

{
  description = "A flake targeting multiple architectures";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  };

  outputs = { self, nixpkgs }: let
    systems = [ "x86_64-linux" "aarch64-linux" ];
    forAllSystems = f: builtins.listToAttrs (map (system: {
      name = system;
      value = f system;
    }) systems);
  in {
    packages = forAllSystems (system: let
      pkgs = nixpkgs.legacyPackages.${system};
    in {
      hello = pkgs.hello;
      default = pkgs.hello;
    });
  };
}

You can also use third-parties projects like flake-utils or flake-parts that automatically provide code to avoid this boilerplate. To avoid re-defining the program multiple times, refer to Flake Utils#Defining a flake for multiple architectures

Using overlays

To use Overlays with flakes, refer to Overlays#In a Nix flake page.

Enable unfree software

To allow for unfree software in a flake project, you need to explicitly allow it by setting config.allowUnree = true; when importing Nixpkgs.

{
  inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  outputs = { self, nixpkgs, flake-compat }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { inherit system; config.allowUnfree = true;};
    in {
      ...
    };
}

NixOS configuration with flakes

It is possible to manage a NixOS system configuration using flakes, gaining the benefits of reproducible, declarative inputs and streamlined updates.

For details and examples, see NixOS system configuration#Defining NixOS as a flake.

Development tricks

Automatically switch nix shells with direnv

It is possible to automatically activate different Nix shells when navigating between project directories by using Direnv. Additional Nix integration with Direnv can be achieved with nix-direnv.

Pushing Flakes to Cachix

https://docs.cachix.org/pushing#flakes

Flake support in projects without flakes

The flake-compat library provides a compatibility layer that allows projects using traditional default.nix and shell.nix files to operate with flakes. For more details and usage examples, see the Flake Compat page.

Another project that allows consuming flakes from non-flake projects is flake-inputs.

Accessing flakes from Nix expressions

If you want to access a flake from within a regular Nix expression on a system that has flakes enabled, you can use something like (builtins.getFlake "/path/to/directory").packages.x86_64-linux.default, where 'directory' is the directory that contains your flake.nix.

Efficiently build multiple flake outputs

To push all flake outputs automatically, checkout devour-flake.

Build a package added in a PR

nix build github:nixos/nixpkgs?ref=pull/<PR_NUMBER>/head#<PACKAGE>

this allows building a package that has not yet been added to nixpkgs.

note that this will download a full source tarball of nixpkgs. if you already have a local clone, using that may be faster due to delta compression:

git fetch upstream pull/<PR_NUMBER>/head && git checkout FETCH_HEAD && nix build .#PACKAGE

this allows building a package that has not yet been added to nixpkgs.

How to add a file locally in git but not include it in commits

When a git folder exists, flake will only copy files added in git to maximize reproducibility (this way if you forgot to add a local file in your repo, you will directly get an error when you try to compile it). However, for development purpose you may want to create an alternative flake file, for instance containing configuration for your preferred editors as described here… of course without committing this file since it contains only your own preferred tools. You can do so by doing something like that (say for a file called extra/flake.nix):

git add --intent-to-add extra/flake.nix
git update-index --skip-worktree --assume-unchanged extra/flake.nix

Rapid iteration of a direct dependency

One common pain point with using Nix as a development environment is the need to completely rebuild dependencies and re-enter the dev shell every time they are updated. The nix develop --redirect <flake> <directory> command allows you to provide a mutable dependency to your shell as if it were built by Nix.

Consider a situation where your executable, consumexe, depends on a library, libdep. You're trying to work on both at the same time, where changes to libdep are reflected in real time for consumexe. This workflow can be achieved like so:

cd ~/libdep-src-checkout/
nix develop # Or `nix-shell` if applicable.
export prefix="./install" # configure nix to install it here
buildPhase   # build it like nix does
installPhase # install it like nix does

Now that you've built the dependency, consumexe can take it as an input. In another terminal:

cd ~/consumexe-src-checkout/
nix develop --redirect libdep ~/libdep-src-checkout/install
echo $buildInputs | tr " " "\n" | grep libdep
# Output should show ~/libdep-src-checkout/ so you know it worked

If Nix warns you that your redirected flake isn't actually used as an input to the evaluated flake, try using the --inputs-from . flag. If all worked well you should be able to buildPhase && installPhase when the dependency changes and rebuild your consumer with the new version without exiting the development shell.

See also

Official sources

  • RFC 49 (2019) - Original flakes specification

Guides

  • NixOS & Flakes Book(Ryan4yin, 2023) - 🛠️ ❤️ An unofficial NixOS & Flakes book for beginners.

Useful flake modules

  • flake-utils: Library to avoid some boiler-code when writing flakes
  • flake-parts: Library to help write modular and organized flakes

References

  1. Nix Reference Manual, §13.8. Experimental Features, 📖︎ flakes subsection
  2. Nix Reference Manual, §14.27. 📖︎ Release 2.4 (2021-11-01)
  3. Nix Reference Manual, §8.5.17. nix flake, 📖︎ URL-like syntax subsection
  4. Nix Reference Manual, §8.5.62. 📖︎ nix registry
  5. Nix Reference Manual, §7.5.19. 📖︎ nix flake lock
  6. Nix Reference Manual, §7.5.17. 📖︎ nix flake info
  7. Nix Reference Manual, §8.5.1. 📖︎ nix