A shell.nix that imports <nixpkgs> uses the version of the channel
installed on your machine. Nothing guarantees that your colleague has the
same one. The result: Python 3.12.14 on your side, Python 3.12.8 on theirs.
This guide shows how to modularise your Nix files and freeze versions
so that everyone works with exactly the same packages. The outputs were
captured on Nix 2.35.2.
What you will learn
- Split the configuration into several files with
import - Pass arguments between files with
inherit - Merge configurations with the
//operator - Freeze a nixpkgs version with
fetchTarballand a hash - Find the sha256 of an archive with
nix-prefetch-url - Understand why flakes were created
In what context?
As soon as your Nix project grows beyond a few lines, you run into these situations, which call either for modularisation or for pinning:
- your
shell.nixmixes configuration, Python packages, CLI tools and environment variables in a single file that grows fast, - you want to reuse the same list of Python packages in several projects without copy-pasting,
- two developers get different results because their Nix channels do not point to the same nixpkgs version,
- you need a precise version of a tool to reproduce a bug reported in CI.
Modularisation and pinning solve each of these problems.
Split the configuration with import
import loads and evaluates a .nix file. If the file contains an
attrset, it returns that attrset. If the file contains a function, it
returns that function (which you then have to call).
Extract the variables into config.nix
The first extracted file only holds values: name, version, debug mode and port. It is the only place to change to adapt the project.
{ projectName = "mon-api"; projectVersion = "2.0.0"; debugMode = true; listenPort = 5000;}This file is a simple attrset, import ./config.nix directly returns
{ projectName = "mon-api"; ... }, with no argument to pass and no
function to call.
Extract the Python packages into python-packages.nix
The second file is richer: it builds the Python environment and only adds
the development tools when debugMode is on. It therefore needs pkgs and
the configuration.
{ pkgs, config }:
let basePackages = ps: [ ps.requests ps.flask ];
devPackages = ps: [ ps.pytest ps.black ];inpkgs.python312.withPackages (ps: basePackages ps ++ (if config.debugMode then devPackages ps else []))This file is a function that expects pkgs and config. It must be
called with the arguments: import ./python-packages.nix { inherit pkgs config; }.
Assemble in shell.nix
The entry point imports both files and composes the final environment.
Note the call of python-packages.nix with inherit pkgs config: it is what
passes the two expected arguments.
{ pkgs ? import <nixpkgs> {} }:
let config = import ./config.nix; pythonEnv = import ./python-packages.nix { inherit pkgs config; };
debugTools = if config.debugMode then with pkgs; [ htop ncdu ] else [];inpkgs.mkShell { name = "${config.projectName}-dev";
packages = with pkgs; [ pythonEnv git ripgrep ] ++ debugTools;
PROJECT_NAME = config.projectName; PROJECT_VERSION = config.projectVersion; LISTEN_PORT = toString config.listenPort;}nix-shell --run "echo \$PROJECT_NAME \$PROJECT_VERSION \$LISTEN_PORT && which htop"mon-api 2.0.0 5000/nix/store/w31kqb23ydg3fli2b8dsy0gl0ily15bm-htop-3.5.3/bin/htopThe configuration is centralised in config.nix, a single place to change
to rename the project, change the version or the debug mode.
Merge configurations with //
The // operator merges two attrsets. The keys on the right-hand side
overwrite those on the left. It is ideal for an override system:
defaults.nix, default values
This file carries the versioned configuration of the project, the one the whole team shares. It must stay exhaustive: every key likely to be overridden must appear in it with a safe value, here debugMode = false. A key missing from defaults.nix but consumed elsewhere will raise a missing attribute error as soon as a developer works without overrides.nix.
{ projectName = "mon-api"; projectVersion = "2.0.0"; debugMode = false; listenPort = 5000;}overrides.nix, local overrides
This second file only holds the differences from the default values, never the complete configuration. Two keys are enough here, the others are inherited as they are. The merge is shallow: // replaces the value of a key as a whole, it does not recursively merge two nested attrsets. If debugMode were an attrset rather than a boolean, redefining a single one of its sub-keys would erase all the others.
{ debugMode = true; listenPort = 8080;}Merge in shell.nix
The merge fits in one line: defaults // overrides. The comments show for
each key whether it comes from the overrides or from the default
values.
let defaults = import ./defaults.nix; overrides = import ./overrides.nix; config = defaults // overrides;in# config.debugMode = true (overridden)# config.listenPort = 8080 (overridden)# config.projectName = "mon-api" (inherited)nix-shell --run "echo \$LISTEN_PORT"8080The port is indeed 8080 (overrides) instead of 5000 (defaults), and
projectName stays "mon-api" because it is not overridden: the merge
applied the priority of the right-hand side.
Use case: multiple environments
Create one file per environment: each one only carries its differences,
and defaults.nix remains the common base.
mon-projet/├── shell.nix├── defaults.nix├── overrides-dev.nix # debugMode=true, port 8080├── overrides-staging.nix # debugMode=false, port 5000└── python-packages.nixSelect the environment from shell.nix:
config = defaults // (import ./overrides-dev.nix);Create reusable utility functions
When some logic comes back in several projects, extract it into a dedicated file, as a function:
config: { PROJECT_NAME = config.projectName; PROJECT_VERSION = config.projectVersion; LISTEN_PORT = toString config.listenPort; DEBUG = if config.debugMode then "1" else "0";}let config = import ./config.nix; mkEnvVars = import ./lib/mk-env-vars.nix; envVars = mkEnvVars config;inpkgs.mkShell ({ packages = [ ... ];} // envVars)The // operator merges the mkShell attrset with the environment
variables, which are automatically exported.
Why freeze the nixpkgs version
By default, import <nixpkgs> {} uses the system channel. This channel
changes at every update. The consequence, measured between the
nixpkgs-unstable of 29 September 2026 and the nixos-24.11 branch:
| Machine A (up-to-date channel) | Machine B (old channel) |
|---|---|
| Python 3.12.14 | Python 3.12.8 |
| git 2.55.0 | git 2.47.2 |
A few months of gap between channels produce visible differences. For a reproducible environment, you have to freeze the source.
Method 1: fetchTarball with a sha256
Replace import <nixpkgs> {} with an import of a fixed archive, along with
its hash: Nix downloads the archive, checks the hash, then evaluates that
version of nixpkgs.
{ pkgs ? import (fetchTarball { url = "https://github.com/NixOS/nixpkgs/archive/nixos-24.11.tar.gz"; sha256 = "sha256:1s2gr5rcyqvpr58vxdcb095mdhblij9bfzaximrva2243aal3dgx"; }) {}}:
pkgs.mkShell { packages = [ pkgs.python312 pkgs.git ];}Now, whatever channel is installed on the machine:
nix-shell --run "python3 --version && git --version"Python 3.12.8git version 2.47.2The versions obtained are those of the downloaded archive, no longer those of the local channel.
Method 2: pin to a precise commit
For even more precision, use a specific nixpkgs commit, with the
hash of its archive computed by nix-prefetch-url --unpack:
{ pkgs ? import (fetchTarball { url = "https://github.com/NixOS/nixpkgs/archive/4c1018dae018162ec878d42fec712642d214fdfa.tar.gz"; sha256 = "sha256:18ggs7jwmpi58k7xza4axy3cjs17c596ihq5y70h6sryz2hypgba"; }) {}}:
pkgs.mkShell { packages = [ pkgs.python312 ];}A commit never changes, it is the strongest guarantee of reproducibility without flakes.
Find the sha256 of a nixpkgs archive
Two methods give the same fingerprint, in two different encodings
that fetchTarball accepts equally.
Method 1: let Nix compute the hash
Put an empty sha256 and run nix-shell. The error shows the right
hash, in SRI format (sha256- followed by base64):
sha256 = ""; # ← intentionally emptywarning: found empty hash, assuming 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='...error: NAR hash mismatch in input 'https://github.com/NixOS/nixpkgs/archive/nixos-24.11.tar.gz?narHash=sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%3D', expected 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' but got 'sha256-/bVBlRpECLVzjV19t5KMdMFWSwKLtb5RyXdjz3LJT+g='Copy the value after but got into your file: sha256 = "sha256-/bVBlRpECLVzjV19t5KMdMFWSwKLtb5RyXdjz3LJT+g="; works as is.
Method 2: nix-prefetch-url
The command downloads and unpacks the archive, adds it to the store and prints its hash:
nix-prefetch-url --unpack https://github.com/NixOS/nixpkgs/archive/nixos-24.11.tar.gzpath is '/nix/store/yb6a9i6qlzvhdz08d82ay7107z8qrnb3-nixos-24.11.tar.gz'1s2gr5rcyqvpr58vxdcb095mdhblij9bfzaximrva2243aal3dgxPrefix it with sha256: in the Nix file.
Find a package in a precise version
Check the version in a given nixpkgs
nix eval queries the package tree without building or downloading anything: the answer comes in a few seconds, which makes it the check to run before freezing a hash. The --impure flag is essential here, because <nixpkgs> is resolved through the NIX_PATH variable of your machine, an outside input that pure mode refuses on principle. The returned value is therefore that of your channel, not that of the archive you are about to freeze: to query a precise version, replace <nixpkgs> with the same fetchTarball as in your shell.nix.
nix eval --impure --expr '(import <nixpkgs> {}).python312.version'"3.12.14"Nixhub.io: search by version
The Nixhub.io site lets you find which nixpkgs version contains a precise version of a package. If you need exactly Python 3.12.8, Nixhub tells you which commit or branch to use.
Recommended structure for a multi-file project
The files seen in this guide are organised by responsibility: the configuration, the packages, the utilities, and the entry point that assembles them.
mon-projet/├── shell.nix # entry point, imports the modules├── defaults.nix # default configuration├── overrides.nix # local overrides (gitignored if needed)├── python-packages.nix # parameterised Python packages└── lib/ └── mk-env-vars.nix # utility functionsPrinciples:
- One file per responsibility (configuration, packages, utilities)
defaults.nixversioned,overrides.nixoptional and local- Utility functions in
lib/ - Pinning in
shell.nix(or in a dedicatednixpkgs.nix)
Limits of classic pinning: why flakes exist
Pinning with fetchTarball works, but has drawbacks that you pay for at
every update and as soon as several sources have to be combined:
| Limit | Impact |
|---|---|
| Manual hash | You have to look up and paste the sha256 at every update |
| No shared lock | Every developer must have the right hash in the file |
| Tedious updates | Changing version = edit the URL + recompute the hash |
| No composition | Combining several sources (overlay, modules) is complex |
Flakes solve these problems with:
- an automatic, versionable
flake.lockfile, - a
nix flake updatecommand to update, - native composition of several inputs.
Classic pinning remains perfectly valid for simple projects or environments without flakes. For team projects, flakes are the recommended solution.
Troubleshooting
Two families of errors stand out in this table, and they are not diagnosed the same way. The first three rows concern the source of the packages: evaluation has not even started. The next three concern the Nix language itself, and the error message then quotes the faulty file and line. A useful reflex in both cases: run again with nix-shell --show-trace, which unfolds the evaluation stack and points at the imported file that is really responsible, often different from the one you were editing.
| Symptom | Likely cause | Solution |
|---|---|---|
hash mismatch | Wrong sha256 or modified archive | Recompute with nix-prefetch-url --unpack |
cannot look up '<nixpkgs>' in pure evaluation mode | nix eval or flake in pure mode | Add --impure or freeze with fetchTarball |
file 'nixpkgs' was not found in the Nix search path | No channel configured | nix-channel --update, or freeze with fetchTarball |
import ./file.nix fails | Wrong relative path | Check that the file exists in the right place |
Missing argument in import | File = function not called | Pass the arguments: import ./f.nix { inherit pkgs; } |
Attribute missing after // | Key not defined in defaults | Check both attrsets before merging |
Key points
import ./file.nixloads a Nix file, you can separate configuration, packages and utilities.- If the file is a function, it must be called with its arguments:
import ./f.nix { inherit pkgs; }. - The
//operator merges two attrsets, ideal for a defaults + overrides system. fetchTarballon a commit archive, with its sha256, freezes the nixpkgs version: no more drift between machines.- The hash is obtained with
nix-prefetch-url --unpackor by letting Nix compute it (empty sha256). - A branch URL (
nixos-24.11) is not a durable pin: the branch moves and the hash ends up no longer matching. Only a commit is immutable. - For team projects, flakes advantageously replace manual pinning thanks to
flake.lock.
Knowledge check
Check that the essentials of this guide are acquired. The questions only cover what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Understand and use Nix flakes
A new full quiz with random questions
Work again only on the questions you missed