14. Flakes: Tips, Tricks & Gotchas
A practical grab-bag for people already living in flakes
By now you've written flakes, split them into modules, rolled a bad generation back, poked at nixpkgs in the repl, written overlays and your own derivations, spun up dev shells, and wired secrets in. This last article is deliberately not a linear tutorial — it's the pile of things experienced flake users just know, collected in one place. Lock hygiene, deduping nixpkgs, the reference-URL syntax you always half-remember, the inspection commands, the caches that make builds fast, and the handful of gotchas that waste an afternoon the first time you hit them. Treat it as a reference you skim now and come back to later.
What this article is
A curated set of habits and sharp edges for day-to-day flake work: keeping
flake.lock clean, collapsing duplicate nixpkgs copies with
follows, the full flake-reference URL grammar, the nix flake
inspection trio, binary caches, and the performance traps (IFD, stale locks, dirty
trees) that bite once and then never again.
flake.lock hygiene
Your flake.lock is the reproducibility contract from the first-flake
article: every loose input reference resolved to an exact commit and content
hash. Keeping it healthy is mostly about updating deliberately and committing the result.
Update everything. The blunt instrument re-resolves all inputs to their newest matching revisions and rewrites the whole lock file:
nix flake update
This is how you pull a newer nixpkgs (and every other input) in one go. Because it only
touches flake.lock, the diff is reviewable and the rollback is trivial: if the new world
breaks, git checkout the old lock file and rebuild.
Update one input. Usually you want to bump just nixpkgs, or just home-manager, without dragging everything else forward. The syntax changed across Nix versions, and which one you use depends on how new your Nix is:
Older Nix
Before Nix 2.19, a single input was updated through nix flake lock with
an explicit flag:
nix flake lock --update-input nixpkgs
Nix 2.19 and newer
nix flake update now takes input names as positional arguments. Pass one
(or several) to update exactly those:
nix flake update nixpkgs
The old --update-input form still works in recent Nix but is deprecated in favour of the
positional form; the manual points you at nix flake update nixpkgs. If you write scripts
or docs meant to survive across Nix versions, be aware that the positional form is the one
being kept.
Test an input without touching the lock. Sometimes you want to try a different
revision of an input for one build — a bug-fix branch of nixpkgs, say — without rewriting
flake.lock at all. That's --override-input, which applies for the duration of a single
command only:
nixos-rebuild build --flake .#bluewhale \
--override-input nixpkgs github:NixOS/nixpkgs/some-fix-branch
Nothing is written to disk; the moment the command finishes, your locked nixpkgs is back in force. It's the right tool for "does this branch fix my problem?" experiments precisely because it leaves no trace.
Always commit the lock file
flake.lock is data, not build output — commit it. An update
commit is a perfect, revertible record of an upgrade: reverting the commit reverts the
upgrade, byte for byte. A repo whose lock file is git-ignored has thrown away the entire
point of flakes.
Deduping nixpkgs with follows
Here's a problem you don't notice until your evaluation gets slow and your store gets fat.
Every flake you depend on declares its own nixpkgs input. Add home-manager, a status-bar
flake, and a neovim flake, and you may now have four different nixpkgs revisions in your
lock file — yours, plus one pinned by each dependency. Each is a separate multi-hundred-megabyte
source tree Nix fetches and evaluates independently.
Worse than the disk cost is the correctness surprise: a module from home-manager might be evaluated against home-manager's nixpkgs, not yours, so a package you overrode or an option you set in your nixpkgs quietly doesn't apply. Two nixpkgs, two realities.
The fix is follows, which redirects a dependency's input to point at yours:
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
home-manager = {
url = "github:nix-community/home-manager/release-24.05";
inputs.nixpkgs.follows = "nixpkgs";
};
};
Read inputs.nixpkgs.follows = "nixpkgs" as: "home-manager's nixpkgs input should
follow my top-level nixpkgs instead of resolving on its own." Now there is one nixpkgs
for the whole flake. Everyone evaluates against the same package set, the lock file shrinks,
and eval and fetch both speed up.
For a chain of dependencies, follows composes: you can point a transitive input at your
top-level one, e.g. inputs.foo.inputs.bar.inputs.nixpkgs.follows = "nixpkgs". It reads
awkwardly, but it collapses even deeply nested duplicates. A quick nix flake metadata
(below) shows the resolved input tree, so you can see exactly which nixpkgs copies you've
managed to eliminate.
Flake reference cheat sheet
A flake reference is the little URL you put in an input's url, or after nix build /
nix run on the command line. The grammar is compact but easy to forget. Here are the
forms you'll actually use:
| Reference | Meaning |
|---|---|
github:owner/repo |
The default branch of a GitHub repo (fast, uses GitHub's tarball API). |
github:owner/repo/ref |
A specific branch, tag, or commit — e.g. github:NixOS/nixpkgs/nixos-24.05. |
git+https://host/path |
Any git repo over HTTPS. Add ?ref=BRANCH and/or ?rev=COMMIT to pin. |
git+ssh://git@host/path |
The same over SSH, for private repos. |
path:./sub |
A local directory (no git fetch; copies the path as-is). |
tarball+https://host/x.tar.gz |
A source tarball. The tarball+ prefix is optional when the extension is a known archive type. |
...?dir=subdir |
The flake.nix lives in subdir/, not the repo root — for monorepos. |
...?submodules=1 |
Fetch git submodules too (off by default). |
...?ref=X&rev=Y |
Combine query params with &; rev must exist within ref. |
reference#attr |
Select one output attribute, e.g. nixpkgs#hello or .#bluewhale. |
A few notes worth internalizing. The #attr selector is orthogonal to the reference
itself: .#bluewhale means "the bluewhale attribute of the flake in the current
directory," which is why nixos-rebuild --flake .#bluewhale works. The github: fetcher is
not just shorthand for git+https://github.com/... — it downloads a tarball snapshot via
GitHub's API rather than doing a full git clone, so it's markedly faster and doesn't need
git installed for that input. And path: deliberately bypasses git, which matters for the
gotcha below.
Inspecting a flake
Three subcommands answer almost every "what is this flake, actually?" question.
nix flake show prints the tree of outputs a flake exposes — the quickest way to
confirm an attribute exists and is spelled the way you think:
$ nix flake show
git+file:///home/jo/nixos-config
└───nixosConfigurations
├───bluewhale: NixOS configuration
└───narwhal: NixOS configuration
nix flake metadata reports the inputs side: the resolved lock, the store path the
flake was copied to, the last-modified time, and — crucially — the full input dependency
tree. This is where you verify that a follows actually collapsed the duplicates you
expected:
$ nix flake metadata
Resolved URL: git+file:///home/jo/nixos-config
Locked URL: git+file:///home/jo/nixos-config?rev=...
Inputs:
├───home-manager: github:nix-community/home-manager/...
│ └───nixpkgs follows input 'nixpkgs'
└───nixpkgs: github:NixOS/nixpkgs/...
The line nixpkgs follows input 'nixpkgs' is the proof your dedup worked — the dependency's
nixpkgs is a pointer, not a second copy.
nix flake check evaluates the flake and runs whatever checks it defines, confirming
the outputs at least evaluate and build their derivations without error. It's the natural
pre-commit and CI gate:
# in a CI job
nix flake check
nix build .#nixosConfigurations.bluewhale.config.system.build.toplevel
The first line catches structural breakage (a typo'd option, a module that won't evaluate);
the second actually builds the system closure, catching real build failures before they
reach a nixos-rebuild. Run these on every push and a broken config never makes it to a
machine.
The git-tracked-files gotcha (recap) and --impure
We met this in the first-flake article, and it stays true forever, so a quick
recap: when a flake lives in a git repo, Nix copies only git-tracked files into the store
before evaluating. A new file you haven't git added is invisible — the build behaves as
if it doesn't exist, producing baffling "path does not exist" errors for a file you're
staring at. The fix is always git add first. (This is also why a path:./sub reference,
which bypasses git, sometimes sees files a git+file reference doesn't.)
The related escape hatch is --impure. Flakes are pure by default: evaluation cannot read
environment variables, absolute paths outside the flake, or the system's current state.
Occasionally you genuinely need one of those — reading $HOME, or builtins.currentSystem,
or a file outside the tree — and passing --impure lifts the restriction for that command:
nix build --impure .#something-that-reads-the-environment
Reach for --impure sparingly and consciously. Every impure input is a way for "works on my
machine" to creep back in — the whole point of flakes is that the answer doesn't depend on
your environment. If you find yourself always needing it, that's usually a smell that a value
should be threaded in explicitly (via specialArgs, below) rather than read from the ambient
world.
Structuring a real configuration
A one-host flake.nix is fine to learn on; a real setup manages several machines and shares
code between them. The shape scales cleanly:
outputs = { self, nixpkgs, ... }@inputs: {
nixosConfigurations = {
bluewhale = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
specialArgs = { inherit inputs; };
modules = [
./hosts/bluewhale
./modules/common.nix
./modules/desktop.nix
];
};
narwhal = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
specialArgs = { inherit inputs; };
modules = [
./hosts/narwhal
./modules/common.nix
./modules/server.nix
];
};
};
};
The idea: a modules/ directory of reusable modules (common.nix for what every host
shares, desktop.nix / server.nix for role-specific bits) and a hosts/ directory for
per-machine specifics. Each nixosSystem just picks the modules that host needs. Adding a
laptop is a new hosts/ entry plus a short module list — no copy-paste of the shared parts.
specialArgs is how you get extra values into your modules' function arguments. By
default a module receives { config, pkgs, lib, ... }; specialArgs = { inherit inputs; }
adds inputs so any module can write { config, pkgs, inputs, ... }: and reach your flake
inputs directly (handy for pulling a package from a non-nixpkgs input). Home-manager has the
exact analogue, extraSpecialArgs, for the arguments passed to its modules — same idea,
different module tree.
When the outputs block gets busy
Once you're producing nixosConfigurations and packages
and dev shells for several systems, hand-writing the outputs
function gets repetitive. Two community libraries tame it:
flake-utils (the classic eachDefaultSystem helper that
stamps out per-system outputs) and flake-parts (a module-system-based
framework for structuring large flakes). Neither is required — reach for them when the
boilerplate, not the concepts, is the problem.
Two cross-cutting rules for real configs. Keep secrets out of the store: everything in a
flake is world-readable in /nix/store, so passwords and keys go through a secrets manager,
not a string in a module — see secrets with sops-nix. And per-project
tooling belongs in per-project dev shells, not your system config: a devShell output in
each project's own flake keeps compilers and language servers scoped to where they're used —
see dev shells.
Binary caches and substituters
You almost never build nixpkgs from source, and that's thanks to substituters (a.k.a.
binary caches). Because a store path's hash is a fingerprint of all its inputs (the
input-addressing idea from the mental model), Nix can ask a cache "do you
already have the path with this hash?" If yes, it downloads the finished build instead of
compiling it. The default cache.nixos.org is why installing a huge package set takes
seconds, not hours.
You configure caches declaratively in your NixOS config:
nix.settings = {
substituters = [
"https://cache.nixos.org"
"https://nix-community.cachix.org"
];
trusted-public-keys = [
"cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
"nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs="
];
};
Each substituter must be paired with its public key in trusted-public-keys. Nix
verifies that every substituted path is signed by a trusted key before it will use it — the
signature is what lets you trust a build you didn't perform yourself. A cache URL with no
matching key is simply ignored.
Cachix in one paragraph
Cachix is a hosted binary-cache service: you build your own or a
community project's packages once, push them to a named cache
(you.cachix.org), and everyone who trusts that cache's key downloads the
prebuilt results instead of rebuilding. It's the standard way community flakes ship
binaries for packages that aren't in nixpkgs — add the substituter and key above and the
build that would have taken an hour becomes a download. Many CI setups push to Cachix so
that developer machines never rebuild what CI already built.
Performance and the classic gotchas
A grab-bag of the traps that cost people an afternoon exactly once.
Import-from-derivation (IFD) makes eval slow. IFD is when evaluation has to wait for a
build to finish — you import a file, or read a path, that is itself the output of a
derivation, so Nix must stop evaluating, run a build, and resume. It works, but it
serializes eval behind builds and can make nix flake check or nixos-rebuild crawl.
Prefer generating such files ahead of time and committing them, or use nixpkgs helpers
designed to avoid IFD, rather than reaching into build outputs mid-evaluation.
The "dirty git tree" warning. When you build a flake in a git repo with uncommitted
changes, Nix prints Git tree '...' is dirty and stamps the build with a "dirty" revision.
It's a warning, not an error — the build uses your working-tree contents (tracked files
only, per the gotcha above) — but it's telling you the exact inputs aren't recorded anywhere.
Commit before you build anything you want to be able to reproduce.
Stale locks and --refresh. A flake reference like a branch is resolved once and then
cached; Nix won't re-hit the network on every command. If you know a branch has moved and you
want Nix to re-check it (rather than trusting its cached resolution), pass --refresh. This
is different from nix flake update: update rewrites the lock to a new revision, while
--refresh just invalidates Nix's cached view of a reference for the current command.
Registry shortcuts. The flake registry maps short names to references, which is why
nix run nixpkgs#hello works without a full URL — nixpkgs is a registry alias. Inspect and
tweak it with nix registry list and nix registry add. Pinning your registry's nixpkgs
to the same revision your system uses avoids the surprise of nix shell nixpkgs#foo pulling
a different nixpkgs than your configuration.
Disk fills up. Every generation and every old build sits in the store until you collect
it. nix store gc deletes store paths that nothing currently references; combined with
pruning old generations (covered in generations & rollback), it's
how you reclaim the gigabytes that flakes and frequent rebuilds accumulate. Set
nix.gc.automatic = true; to let NixOS run it on a schedule.
Enabling flakes. And the one that gates everything: flakes are still an experimental
feature, so nix.settings.experimental-features = [ "nix-command" "flakes" ]; must be in
your config (with the transitional nix.conf line to bootstrap it) — the full story is in
the first-flake article, and the "why still experimental" background is in the
mental model.
Key Takeaways
- Lock hygiene:
nix flake updatebumps everything;nix flake update nixpkgs(or, on older Nix,nix flake lock --update-input nixpkgs) bumps one input;--override-inputtests a revision without touching the lock. Always commitflake.lock. - Dedupe with
follows:inputs.foo.inputs.nixpkgs.follows = "nixpkgs";collapses a dependency's nixpkgs into yours — one fetch, one eval target, one reality. Verify withnix flake metadata. - Reference grammar:
github:owner/repo/ref,git+https://…?ref=…&rev=…,path:./sub,tarball+https://…, plus?dir=,?submodules=1, and the#attrselector. - Inspect:
nix flake show(outputs),nix flake metadata(inputs/lock tree),nix flake check(evaluates + builds — a great CI gate). - Gotchas: flakes see only git-tracked files (
git addfirst);--impurelifts purity but invites drift — use it sparingly. - Structure: share modules across hosts, thread values in with
specialArgs/extraSpecialArgs, reach for flake-parts/flake-utils only when boilerplate hurts; keep secrets out of the store and dev tooling in per-project shells. - Caches: pair each
substitutersURL with itstrusted-public-keysentry; Cachix hosts prebuilt binaries so builds become downloads. - Performance: avoid IFD, commit before building (the "dirty tree" warning), use
--refreshfor stale references, andnix store gcto reclaim disk.
And that's the series. Look back at the arc: we started with the mental model — a system is a description, that description builds immutable store paths, and generations let you move between whole systems atomically. We learned just enough of the Nix language to read a config without flinching, then turned it into a real flake-based system, grew it with the module system, and made upgrades safe with generations and rollback. We went deeper — exploring nixpkgs in the repl, bending packages with overlays and overrides, writing our own derivations and local packages, spinning up dev shells, and managing secrets. Then we learned to debug builds when they go wrong, and finished with the tips on this page.
That's a complete loop: you can describe a machine, package the software it runs, reproduce it anywhere, and repair it when it breaks. The rest is just more of the same ideas applied to bigger fleets and stranger requirements — more hosts, more inputs, more modules, all resting on the same handful of guarantees you now understand from the ground up. Go build something, break it, roll it back, and enjoy the fact that "break it" stopped being scary a long time ago.