8. Overlays & Overrides

Bend nixpkgs to your needs without forking a 100,000-package repo

Imagine you own one enormous, beautifully organized cookbook — tens of thousands of recipes, cross-referencing each other, all tested to work together. One evening you want the lasagna, but with a little more garlic and a gluten-free pasta. You could photocopy the entire cookbook, edit your copy, and cook from that forever after — but now you own a fork of the cookbook, and every time the original gets a correction you have to re-apply your garlic edit by hand. The saner move is to slip a sticky note onto the lasagna page: "when you make this, use twice the garlic and the gluten-free noodles." The original book is untouched; your note travels with it; and everything that references the lasagna recipe now transparently gets your version.

That sticky note is exactly what overrides and overlays are for nixpkgs. Nixpkgs is the cookbook: a giant collection of package recipes (derivations) that all reference each other. Sooner or later you'll need one package built slightly differently — a newer version, a patch, a build flag turned on, or an entirely new package that lives alongside the rest. This article is about doing that surgically, without forking nixpkgs and without losing reproducibility.

The whole idea in one paragraph

A package in nixpkgs is produced by a function, and that function's output is a derivation. Overrides reach into a single package and change either its inputs (.override — the arguments to that function) or its derivation attributes (.overrideAttrs — the source, patches, build steps). Overlays are the mechanism that makes such a change apply everywhere: an overlay is a function final: prev: { … } that layers your modified packages on top of the base set, so that everything which depends on the package you changed picks up your version too. Overrides are the sticky note; overlays are how the note gets stapled into every copy of the book.

The problem: I need it slightly different

You're building a system and you hit one of these:

  • The version in your nixpkgs is 1.4.2, but you need 1.5.0 (or, more often, an older version because 1.5.0 regressed something).
  • Upstream has a bug and you have a one-line patch that fixes it, but it hasn't landed in a release yet.
  • The package is built with a feature disabled — no GUI, no CUDA, no JACK support — and you want it flipped on.
  • You wrote a small tool and want it available as pkgs.mytool, referenced the same way as any other package, including by other packages.

The tempting-but-wrong move is to clone nixpkgs, edit the recipe, and point your flake at your fork. That works exactly once. Then nixpkgs moves on, you rebase, your edits conflict, and you've signed up to maintain a fork of one of the largest repositories on GitHub to change a single build flag. Overrides and overlays exist so you never have to.

Forking nixpkgs

Copy the whole repo, edit the recipe in place, track your fork forever. Every upstream update is a merge conflict waiting to happen. You now maintain nixpkgs.

Overriding

Keep upstream nixpkgs pinned in your flake.lock untouched, and describe your change as a small function applied on top. Upstream updates flow through; your change re-applies automatically against the new base.

Two kinds of override: inputs vs. attributes

This is the distinction that trips everyone up, so we'll make it crisp. A nixpkgs package is the result of calling a function — the recipe — with a set of arguments — its inputs. That function, inside, calls stdenv.mkDerivation with a set of attributes — the source, patches, build phases, and so on. There are therefore two different places you can intervene, and two different tools:

.override vs .overrideAttrs, in one line each

.override { … } changes the arguments passed into the package's function — the knobs the packager exposed (withGui, enableFoo, a dependency to swap). It re-runs the recipe with new inputs.
.overrideAttrs (old: { … }) changes the attributes passed to mkDerivation inside the recipe — the version, src, patches, postInstall, and so on. It edits the recipe's output, not its inputs.

.override — turn the knobs the packager exposed

Look at the head of a typical nixpkgs recipe. It's a function whose arguments are its inputs — dependencies and boolean feature flags:

The shape of a package function

{ lib, stdenv, fetchurl, pkg-config, gtk3
, withGui ? true          # a feature flag the packager exposed
, ffmpeg ? null           # an optional dependency
}:
stdenv.mkDerivation (finalAttrs: {
  pname = "coolapp";
  version = "1.4.2";
  # …
})

Those named arguments — withGui, ffmpeg, and the dependencies themselves — are exactly what .override lets you change. You hand it a set of new argument values, and nixpkgs re-invokes the same function with them:

Flipping a build flag and swapping a dependency

# Build coolapp headless, and against a specific ffmpeg
pkgs.coolapp.override {
  withGui = false;
  ffmpeg  = pkgs.ffmpeg-full;
}

You can only override arguments the function actually has. If a package doesn't take a withGui argument, .override { withGui = false; } is an error — there's no knob to turn. (How do you discover the knobs? The Nix repl is the fastest way: :e pkgs.coolapp opens the recipe, or you inspect pkgs.coolapp.override.__functionArgs to list the accepted arguments.)

If you need the previous value of an argument to compute the new one, .override also accepts a function:

Extending an argument instead of replacing it

pkgs.coolapp.override (prev: {
  extraPlugins = prev.extraPlugins ++ [ pkgs.myPlugin ];
})

.overrideAttrs — edit the recipe's derivation

.override can't help you bump a version or add a patch, because version and patches aren't arguments to the function — they're attributes the function passes to stdenv.mkDerivation. That's the job of .overrideAttrs. You give it a function from the old attribute set to a set of changes, and it produces a new derivation with those attributes replaced or added:

Bumping a version (and its source hash)

pkgs.coolapp.overrideAttrs (old: rec {
  version = "1.5.0";
  src = pkgs.fetchurl {
    url = "https://example.com/coolapp-${version}.tar.gz";
    hash = "sha256-AAAA…";   # the new tarball's hash
  };
})

Note the old: argument — it's the attribute set originally passed to mkDerivation, so you can build your change from the original rather than rewriting it. That's essential for the two most common surgical edits: adding a patch and appending a build step.

Adding a patch and a post-install step

pkgs.coolapp.overrideAttrs (old: {
  # append to the existing patch list, don't clobber it
  patches = (old.patches or []) ++ [ ./fix-crash.patch ];
  # tack on an extra step after the normal install
  postInstall = (old.postInstall or "") + ''
    ln -s $out/bin/coolapp $out/bin/ca
  '';
})

The (old.patches or []) idiom matters: patches might not be set on the original at all, so you default it to an empty list before appending. Blindly writing patches = [ ./fix.patch ]; would discard any patches nixpkgs already applies — a classic way to silently un-fix a package. The same care applies to postInstall, buildInputs, nativeBuildInputs, and any other list- or string-valued attribute: append, don't replace, unless you truly mean to.

How to decide which one to use

Ask: is the thing I want to change an argument to the recipe, or an attribute of the derivation? A feature flag or a dependency the packager parameterized → .override. The version, source, patches, or a build/install phase → .overrideAttrs. When in doubt, open the recipe with :e in the repl and look at whether the thing sits in the function's argument list (top) or inside the mkDerivation attribute set (body).

A subtle but useful point: the two compose. Because .override re-runs the function and .overrideAttrs edits the result, you can chain them — pkgs.coolapp.override { withGui = false; }.overrideAttrs (old: { … }) — first re-invoking the recipe with new inputs, then editing the derivation it produces.

A note on overrideDerivation and overrideAttrs arg forms

You may see .overrideDerivation in older code. It operates on the raw Nix derivation after mkDerivation has run, so attributes that mkDerivation itself interprets (like separateDebugInfo) won't behave as expected. Prefer .overrideAttrs. Modern nixpkgs also supports a two-argument form, .overrideAttrs (finalAttrs: prevAttrs: { … }), where finalAttrs lets attributes refer to the final resolved values (handy when version feeds into src without a rec). The single-argument (old: …) / (prev: …) form is what you'll use most.

Overlays: make a change apply everywhere

Overrides give you a modified package as a value. That's enough if you only ever reference it in one place — environment.systemPackages = [ (pkgs.coolapp.override { … }) ];. But it has two limits. First, it's local: if another package depends on coolapp, it still gets the original, not yours. Second, it doesn't help you add a brand-new package to pkgs. Overlays solve both.

An overlay is a function of two arguments that returns an attribute set of packages to add or replace:

The canonical overlay shape

final: prev: {
  coolapp = prev.coolapp.overrideAttrs (old: {
    patches = (old.patches or []) ++ [ ./fix-crash.patch ];
  });
  mytool = final.callPackage ./mytool { };   # a brand-new package
}

The two arguments are the crux of overlays, and getting them right is the difference between a working config and an "infinite recursion" error. They are two different views of the package set:

  • prev (older code calls it super) is the package set as it was before this overlay ran — the previous stage. Use prev when you want to refer to the original thing you're modifying: prev.coolapp is the coolapp you're about to override.
  • final (older code calls it self) is the package set as it will be after all overlays have been applied — the finished result. Use final when you want to reference other packages, so you get their final, possibly-overlaid versions as dependencies.

The one rule that avoids infinite recursion

Base your override on prev; reference dependencies through final. Writing coolapp = prev.coolapp.overrideAttrs … is fine — you're building your new coolapp from the old one. Writing coolapp = final.coolapp.overrideAttrs … is a trap: final.coolapp is the thing you're defining, so its definition depends on itself, and Nix loops forever. Conversely, a package's dependencies should come from final, so that if some other overlay also modifies a dependency, your package builds against that final version too.

Why is final even safe to use, given that it's "the finished set" and we're still in the middle of finishing it? Because Nix is lazy and the package set is a fixpoint, exactly like the config fixpoint from the module system article. final is the whole package set defined recursively in terms of itself. Referring to final.ffmpeg from inside your coolapp definition doesn't ask for "the entire finished set" — it asks for one field, ffmpeg, which Nix computes on demand. That resolves cleanly. The only thing that doesn't resolve is when a field's value depends on its own final value — coolapp defined via final.coolapp — which is a genuine loop. Hence the rule: prev for the thing itself, final for its neighbours.

The overlay pipeline: prev looks left, final looks right base pkgs nixpkgs as imported overlay 1 final: prev: { … } overlay 2 final: prev: { … } final pkgs used to build prev = base prev = after overlay 1 final = the finished set on the right (every overlay sees the same final) Each overlay's prev is the stage immediately to its left; every overlay's final is the single finished set on the right.

Applying overlays

An overlay is just a function until you tell a package set to use it. There are two places you do that.

Inside a NixOS module, set the nixpkgs.overlays option. The module system merges this list like any other, and the resulting overlaid pkgs is what the rest of your configuration sees:

Applying overlays in a module

{ ... }:
{
  nixpkgs.overlays = [
    (final: prev: {
      coolapp = prev.coolapp.overrideAttrs (old: {
        patches = (old.patches or []) ++ [ ./fix-crash.patch ];
      });
    })
    (import ./overlays/my-tools.nix)   # an overlay stored in its own file
  ];
}

Or when you import nixpkgs yourself, pass overlays in the attribute set. This is what you do outside the NixOS module system — in a nix-shell, a standalone script, or a flake's pkgs binding:

Importing nixpkgs with overlays

let
  pkgs = import nixpkgs {
    system = "x86_64-linux";
    overlays = [ myOverlay otherOverlay ];
  };
in
  pkgs.coolapp   # already carries every overlay's changes

Overlays in a flake

Flakes standardize how you both expose an overlay to others and consume one from another flake. The convention is an overlays.default output:

Exposing and consuming an overlay in flake.nix

{
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
  # someone else's flake that exports overlays.default
  inputs.foo.url = "github:someone/foo";
  outputs = { self, nixpkgs, foo }: {
    # EXPOSE our own overlay for others to use
    overlays.default = final: prev: {
      mytool = final.callPackage ./mytool { };
    };
    nixosConfigurations.bluewhale = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      modules = [
        ./configuration.nix
        {
          # CONSUME both our overlay and foo's
          nixpkgs.overlays = [
            self.overlays.default
            foo.overlays.default
          ];
        }
      ];
    };
  };
}

Because your overlay is a plain output, another person adds your packages to their system by pinning your flake as an input and dropping yourflake.overlays.default into their own nixpkgs.overlays list. This is the packaging analogue of the nixosModules outputs from the module system article — a small, well-defined seam other flakes plug into.

Composition and ordering

Overlays apply left to right, and each one sees the result of everything before it as its prev. This is the source of both their power and their footguns.

  1. Nix starts from the base package set (your imported nixpkgs).
  2. It applies the first overlay: its prev is the base set.
  3. It applies the second overlay: its prev is the base set with overlay 1 already applied.
  4. …and so on, each overlay's prev being the accumulated result so far.
  5. Every overlay's final, by contrast, is the same fully-overlaid set — the result after the last overlay. That's the fixpoint.

Order therefore matters whenever two overlays touch the same package. If overlay A bumps coolapp to 1.5.0 and overlay B, later, appends a patch to prev.coolapp, then B's patch is written against the 1.5.0 source it's actually applied to — good. Swap the order and B appends its patch to 1.4.2 first; A's later .overrideAttrs (old: { version; src; }) merges over old, so B's patches entry is retained (append doesn't get thrown away — that's the same "overrideAttrs merges over old" principle we relied on above). The subtler failure is that the patch was written for 1.4.2 but now has to apply against A's new 1.5.0 src, so it may simply fail to apply in the patch phase. The list order encodes "who gets the last word."

Here are the failure modes to keep in your head:

Common overlay mistakes

  • Infinite recursion: using final.coolapp to define coolapp. Base the definition on prev instead.
  • Overriding the wrong layer: a later overlay basing on prev silently discards an earlier overlay's change to the same attribute (e.g. replacing patches instead of appending).
  • Wrong tool: reaching for .override to change a version (that's .overrideAttrs), or .overrideAttrs to flip a flag the packager exposed (that's .override).
  • Mass rebuilds: overriding a package deep in the dependency graph — stdenv, openssl, glibc — forces everything downstream to rebuild from source, because you changed an input and thus every dependent hash.

Habits that avoid them

  • prev for the thing you're changing; final for dependencies you reference.
  • Always append to list/string attributes: (old.patches or []) ++ [ … ].
  • Match the tool to the target: argument → .override; attribute → .overrideAttrs.
  • Override as high up the tree as possible; expect a rebuild storm if you touch a low-level dependency, and lean on a binary cache when you can't avoid it.

That last point deserves emphasis because it surprises people. Nixpkgs is input-addressed: change an input to openssl and every package that links openssl now has a different hash and must be rebuilt, since none of the cached binaries match your modified inputs anymore. Overriding a leaf package (an app nothing else depends on) is cheap; overriding something near the root of the dependency graph can mean recompiling thousands of packages. That's not a bug — it's the reproducibility guarantee doing its job — but it's worth knowing before you .overrideAttrs your libc at 11pm.

Watch prev and final resolve

Ordering and the prev/final distinction are much easier to feel than to read about. This demo starts from a tiny base package set and lets you switch a handful of small overlays on and off, reorder them, and see what pkgs.foo resolves to at the end — including a warning when an ordering makes an overlay see the wrong (pre- or post-overlay) value.

Base package set

Overlays — applied top to bottom (top runs first)

Resolved result

When to reach for which

Three tools, a rough decision order from lightest to heaviest:

Override → overlay → local package

  1. A one-off .override / .overrideAttrs when you need a tweaked package in exactly one place and nothing else depends on the change. Inline it right where you use it: systemPackages = [ (pkgs.coolapp.override { … }) ];. Smallest blast radius, no ceremony.
  2. An overlay when the change must apply everywhere — because other packages depend on the one you're changing, or because you're adding a package to pkgs that other code (or other overlays) will reference. Overlays are also the right home for a change you want to share across machines or export from a flake.
  3. A full local package when you're not tweaking an existing recipe but writing a new one from scratch — your own software, or something not in nixpkgs at all. That's a derivation of its own, usually wired in with callPackage (often through an overlay so it lands in pkgs).

The boundary between the second and third is soft: adding mytool = final.callPackage ./mytool { } in an overlay is introducing a local package — the overlay is just the delivery mechanism that puts it in pkgs. The next two articles pick up exactly here. Packaging & derivations teaches you to write the ./mytool recipe itself — stdenv.mkDerivation, sources, phases, and the finalAttrs pattern you saw in the recipe head above. Local packages then covers organizing your own packages and wiring them into a flake cleanly, overlay and all.

Key Takeaways

  • Never fork nixpkgs to change one package. Keep upstream pinned and describe your change as an override or overlay applied on top, so upstream updates keep flowing.
  • .override { … } changes a package's inputs — the arguments the recipe's function exposes (feature flags, dependencies). It re-runs the recipe with new arguments.
  • .overrideAttrs (old: { … }) changes the derivation attributes — version, src, patches, postInstall. Build from old and append to lists ((old.patches or []) ++ …) so you don't discard what nixpkgs already set.
  • An overlay is final: prev: { … } that layers modified or new packages onto the set. Use prev to base your change on the original; use final to reference other (possibly-overlaid) packages. Using final to define the very thing you're overriding causes infinite recursion.
  • Apply overlays via nixpkgs.overlays = [ … ] in a module or import nixpkgs { overlays = [ … ]; } directly. In flakes, expose overlays.default and consume another flake's the same way.
  • Overlays compose left-to-right: each sees prior overlays in its prev, while every overlay shares the same final fixpoint. Watch for infinite recursion, discarded changes from wrong ordering, the wrong override tool, and mass rebuilds when you touch a low-level dependency.
  • Escalate deliberately: one-off override for a local tweak, an overlay when it must apply everywhere or add to pkgs, a full local package when you're writing a new recipe.

You can now bend any package in nixpkgs to your needs — a new version, a patch, a flag, or a wholesale addition — without touching upstream. So far you've only edited existing recipes, though. Next we go one level down and write a recipe from scratch: how packaging & derivations turn source code into a store path with stdenv.mkDerivation, the build phases, and the finalAttrs pattern you glimpsed here.