2. The Nix Language

The small functional language behind every NixOS config and flake

In the last article we said a NixOS system is a description: you write down what you want, and one command builds a whole system to match. But a description written in what, exactly? Those files aren't YAML or TOML or JSON. They're written in the Nix language — a small, purpose-built programming language whose entire job is to compute configuration data and build recipes.

That framing is worth holding onto, because it's what makes the language feel unusual at first. Most languages you know are about doing things: open a file, mutate a variable, print to the screen, in order. Nix does none of that. A Nix program is one big expression that, when evaluated, produces a value — usually a nested tree of attribute sets that describes your system or your package. Think of it less as a script and more as "JSON, but with variables, functions, and the ability to compute things."

What kind of language this is

Nix is functional (you build values by composing functions, not by running statements in sequence), pure (evaluating an expression has no side effects — no files written, nothing printed, no clock read), lazy (nothing is computed until something actually needs it), and dynamically typed (values have types, but you don't declare them; a mismatch surfaces at evaluation time). Every one of those properties exists to serve a single goal: turning your files into predictable, reproducible configuration data.

The good news: the language is small. There are no classes, no loops, no mutable variables, no return. Once you've internalized attribute sets, functions, and laziness, you can read essentially any NixOS configuration or flake. This article walks through the whole thing with tiny worked examples. Wherever you see a nix-repl> prompt, that's an expression typed into nix repl and the line below is what Nix evaluates it to — you can follow along by running nix repl yourself.

Values: the building blocks

Everything in Nix is a value, and there are only a handful of kinds. Let's meet them.

Primitives

Numbers, booleans, and null

nix-repl> 40 + 2
42
nix-repl> 3.0 / 2
1.5
nix-repl> true && false
false
nix-repl> null
null

Integers and floats behave as you'd expect (mixing them promotes to a float). Booleans are true and false, combined with &&, ||, and !. There's a null value, used throughout NixOS options to mean "unset — use the default."

Strings

Ordinary strings use double quotes. The interesting feature is interpolation: inside a string, ${ ... } evaluates a Nix expression and splices its string value in. (This is also where NixOS's $ habits come from — that dollar-brace is Nix syntax, not shell.)

Interpolation with ${ ... }

nix-repl> name = "world"
nix-repl> "hello, ${name}!"
"hello, world!"
nix-repl> "1 + 1 = ${toString (1 + 1)}"
"1 + 1 = 2"

Only string-valued expressions can be interpolated, which is why the number 1 + 1 is wrapped in toString. Interpolating a package (as configs constantly do) splices in its /nix/store path.

For multi-line text — scripts, config file bodies — Nix has indented strings written with double single-quotes, ''...''. Their trick is that the smallest common leading indentation is stripped automatically, so you can indent the string to match the surrounding code without that whitespace ending up in the value:

Multi-line ''...'' strings

let
  greeting = ''
    #!/bin/sh
    echo "starting up"
    echo "done"
  '';
in greeting

The four-space indent shared by every line is removed, so the resulting string starts flush at #!/bin/sh. Inside ''...'' the escape for a literal interpolation is ''${, and a literal double-quote needs no escaping at all — which is exactly what you want when embedding shell or other config snippets.

Paths

Nix has a dedicated path type, written as a bare filesystem path — no quotes. Any token containing a slash that isn't a URL is a path: ./configuration.nix, ../modules, /etc/nixos. Relative paths are resolved against the file they appear in, not the current working directory, which is part of what keeps evaluation reproducible. When a path is used where a store path is needed, its contents are copied into the store.

There's also the angle-bracket form, <nixpkgs>, which looks a path up in Nix's search path (the NIX_PATH). You'll see it in older, pre-flake material; flakes deliberately avoid it because it depends on mutable global state — exactly the kind of thing we're trying to eliminate.

Paths vs. strings

nix-repl> ./hello.txt
/home/jo/project/hello.txt      # resolved relative to this file
nix-repl> "/etc/hostname"
"/etc/hostname"                 # just a string, not a path

Lists

A list is written with square brackets, and its elements are separated by whitespace — no commas. This trips up nearly everyone at first, especially because a stray comma is a syntax error, not a second element.

What you might type

[ "git", "htop", "vim" ]

Comma-separated, like most languages. This is a syntax error in Nix.

What Nix wants

[ "git" "htop" "vim" ]

Whitespace-separated. Lists can hold mixed types and other lists, too.

Because elements are space-separated, a function call inside a list often needs parentheses so Nix doesn't read the arguments as more list elements: [ (f 1) (f 2) ] is a two-element list, whereas [ f 1 f 2 ] is a four-element list containing the function f and the numbers.

Attribute sets

This is the heart of the language. An attribute set ("attrset") is an unordered collection of name = value; pairs wrapped in braces. Every pair ends in a semicolon, including the last one.

An attribute set

nix-repl> { hostName = "bluewhale"; cores = 8; enable = true; }
{ cores = 8; enable = true; hostName = "bluewhale"; }

You read a value back out with dot access: machine.hostName. Attribute sets nest freely, and Nix lets you write nested attributes with a dotted shorthand — services.openssh.enable = true; is exactly the same as services = { openssh = { enable = true; }; };.

That dotted shorthand is why NixOS configs are so pleasant to read: networking.hostName, services.nginx.enable, boot.loader.grub.device. Under the hood, though, it's all one big tree of attribute sets. Here's the whole picture:

One config is a tree of attribute sets{ … }the confignetworkingservicesenvironment.systemPackages = [ … ]hostName = "bluewhale"leaf: a stringopensshenable = trueleaf: a booleanThe dotted path services.openssh.enable is just a walk from the root down to a leaf value.

Bindings and scope

You rarely write one giant literal. You compute intermediate values and give them names.

let ... in

let introduces local bindings that are visible in the expression after in. The bindings are only in scope within that expression — there are no global variables.

Naming intermediate values

nix-repl> let x = 10; y = x * 2; in x + y
30

Note that y can refer to x even though x is defined "before" it — order doesn't matter inside a let, and bindings can reference each other. (This works because evaluation is lazy; more on that soon.)

rec — recursive attribute sets

In an ordinary attribute set, one attribute cannot see its siblings by name. Prefix the set with rec and it can:

Plain set — error

{
  version = "1.4";
  name = "app-${version}";
}
# error: undefined variable 'version'

rec set — works

rec {
  version = "1.4";
  name = "app-${version}";
}
# name evaluates to "app-1.4"

inherit — pull names into a set

inherit x; is shorthand for x = x; — it copies a name from the surrounding scope into the set you're building. inherit (src) a b; pulls a and b out of another attribute set src. It's pure sugar, but it appears constantly and reads much more cleanly than the long form.

inherit in action

let
  pkgs = { git = "…"; htop = "…"; vim = "…"; };
  version = "1.4";
in {
  inherit version;          # same as  version = version;
  inherit (pkgs) git htop;  # same as  git = pkgs.git; htop = pkgs.htop;
}

with — dump a set into scope

with someSet; expr makes every attribute of someSet available as a bare name inside expr. The classic use is with pkgs; so you can write [ git htop vim ] instead of [ pkgs.git pkgs.htop pkgs.vim ].

with for brevity

let pkgs = { git = "G"; htop = "H"; vim = "V"; };
in with pkgs; [ git htop vim ]
# => [ "G" "H" "V" ]

with is convenient but has a genuinely confusing edge: names brought in by with have lower priority than let-bound or function-argument names, and they don't shadow an enclosing binding the way you'd expect. If a variable is already in scope, the with version is quietly ignored. Because of this, many style guides recommend using with sparingly and keeping its body small — a single list is the sweet spot, a large nested expression is where it bites.

Functions

Functions are values, like everything else. A function is written pattern: body, with a colon. There's no def, no name (you name one by binding it in a let or a set), and crucially every function takes exactly one argument.

A one-argument function

nix-repl> double = x: x * 2
nix-repl> double 21
42

Application is just juxtaposition — double 21, no parentheses needed.

Currying: many arguments, one at a time

If every function takes one argument, how do you write a function of two? You return another function. x: y: x + y is a function that takes x and returns a function that takes y. Applying it to two arguments happens one step at a time — this is called currying, and it's why Nix function calls are just names and values separated by spaces.

Currying: add = x: y: x + yadda functionadd 3a NEW function: y: 3 + yadd 3 4= 7apply 3apply 4Each application feeds one argument and hands back the next function until the body can be evaluated.Partial application — stopping after add 3 — is free and often useful.

Attribute-set arguments

For a function that takes several named options, Nix lets the single argument be an attribute set and destructures it in the pattern. This is the form you'll see at the top of nearly every NixOS module and package:

The pattern you'll see everywhere

{ config, pkgs, ... }:
{
  environment.systemPackages = [ pkgs.git ];
}

This is one function of one argument, where the argument is expected to be an attribute set containing at least config and pkgs. The ... means "and any other attributes are allowed too" — without it, passing a set with extra keys is an error.

Arguments can have defaults with ?, making them optional:

Default argument values

nix-repl> greet = { name, punct ? "!" }: "hi ${name}${punct}"
nix-repl> greet { name = "jo"; }
"hi jo!"
nix-repl> greet { name = "jo"; punct = "."; }
"hi jo."

The @-pattern

Sometimes you want to destructure the argument set and keep a name for the whole thing. The @-pattern does both: args@{ config, pkgs, ... }: binds config and pkgs individually while also binding args to the entire set, so you can pass it along untouched.

@: name the whole argument

args@{ config, pkgs, ... }:
# use pkgs.git here, and pass the full set on with 'args'

Operators and everyday idioms

A few operators come up constantly in real configs. These five will cover the vast majority of what you read.

The operators you'll actually use

nix-repl> { a = 1; b = 2; } // { b = 9; c = 3; }   # merge / update
{ a = 1; b = 9; c = 3; }
nix-repl> { a = 1; } ? a                            # has-attr test
true
nix-repl> ({ a = 1; }.b or 99)                      # access with default
99
nix-repl> [ 1 2 ] ++ [ 3 4 ]                        # list concatenation
[ 1 2 3 4 ]
  • // — update / merge. a // b produces a new set with all of a's attributes, overridden by any that also appear in b. It's a shallow merge (it does not deep-merge nested sets), and it's how you tweak a package or extend a config: "take this set, but change these few keys."
  • ? — has-attribute. set ? name is true when name is present. Handy for conditionals like if cfg ? extraConfig then ... else ....
  • . with or — safe access. set.a.b or default reads a (possibly nested) attribute, falling back to default if any part of the path is missing, instead of throwing.
  • ++ — list concatenation. Joins two lists. You'll see it when a config appends packages to a base list: basePackages ++ [ pkgs.htop ].

Nix also has the expected if/then/else (which is an expression — it must have an else, because it has to produce a value) and an assert cond; body for sanity checks.

Builtins and lib

Nix ships a set of primitive operations in the builtins namespace, plus the familiar higher-order functions. A quick tour of the ones you'll meet early:

A glance at the standard toolkit

nix-repl> map (x: x * x) [ 1 2 3 ]
[ 1 4 9 ]
nix-repl> builtins.filter (x: x > 2) [ 1 2 3 4 ]
[ 3 4 ]
nix-repl> builtins.length [ "a" "b" "c" ]
3
nix-repl> builtins.attrNames { z = 1; a = 2; }
[ "a" "z" ]
nix-repl> builtins.toString 42
"42"

import deserves special mention: import ./other.nix reads that file, evaluates the single expression inside it, and returns the result. Since a file's expression is very often a function, import ./mkThing.nix { inherit pkgs; } is the standard way to load a Nix file and immediately call it with arguments. This is the mechanism that lets a configuration be split across many files.

Beyond builtins, the nixpkgs lib provides hundreds of higher-level helpers — lib.mkIf, lib.mkDefault, lib.mkForce, lib.optionals, lib.mapAttrs, string and list utilities, and so on. You don't need to memorize them; just recognize that when you see lib.something in a config, it's a plain function from that standard library, and you can look it up. We'll introduce the specific ones (mkIf, mkDefault, mkForce) when we cover modules, where they earn their keep.

Why laziness matters

Nix is lazy: an expression is only evaluated when its value is actually needed, and never more than once. This isn't a performance micro-optimization — it's what makes the whole ecosystem viable.

Unused values are never evaluated

nix-repl> let
            x = 1;
            boom = builtins.throw "kaboom";
          in x
1

boom would raise an error if evaluated — but it never is, because nothing asks for it. Only x is forced. The same reason lets let bindings reference each other in any order: Nix only follows a reference when it's demanded.

Now scale that up. Nixpkgs is one enormous attribute set describing over a hundred thousand packages. If evaluating your configuration meant building — or even fully evaluating — that entire set, nothing would ever finish. Laziness means Nix evaluates only the attributes your configuration actually reaches. Ask for pkgs.git and Nix computes the derivation for git and nothing else; the other hundred-thousand-plus packages are never touched. Your config selects a tiny live subset out of a colossal lazy tree, and only that subset is ever computed.

The one-sentence version

Laziness is why you can import the entire universe of nixpkgs at the top of a small config file and still have evaluation finish in a fraction of a second — Nix only ever computes the handful of values you actually use.

It's all just functions returning attribute sets

Here's the tie-back that makes everything click. All the machinery you'll build in the rest of this series is written in exactly the language above — there's no separate "config DSL" to learn on top of it.

A NixOS module — the unit a configuration is built from — is just a function that takes an attribute set and returns an attribute set:

A NixOS module is a function → attrset

{ config, pkgs, ... }:      # a function taking one attrset argument
{                           # returning an attrset (the config it contributes)
  networking.hostName = "bluewhale";
  services.openssh.enable = true;
  environment.systemPackages = [ pkgs.git pkgs.htop ];
}

Every concept here is one we just covered: an attribute-set argument with ..., dotted attribute paths, a list with no commas, and dot access into pkgs. NixOS collects many such functions, calls each with the same argument, and merges all the returned sets into one big configuration tree.

A flake is the same story one level up: flake.nix evaluates to an attribute set with an inputs attribute and an outputs attribute, where outputs is — you guessed it — a function that takes the resolved inputs and returns a set of results (your NixOS configurations, packages, dev shells, and so on).

A flake is an attrset with an outputs function

{
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
  outputs = { self, nixpkgs, ... }: {
    # ... attributes describing what this flake provides ...
  };
}

Don't worry about what goes inside those outputs yet — that's the next article. The point is only this: once you can read attribute sets and functions, a flake and a module hold no syntactic surprises. They are ordinary Nix values.

Try it: a Nix REPL

The fastest way to build intuition for a small functional language is to poke at it. Type an expression, see what it evaluates to — attribute sets, function application, // merges, list operations, string interpolation — the same way you would at a real nix repl prompt.

Key Takeaways

  • Nix is a pure, lazy, functional, dynamically-typed language whose only job is to evaluate to configuration data and build recipes. A program is one expression that produces one value — think "JSON with functions," not "a script."
  • Attribute sets are the core: { name = value; } with semicolons, nested freely, with the dotted shorthand a.b.c = …. A whole config is one big tree of them.
  • Lists are space-separated — no commas — and often need parentheses around function calls inside them.
  • Functions take one argument; multiple arguments are done by currying, and the attribute-set pattern { config, pkgs, ... }: with defaults (?) and the @-pattern is the form you'll see everywhere.
  • Learn the everyday operators: // (shallow merge/update), ? (has-attr), .x or default (safe access), ++ (list concat), plus let … in, rec, inherit, and (carefully) with.
  • Laziness is load-bearing: only the values you actually reach are ever computed, which is why importing all of nixpkgs is cheap.
  • Modules and flakes are just functions returning attribute sets — so the language on this page is all you need to read and write them.

You can now read a NixOS configuration line by line and know what each piece is: this is a function, that's an attribute set, this list has three packages, that string interpolates a store path. In the next article we put it to work and build your first flake — a real, reproducible NixOS configuration you can rebuild into a running system.