Jump to content

Flakes

From NixOS Wiki
This page contains changes which are not marked for translation.

Nix flakes is an experimental feature that was introduced with Nix 2.4 (see release notes).

Introduction

Nix flakes enforce a uniform structure for Nix projects, pin versions of their dependencies in a lock file, and make it more convenient to write reproducible Nix expressions.

  • A flake refers to a file-system tree whose root directory contains the Nix file specification called flake.nix.
  • The contents of flake.nix file follow a uniform naming schema for declaring packages and their dependencies in the Nix language.
  • Flakes also allow for locking references and versions that can then be queried and updated programmatically.

Enabling flakes

Enable flakes temporarily

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

 --experimental-features 'nix-command flakes'

Enable flakes permanently in NixOS

Add the following to the NixOS configuration:

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

With Home Manager

Add the following to your home manager config:

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

Other Distros, without Home Manager

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

Basic Usage of Flake

⚠︎
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.

Generate flake.nix file

To initialize a flake, run the following flake command in the project directory:

$ nix flake init

Common structure

The above command will provide a very simple flake file looking like:

{
  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;

  };
}

You will then be able to build this flake with nix build and run it with nix run

Note: Flakes force you to specify a program for each supported architecture. To avoid this, refer to #Defining a flake for multiple architectures section of the wiki.

The nix flakes 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

Using nix flakes with NixOS

By default, nixos-rebuild switch will read its configuration from /etc/nixos/flake.nix if it is present.

A basic NixOS flake.nix could look like this:

{
  inputs.nixpkgs.url = github:NixOS/nixpkgs/nixos-unstable;
  outputs = { self, nixpkgs }: {
    # replace 'joes-desktop' with your hostname here.
    nixosConfigurations.joes-desktop = nixpkgs.lib.nixosSystem {
      modules = [ ./configuration.nix ];
    };
  };
}

If you want to pass on the flake inputs to external configuration files, you can use the specialArgs attribute:

{
  inputs.nixpkgs.url = github:NixOS/nixpkgs/nixos-unstable;
  inputs.home-manager.url = github:nix-community/home-manager;

  outputs = { self, nixpkgs, ... }@inputs: {
    nixosConfigurations.fnord = nixpkgs.lib.nixosSystem {
      specialArgs = { inherit inputs; };
      modules = [ ./configuration.nix ];
    };
  };
}

Then, you can access the flake inputs from the file configuration.nix like this:

{ config, lib, inputs, ... }: {
  # do something with home-manager here, for instance:
  imports = [ inputs.home-manager.nixosModules.default ];
  ...
}

nixos-rebuild also allows to specify different flake using the --flake flag:

# nixos-rebuild switch --flake .

By default nixos-rebuild will use the current system hostname to look up the right NixOS configuration in nixosConfigurations. You can also override this by using appending it to the flake parameter:

# nixos-rebuild switch --flake /etc/nixos#joes-desktop

To switch a remote host you can use:

$ nixos-rebuild --flake .#mymachine \
  --target-host mymachine-hostname \
  --build-host mymachine-hostname --fast \
  switch
⚠︎
Warning: Remote building seems to have an issue that's resolved by setting the --fast flag.

Importing packages from multiple nixpkgs branches

A NixOS config flake could be as follows (replace <hostname> with your hostname):

{
  description = "NixOS configuration with two or more channels";

 inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
    nixpkgs-unstable.url = "github:NixOS/nixpkgs/nixos-unstable";
  };

  outputs =
    { nixpkgs, nixpkgs-unstable, ... }:
    {
      nixosConfigurations."<hostname>" = nixpkgs.lib.nixosSystem {
        modules = [
          {
            nixpkgs.overlays = [
              (final: prev: {
                unstable = nixpkgs-unstable.legacyPackages.${prev.system};
                # use this variant if unfree packages are needed:
                # unstable = import nixpkgs-unstable {
                #   inherit prev;
                #   system = prev.system;
                #   config.allowUnfree = true;
                # };
              })
            ];
          }
          ./configuration.nix
        ];
      };
    };
}
# NixOS configuration.nix, can now use "pkgs.package" or "pkgs.unstable.package"
{ pkgs, ... }:
{
  environment.systemPackages = [
    pkgs.firefox
    pkgs.unstable.chromium
  ];
  # ...
}

If the variable nixpkgs points to the flake, you can also define pkgs with overlays with:

pkgs = import nixpkgs { system = "x86_64-linux"; overlays = [ /*the overlay in question*/ ]; };

Pinning the registry on NixOS

{ inputs, ... }:
{
 nix.registry = {
    nixpkgs.flake = inputs.nixpkgs;
  };
}

To make sure the registry entry is "locked", use the following:

  nix.registry = {
    nixpkgs.to = {
      type = "path";
      path = pkgs.path;
      narHash = builtins.readFile
          (pkgs.runCommandLocal "get-nixpkgs-hash"
            { nativeBuildInputs = [ pkgs.nix ]; }
            "nix-hash --type sha256 --sri ${pkgs.path} > $out");
    };
  };

This has the unfortunate side-effect of requiring import-from-derivation and slowing down build times, however it may greatly speed up almost every eval. Full-time flakes users may be able to just use narHash = pkgs.narHash.

Getting Instant System Flakes Repl

How to get a nix repl out of your system flake:

$ nix repl

nix-repl> :lf /path/to/flake
Added 18 variables.

nix-repl> nixosConfigurations.myHost.config.networking.hostName
"myHost"

However, this won't be instant upon evaluation if any file changes have been done since your last configuration rebuild. Instead, if one puts:

nix.nixPath = let path = toString ./.; in [ "repl=${path}/repl.nix" "nixpkgs=${inputs.nixpkgs}" ];

In their system flake.nix configuration file, and includes the following file in their root directory flake as repl.nix:

let
  flake = builtins.getFlake (toString ./.);
  nixpkgs = import <nixpkgs> { };
in
{ inherit flake; }
// flake
// builtins
// nixpkgs
// nixpkgs.lib
// flake.nixosConfigurations

(Don't forget to git add repl.nix && nixos-rebuild switch --flake "/etc/nixos") Then one can run (or bind a shell alias):

source /etc/set-environment && nix repl $(echo $NIX_PATH | perl -pe 's|.*(/nix/store/.*-source/repl.nix).*|\1|')

This will launch a repl with access to nixpkgs, lib, and the flake options in a split of a second.

An alternative approach to the above shell alias is omitting repl from nix.nixPath and creating a shell script:

nix.nixPath = [ "nixpkgs=${inputs.nixpkgs}" ];
environment.systemPackages = let
  repl_path = toString ./.;
  my-nix-fast-repl = pkgs.writeShellScriptBin "my-nix-fast-repl" ''
    source /etc/set-environment
    nix repl "${repl_path}/repl.nix" "$@"
  '';
in [
  my-nix-fast-repl
];

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