11. Reproducible Dev Environments

Pin a project's exact toolchain in its flake — and enter it automatically

Open almost any project's README and you'll find a paragraph like this near the top: "You'll need Node 20, PostgreSQL 15, protoc, and a recent golangci-lint. Make sure node_modules/.bin is on your PATH, and export DATABASE_URL before running the tests." It's a ritual every developer knows: a checklist of global installs, version juggling, and environment variables you set once and forget. It half-works, it drifts, and six months later a new teammate spends a day discovering that the build only passes if you have exactly protoc 3.21 — which nobody wrote down.

That checklist is the imperative package manager from the mental-model article, wearing a different hat. It's the same accumulated, undocumented drift, just scoped to a single repository instead of a whole machine. NixOS already taught us the cure at the system level: describe what you want in a file, pin the inputs, and let one command make reality match. Dev shells apply that exact same idea to a project. The tools a repo needs stop being something you install globally and start being something the flake provides — pinned to precise versions, isolated from everything else on your machine, and reproduced byte-for-byte on a colleague's laptop or in CI.

The whole idea in one paragraph

A dev shell is a throwaway environment, described in your flake.nix, that puts a specific set of tools and libraries on your PATH and sets a specific set of environment variables — and nothing else. You enter it with nix develop. Because the tools come from your flake's pinned nixpkgs input, everyone who enters the shell gets the identical toolchain, and nothing leaks into (or is polluted by) your global system. No apt install, no version managers, no "works on my machine."

This is, for many people, the single most useful thing Nix does — you can get all of it on any Linux or macOS machine with Nix installed, without running NixOS at all.

A shell scoped to one project

Think about what a shell environment actually is: a PATH listing directories to search for executables, plus a bag of environment variables, plus whatever shell functions and aliases were set up on the way in. A normal login shell inherits a giant, machine-global version of all three. A dev shell is a small, deliberate one, built fresh for a single project.

When you run nix develop, Nix evaluates your flake, builds (or fetches from the cache) every tool the shell declares, and drops you into a subshell whose PATH has been prepended with bin/ directories pointing straight into /nix/store. Type node inside that shell and you get the exact node your flake pinned — not the one in /usr/bin, which might not exist at all. Exit the shell and that PATH is gone; your normal environment is untouched.

flake.nix inputs.nixpkgs (pinned) devShells.default mkShell { packages = [ node pg ] } nix develop build / fetch, then enter isolated dev shell PATH prepended with: …-nodejs-20.11.1/bin …-postgresql-15.6/bin DATABASE_URL set by hook exit → PATH restored, global system untouched The tools live in the store, pinned by the same flake.lock that pins your system. Two people who check out the repo enter the byte-for-byte same environment.

The word "isolated" is doing real work here. A node you installed globally shares a single node_modules search path, a single npm prefix, one version at a time. Twelve projects fighting over one global Node is how version managers like nvm were born. With dev shells, each project's flake declares its own Node, its own Postgres, its own protoc; they coexist in the store exactly the way multiple package versions coexisted in the mental-model article, and switching between them is just cd-ing into a different directory.

devShells in a flake

The dev shell is a flake output, right alongside the nixosConfigurations you already know. Its well-known name is devShells, and — like most flake outputs that produce something buildable — it's indexed by system, then by a shell name:

flake.nix — a single-system dev shell

{
  description = "Dev environment for my web app";
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
  outputs = { self, nixpkgs }:
    let
      system = "x86_64-linux";
      pkgs = nixpkgs.legacyPackages.${system};
    in {
      devShells.${system}.default = pkgs.mkShell {
        packages = [
          pkgs.nodejs_20
          pkgs.postgresql_15
          pkgs.protobuf
        ];
        shellHook = ''
          echo "entered $(node --version) dev shell"
          export DATABASE_URL="postgres://localhost/app_dev"
        '';
      };
    };
}

Two flake details worth calling out before we get to mkShell itself:

  • pkgs = nixpkgs.legacyPackages.${system} is how you get the package set out of the flake-form nixpkgs input. (It's called legacyPackages for boring historical reasons — the flake packages output has a stricter schema than the sprawling nixpkgs tree, so nixpkgs exposes its full set under this name. It's the normal, correct way to get pkgs; the name is not a warning.)
  • devShells.${system}.default — default is the shell nix develop picks when you don't name one. You can add more (devShells.${system}.ci, .docs, …) and select them with nix develop .#ci.

Entering it

From inside the repo:

$ nix develop
entered v20.11.1 dev shell
$ which node
/nix/store/…-nodejs-20.11.1/bin/node
$ node --version
v20.11.1

You're now in a subshell with the pinned tools on PATH and DATABASE_URL exported. Everything you'd expect from a shell works; the difference is that the toolchain is defined by the flake, not by your machine. Type exit (or Ctrl-D) to leave and get your normal shell back.

Running one command in the shell

You don't always want an interactive session. To run a single command inside the dev shell and come straight back out, use -c (short for --command):

$ nix develop -c npm test
$ nix develop -c make build

This is the form you reach for constantly: it's how a Makefile target, a git hook, or a CI job runs "the thing" with the project's exact toolchain, without anyone having to be in the shell first. nix develop -c $SHELL is also a handy way to enter interactively while keeping your own shell (zsh, fish) instead of the default bash.

Two entry points, one shell

nix develop drops you into the dev shell interactively. nix develop -c <cmd> runs one command inside it and exits. Both build the identical environment from the flake, so a command you run with -c in CI behaves exactly like the same command typed by a developer sitting in the shell.

Covering every system without repeating yourself

There's an obvious wart in that first flake: devShells.${system}.default hardcodes x86_64-linux. A colleague on an Apple Silicon Mac (aarch64-darwin) or an ARM Linux box (aarch64-linux) checks out the repo, runs nix develop, and gets "error: flake does not provide a dev shell for aarch64-darwin." We need the same shell defined for every system we care about — but writing it out four times is exactly the kind of copy-paste that rots.

The manual way: genAttrs

The standard library has a helper, lib.genAttrs, that builds an attribute set by mapping a function over a list of names. Point it at your list of systems and you get one entry per system, generated from a single definition:

flake.nix — all systems, by hand

outputs = { self, nixpkgs }:
  let
    systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
    # forAllSystems f = { x86_64-linux = f "x86_64-linux"; aarch64-linux = f "…"; … }
    forAllSystems = f: nixpkgs.lib.genAttrs systems f;
  in {
    devShells = forAllSystems (system:
      let pkgs = nixpkgs.legacyPackages.${system}; in {
        default = pkgs.mkShell {
          packages = [ pkgs.nodejs_20 pkgs.postgresql_15 ];
        };
      });
  };

Read forAllSystems as "for each system in the list, produce this value, keyed by the system name." The function it's given takes a system, builds the right pkgs for it, and returns { default = …; }. The result is devShells.x86_64-linux.default, devShells.aarch64-linux.default, and so on — the exact shape nix develop expects, with the shell written once. This is worth understanding even if you later reach for a helper, because it's just Nix — no extra inputs, nothing magic.

The flake-utils way

That forAllSystems/genAttrs pattern is so common that the community packaged it. The flake-utils input from numtide gives you eachDefaultSystem, which does the iteration and the per-system wrapping for you:

flake.nix — all systems, with flake-utils

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
    flake-utils.url = "github:numtide/flake-utils";
  };
  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let pkgs = nixpkgs.legacyPackages.${system}; in {
        devShells.default = pkgs.mkShell {
          packages = [ pkgs.nodejs_20 pkgs.postgresql_15 ];
        };
      });
}

Notice the shape flipped: inside eachDefaultSystem you write devShells.default (no ${system}), and the helper inserts the system layer for you, turning it into devShells.<system>.default for each of its default systems — the same four x86-64/aarch64 Linux and Darwin doubles as above. eachDefaultSystem also transposes every output the same way, so if you later add packages or checks, they get the per-system treatment for free.

genAttrs (no extra input)

Pure standard library — nothing new to fetch or lock. You write the systems list and the wrapping yourself, so the structure is fully visible. Slightly more boilerplate, but zero dependencies and no indirection to learn.

flake-utils (a small dependency)

eachDefaultSystem removes the per-system boilerplate and gives you a sensible default systems list. Costs one more flake input to pin and update, and a little "where did the system layer go?" magic. Extremely common in the wild.

Neither is "correct" — plenty of large flakes stick to genAttrs precisely to avoid the extra input, while plenty of others lean on flake-utils (or flake-parts, a heavier framework) to stay terse. Know both; the manual version is what the helper is doing under the hood.

Inside mkShell

pkgs.mkShell is where you actually describe the environment. It's a thin wrapper around the same stdenv.mkDerivation that builds real packages — a dev shell is, quietly, "the build environment of a package that has no build" — which is why its arguments look build-flavored. Four of them matter.

packages — the tools you want on PATH

This is the everyday one. packages is a list of derivations whose bin/ directories are put on your PATH. Compilers, language runtimes, linters, formatters, database servers, ripgrep — anything you want to run in the shell goes here.

packages is just nativeBuildInputs

In mkShell, packages is literally an alias for nativeBuildInputs. You'll see both spellings in real flakes; they do the same thing. packages is the clearer name for "tools I want available," so prefer it in a dev shell.

buildInputs vs nativeBuildInputs — and why it usually doesn't bite you

The distinction between these two comes from cross-compilation, and it's worth understanding even though, for a typical same-platform dev shell, both make things available and the difference is invisible:

  • nativeBuildInputs are things that need to run during the build — on the machine doing the building. Compilers, code generators, pkg-config, protoc: tools you invoke. This is what packages aliases, and it's the right home for anything you'll actually execute in the shell.
  • buildInputs are things that get linked into or used by what you're building — libraries for the target machine. openssl, zlib, sqlite when you're compiling a program that links against them.

When you cross-compile (say, building on x86-64 for a Raspberry Pi), the two must come from different package sets — you need an x86-64 protoc that runs on your builder, but an ARM openssl for the code to link against. On a normal dev shell where you build for the machine you're on, both resolve to the same set, so putting a library in the "wrong" list still works. The habit to keep anyway: tools you run → packages; libraries you compile and link against → buildInputs. It keeps the intent legible and stays correct if the shell is ever reused for cross-compilation.

A shell that also builds a C-linking program

pkgs.mkShell {
  # tools you run
  packages = [ pkgs.gcc pkgs.pkg-config pkgs.gnumake ];
  # libraries the program links against
  buildInputs = [ pkgs.openssl pkgs.zlib ];
}

shellHook — code that runs on entry

shellHook is a string of bash that runs every time you enter the shell, right before the prompt appears. It's the place for anything the environment needs at startup that isn't just a tool on PATH: printing a hint, creating a scratch directory, starting a throwaway Postgres, or exporting a computed variable.

A more realistic shellHook

shellHook = ''
  export PROJECT_ROOT="$PWD"
  export PATH="$PWD/node_modules/.bin:$PATH"
  export DATABASE_URL="postgres://localhost:5432/app_dev"
  mkdir -p .cache
  echo "dev shell ready — run 'npm test' to check your setup"
'';

Note the literal dollar signs: $PWD, $PATH, and the ''…'' string are all plain shell, evaluated when you enter the shell, not by Nix. (Inside a Nix ''…'' string, actual Nix interpolation uses ${'$'}{…} — a deliberately awkward escape, precisely so ordinary shell $VAR usage passes through untouched, which is what you want most of the time.)

inputsFrom — inherit another package's build environment

This one is a quiet superpower. inputsFrom takes a list of packages and pulls in all of their buildInputs and nativeBuildInputs, so your shell has everything needed to build those packages — without you re-listing their dependencies by hand.

The classic use: you have a real package derivation for your project (from the local-packages article), and you want a dev shell that can build it. Instead of duplicating its dependency list, you point inputsFrom at the package itself:

A dev shell derived from your package

let
  myApp = pkgs.callPackage ./package.nix { };
in pkgs.mkShell {
  # everything myApp needs to build, automatically:
  inputsFrom = [ myApp ];
  # plus dev-only extras that aren't build deps:
  packages = [ pkgs.rust-analyzer pkgs.cargo-watch ];
}

Now the shell always has exactly the dependencies your package build requires — if you add a buildInputs entry to the package, the shell inherits it on the next nix develop, with no second edit. You layer editor tooling and watchers on top via packages. This keeps "how to build the thing" defined in exactly one place.

Plain environment variables

Any attribute you pass to mkShell that isn't one of its known arguments becomes an environment variable in the shell, as long as its value can be coerced to a string. This is the tidy way to set variables that don't need any logic:

Attributes become env vars

pkgs.mkShell {
  packages = [ pkgs.go ];
  # these two become $CGO_ENABLED and $GOFLAGS in the shell:
  CGO_ENABLED = "0";
  GOFLAGS = "-mod=vendor";
}

Use bare attributes for static values and shellHook for anything that needs to run commands or reference other variables.

The ergonomic endgame: direnv

nix develop is great, but there's friction: you have to remember to run it, it drops you into a fresh bash subshell (losing your zsh/fish niceties), and every entry re-checks the flake, which on a cold cache can pause for a second or two. For a tool you enter dozens of times a day, that friction adds up. The fix that turns dev shells from "nice" into "never think about it again" is direnv.

direnv is a small, language-agnostic shell extension: when you cd into a directory containing a .envrc file, it runs that file and loads the resulting environment into your current shell; when you cd out, it unloads it. On its own it knows nothing about Nix. The bridge is nix-direnv, a faster, caching implementation of direnv's use flake (and older use nix) helpers.

The entire per-project setup is a one-line file:

.envrc

use flake

The first time you cd into the repo, direnv refuses to run an unreviewed .envrc and asks you to approve it — a security guard against a malicious .envrc in a cloned repo:

direnv: error .envrc is blocked. Run `direnv allow` to approve its content
$ direnv allow
direnv: loading .envrc
direnv: using flake
direnv: export +DATABASE_URL +PATH …

From then on the workflow disappears. cd into the project and your shell is the dev shell — node, postgres, protoc, DATABASE_URL, all present, in your normal shell, with your normal prompt. cd out and they vanish. No command to remember, no subshell.

~ (home) plain login shell no project tools .envrc: use flake read by nix-direnv ~/proj same shell, now with node · pg · $DATABASE_URL ~/other tools unloaded back to plain shell cd proj cd .. Auto-enter on cd in, auto-exit on cd out — the environment follows the directory. nix-direnv caches the evaluated shell, so re-entry is near-instant.

Why nix-direnv, specifically

Plain direnv can call Nix, but it re-evaluates the flake and rebuilds the environment every single time you enter the directory — slow and wasteful. nix-direnv fixes two things:

  • Caching. It stores the evaluated shell environment and reuses it, so re-entering the directory is near-instant instead of re-running Nix. It only re-evaluates when flake.nix or flake.lock actually change.
  • Garbage-collection roots. It symlinks the shell's derivation into your gcroots so nix-collect-garbage won't delete the tools your dev shell depends on. Without this, a routine garbage collection could evict your toolchain and force a rebuild; with it, the environment survives GC and even works offline.

Installing it is one line in your NixOS (or Home Manager) config:

Enable direnv + nix-direnv on NixOS

# in configuration.nix
programs.direnv.enable = true;   # pulls in nix-direnv and hooks your shell

On NixOS the programs.direnv module wires nix-direnv in and installs the shell hook for you. (On non-NixOS machines you install direnv + nix-direnv yourself and add both a shell hook and a source line to your .direnvrc; the project's README covers it.) One habit worth adopting: add .direnv/ to your .gitignore, since that's where nix-direnv keeps its per-project cache.

Why direnv is the endgame

A committed one-line .envrc plus nix-direnv means the correct, pinned toolchain loads automatically the instant anyone enters the project — in their own shell, with no command to remember and no startup lag after the first run. The dev environment stops being something you do and becomes a property of the directory.

How this relates to the old nix-shell

If you've touched Nix before flakes, you'll have met nix-shell and shell.nix. It's worth being clear on how the pieces line up, because both worlds are still very much alive:

Classic: nix-shell + shell.nix

nix-shell reads a shell.nix (or default.nix) in the current directory and builds an environment from it — historically with mkShell too. But its nixpkgs comes from your machine's mutable channels, so "the same" shell.nix can build differently on different machines. No lock file.

Flake: nix develop + devShells

nix develop reads devShells.<system>.default from your flake, with nixpkgs pinned by flake.lock. Same mkShell underneath — but now the toolchain is pinned and reproducible, exactly like your system config.

The key continuity: mkShell predates flakes and is used by both. The move to flakes didn't change how you describe a shell — it changed how the shell's nixpkgs gets pinned (lock file instead of channels) and the command you enter it with (nix develop instead of nix-shell).

For compatibility, nix develop can still consume a classic file with nix develop -f shell.nix, and if you need to support teammates who still run bare nix-shell, a common trick is a tiny shell.nix that imports your flake's dev shell (via builtins.getFlake or the flake-compat shim) so both commands land in the identical environment. But for a greenfield project on this flakes-first series, devShells + nix develop + direnv is the whole story.

Pinning, updating, and CI

Everything the first-flake article said about reproducibility applies to dev shells unchanged, because the shell's tools come from the very same pinned nixpkgs input. That's the quiet payoff of putting the dev environment in the flake: it's governed by the same flake.lock.

  • Pinning. Your nodejs_20, postgresql_15, and friends resolve through the exact nixpkgs commit recorded in flake.lock. Two people, a year apart, get the same tool builds down to the hash. The dev environment is as reproducible as the OS.
  • Updating. Bumping your toolchain is the same deliberate act as upgrading a system: nix flake update (or nix flake update nixpkgs) rewrites flake.lock to a newer nixpkgs, and the next nix develop picks up the newer tools. The change is a reviewable one-file diff, and reverting the lock file instantly reverts the toolchain — no "which Node did the CI runner have?" archaeology.
  • CI uses the identical shell. This is the clincher. A CI job with Nix installed runs your tests with nix develop -c <cmd> against the same committed flake.lock, so the CI toolchain is provably the developer toolchain. The class of bug where "it passes locally but fails in CI" (or vice versa) because of a version skew simply stops existing — there's one pinned definition of the environment, and everyone, human or robot, enters it.

The same environment, everywhere

# a developer, interactively
$ nix develop
$ npm test
# CI, non-interactively, same flake.lock
$ nix develop -c npm test
# a Makefile target, same again
test:
	nix develop -c npm test

Build a dev shell

Rather than describe mkShell in the abstract, assemble one below. Check the tools your project needs and edit the shellHook line, and watch the generated devShells.default snippet update — alongside a simulated summary of what would be on your PATH and in your environment after nix develop.

The snippet is the value you'd put inside eachDefaultSystem (system: let pkgs = …; in { … }) — no ${system} layer needed. The PATH and environment summary is a simulation: it shows which binaries each tool would provide and which variables the shellHook exports; it doesn't actually run Nix.

Key Takeaways

  • A dev shell is a project-scoped environment declared in flake.nix: a pinned set of tools on PATH plus env vars, isolated from your global system. It's the cure for per-project "works on my machine."
  • The output is devShells.<system>.default, built by pkgs.mkShell. Enter it with nix develop; run one command in it with nix develop -c <cmd>.
  • Cover all systems once: either by hand with nixpkgs.lib.genAttrs (a forAllSystems helper, no extra input) or with flake-utils's eachDefaultSystem (terser, one more input to pin).
  • mkShell arguments: packages (tools on PATH; an alias for nativeBuildInputs), buildInputs (libraries you link against), shellHook (bash run on entry), inputsFrom (inherit another package's build deps), and bare attributes that become environment variables.
  • direnv + nix-direnv is the ergonomic endgame: a committed one-line .envrc (use flake) auto-loads the shell on cd in and unloads on cd out, with caching and gcroots so it's fast and survives garbage collection.
  • Same mkShell, different pinning: nix develop/devShells is the flake-era replacement for nix-shell/shell.nix — the shell description is the same, but the toolchain is now pinned by flake.lock.
  • CI enters the identical shell: the dev environment is pinned by the same lock file as the OS, updated deliberately with nix flake update, and reproduced exactly by nix develop -c in CI — so local and CI toolchains can't drift apart.

Your projects now carry their own toolchains, pinned and reproducible, and load them the moment you enter their directory. There's one thing a dev shell (and everything else in your flake) still can't safely hold, though: secrets. The Nix store is world-readable, so a password interpolated into a derivation is a password published to every user on the machine. Next, we'll fix that with sops-nix — encrypted at rest, decrypted only at activation, never in the store in cleartext.