NixOSaaS
← Back to the blog

13 November 2026 · NixOSaaS

Introduction to the Nix programming language

Learn Nix from first principles: values, functions, attribute sets, modules and a reproducible development shell—with practical exercises.

A developer joins your team. Their first task should be understanding the application, but instead they spend the morning finding the right compiler, installing utilities and comparing configuration files. A week later, CI uses a different version of a tool and the same build fails again.

Nix gives you a language for describing those dependencies and composing reusable environments. Learning it also makes NixOS configuration easier to read. You do not have to replace Python, Go or Bash: Nix describes how tools and systems fit together, while those languages continue to implement your applications and scripts.

This introduction starts with small expressions and ends with a complete project shell. No previous functional-programming experience is required.

Nix, Nixpkgs and NixOS: three different things

NameWhat you are working with
Nix languageExpressions saved in .nix files.
Nix toolingCommands that evaluate expressions, build outputs and manage store paths.
NixpkgsA collection of package definitions and supporting functions written largely in Nix.
NixOSA Linux distribution whose system configuration uses Nix and a module system.
FlakeA convention for project inputs and outputs, with dependency revisions recorded in a lock file.

You can learn the language on NixOS, another Linux distribution or macOS. The operating system does not change the meaning of an expression such as 6 * 7.

Before you begin: install Nix if needed

NixOS already includes Nix. On Ubuntu, Debian, Fedora or a MacBook, you can use Nix without replacing your operating system. First open a terminal and check:

nix --version

If this prints a version, skip installation and continue to the learning workspace below. If it says command not found, choose the appropriate instructions here. You do not need Go or Python installed to start this article.

Linux: Ubuntu and Debian

For a typical systemd-based Ubuntu or Debian installation, install the download and extraction tools:

sudo apt update
sudo apt install curl xz-utils ca-certificates

Then run the official multi-user installer from your normal user account:

curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install | sh -s -- --daemon

This downloads and executes the installation script. Read the prompts and enter your sudo password when requested; do not start the entire command with sudo. The installer sets up the Nix store and a background daemon. This is a system installation, whereas the project environments later in this article are selected per shell.

The official download page recommends this Linux route for systems using systemd with SELinux disabled and sudo access. For other setups, consult the installation guide before proceeding.

Linux: a note for Fedora users

Fedora commonly enables SELinux, so do not assume the generic installer above is appropriate for its default configuration. The official Nix installation guide also points Fedora users to the Fedora Nix package, installed through dnf. Follow that package’s current setup instructions for your Fedora release, including daemon configuration. Keep SELinux enabled rather than weakening host security just to follow a tutorial. Once nix --version works, the language exercises below are the same.

macOS: Intel and Apple Silicon MacBooks

Open Terminal using Spotlight: press Command + Space, type Terminal, and press Enter. Use a native terminal on Apple Silicon rather than a Rosetta-translated session. The current official installer requires macOS 14 or newer; check the download page for changes to supported versions.

Run:

curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install | sh

Follow the prompts and provide your administrator password when requested. The installer uses the multi-user setup on macOS. You do not need Homebrew, NixOS or nix-darwin for this tutorial. The commands here work in Bash and zsh, macOS’s usual default shell.

Open a new terminal and verify

After installation finishes successfully, close Terminal and open it again so the shell loads the environment changes. Run:

command -v nix
nix --version
nix --extra-experimental-features 'nix-command flakes' eval --expr '6 * 7'

The first command should print a path, the second a Nix version, and the final command should print 42. Your version does not need to match a screenshot or example exactly.

If nix is still missing, check the installer’s final shell-setup instructions before reinstalling. For an official multi-user installation, if this file exists, you can load it into the current Bash or zsh session:

if [ -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then
  . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
fi
nix --version

If the installer reported an error, resolve that error first; changing PATH alone will not repair an incomplete installation. Continue below once the version check and the 42 expression succeed.

1. Prepare a small learning workspace

Check that Nix is available:

nix --version

If Nix is not available yet, complete the installation section above before continuing. You do not need to install Go or Python for the language exercises.

Use a fresh directory outside an existing Git repository:

mkdir -p ~/projects/nix-language-lab
cd ~/projects/nix-language-lab

Run these commands as a normal user. To make the examples shorter, define a helper in your current Bash or zsh terminal:

nx() {
  command nix --extra-experimental-features 'nix-command flakes' "$@"
}

nx is our temporary shell function, not a standard Nix command. It enables the command features used below without editing system settings. Define it again if you open another terminal.

Try your first expression:

nx eval --expr '6 * 7'

Expected result:

42

For interactive exploration, run nx repl, enter an expression at its prompt, and use :q to leave. Do not type the nix-repl> prompt itself.

2. Think in expressions and values

A Nix expression produces a value. A .nix file is not a sequence of shell commands: it contains an expression, which might produce a number, a configuration set or a function.

For example:

nx eval --expr 'if 4 > 2 then "ready" else "waiting"'

Result:

"ready"

Both branches are required. The conditional chooses a value; it does not execute an installation step.

Nix values are immutable. Rather than updating a variable repeatedly, you derive new values from existing ones. Nix also evaluates lazily: it only computes expressions when their results are needed. This is useful when describing large collections of packages, but it means an error can appear only when a particular value is inspected.

nx eval --expr 'let unused = builtins.throw "not needed"; in 42'

This still returns 42: nothing asks for unused.

3. Basic data types

TypeExampleTypical use
Integer8080A port number
Float0.75A numeric calculation
BooleantrueEnable or disable a feature
String"training"Names and text
NullnullAn absent value where supported
Path./settings.nixA file reference
List[ "git" "curl" ]An ordered collection
Attribute set{ name = "lab"; port = 8080; }Named values

A path such as ./settings.nix is not the same value as the string "./settings.nix". Relative path literals in a file are resolved relative to that Nix file. Strings are text unless the receiving function interprets them otherwise.

Comments use # for the remainder of a line, or /* ... */ for a block.

4. Attribute sets: the structure you will see everywhere

An attribute set groups values under names:

{
  name = "training-api";
  port = 8080;
  enabled = true;
}

Every attribute assignment ends with a semicolon. There are no commas between these assignments.

Select one value using a dot:

nx eval --expr '{ name = "training-api"; port = 8080; }.port'

Result: 8080.

Sets can be nested. These two expressions have the same structure:

{ service = { port = 8080; }; }
{ service.port = 8080; }

You can supply a fallback when selecting an absent attribute:

nx eval --expr '{ name = "training-api"; }.port or 8080'

Here, or belongs to attribute selection. Boolean “or” uses || instead.

Combining sets

The // operator combines two sets, taking the right-hand value when a name appears in both:

nx eval --expr '{ port = 8080; } // { port = 9090; enabled = true; }'

This is a shallow merge. If both sides contain a nested service attribute, the right-hand service replaces the left-hand one; it does not automatically merge their children. It is also different from the NixOS module system’s option-merging rules.

5. Local names with let … in

Use let to bind names and in to introduce the expression that uses them:

nx eval --raw --expr 'let name = "NixOSaaS"; in "Hello, ${name}!"'

Expected output:

Hello, NixOSaaS!

--raw prints a string without Nix’s surrounding quotes. It may not add a trailing newline.

${name} inserts a value into a string. Convert numbers explicitly when needed:

nx eval --raw --expr 'let port = 8080; in "Listening on ${toString port}"'

The shell command uses single quotes around the expression so Bash or zsh does not attempt to expand ${...} before Nix receives it.

For multi-line text, Nix offers indented strings:

''
  Welcome to the training lab.
  Keep the environment definition with your project.
''

These strings still support Nix interpolation. When embedding shell code, write ''${HOME} inside an indented string if you want the shell, rather than Nix, to expand ${HOME} later.

6. Lists and transformations

Lists separate elements with whitespace:

[ "development" "staging" "production" ]

Combine lists with ++:

nx eval --expr '[ "git" ] ++ [ "curl" "jq" ]'

Transform every element with builtins.map:

nx eval --expr 'builtins.map (name: "service-${name}") [ "api" "worker" ]'

Result:

[ "service-api" "service-worker" ]

The expression name: "service-${name}" is a function. Parentheses keep a function call together when it is a single element inside a list; [ (f 1) ] differs from [ f 1 ].

7. Functions without the ceremony

A function uses a colon to separate its argument from its body:

port: port + 1000

Call it by placing an argument after it:

nx eval --expr '(port: port + 1000) 8080'

Result: 9080. Nix does not require the familiar function(argument) syntax.

Multiple arguments are commonly expressed as functions returning functions:

nx eval --expr '(a: b: a + b) 20 22'

For configuration code, an attribute-set argument is often clearer:

{ name, port ? 8080 }:
{
  inherit name port;
  enabled = true;
}

name is required. port defaults to 8080 when omitted. inherit name port; is shorthand for name = name; port = port; inside the resulting set.

The commas here separate function argument declarations, not attributes in an ordinary set. Add ... to the argument pattern when additional input attributes should be accepted.

8. Split code across files

Create a reusable function:

cat > service.nix <<'EOF'
{ name, port ? 8080 }:
{
  inherit name port;
  endpoint = "http://localhost:${toString port}";
}
EOF

Create a file that imports and calls that function:

cat > example.nix <<'EOF'
let
  makeService = import ./service.nix;
in
  makeService {
    name = "training-api";
    port = 9090;
  }
EOF

Evaluate it:

nx eval --json --file ./example.nix

Expected output (key order is not significant):

{"endpoint":"http://localhost:9090","name":"training-api","port":9090}

This describes a service record; it does not start an HTTP server. import evaluates another file and returns its value. Here that value is a function, which we call with a set of arguments. The imported file does not automatically inherit local variables from its caller.

Try removing port = 9090; and evaluate again. The default should produce port 8080.

9. Recognise common configuration patterns

rec {
  name = "training";
  label = "${name}-environment";
}

rec allows attributes to reference others in the same set. Avoid circular references: a value that depends on itself cannot be resolved.

with pkgs; [ git curl jq ]

with makes names from a set available for lookup in an expression. The explicit alternative, [ pkgs.git pkgs.curl pkgs.jq ], is often easier for beginners to follow.

{ config, pkgs, ... }: {
  services.openssh.enable = true;
}

This is a function returning a set. config and pkgs are arguments supplied by the NixOS module system—not language keywords. services.openssh.enable is a module option, not a built-in language feature. Writing it does not start SSH immediately: the module must be incorporated into a system build and activated.

10. A complete development-environment exercise

Create flake.nix in your learning directory:

cat > flake.nix <<'EOF'
{
  description = "Nix language learning environment";
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";

  outputs = { nixpkgs, ... }:
    let
      systems = [ "x86_64-linux" "aarch64-linux"
                  "x86_64-darwin" "aarch64-darwin" ];
    in {
      devShells = nixpkgs.lib.genAttrs systems (system:
        let pkgs = nixpkgs.legacyPackages.${system};
        in {
          default = pkgs.mkShell {
            packages = [ pkgs.python3 pkgs.git ];
            TRAINING_PROJECT = "nix-language-lab";
          };
        });
    };
}
EOF

On macOS, use github:NixOS/nixpkgs/nixpkgs-26.05-darwin as the input URL to follow that release’s Darwin-tested branch. These release branches can advance; the lock file records the exact revision selected.

Create the lock file and run Python through Nix:

nx flake lock
nx develop -c python3 -c 'import os; print(os.environ["TRAINING_PROJECT"])'

Expected output:

nix-language-lab

The first run may take several minutes to download and unpack dependencies. Wait for completion; a quiet progress display alone does not indicate failure.

For an interactive shell, run:

nx develop

Inside that shell:

python3 --version
git --version
echo "$TRAINING_PROJECT"

Run exit once when finished. The nx helper was defined in your original shell; use the supplied tools directly inside the development shell.

Here the earlier concepts fit together: outputs is a function, systems is a list, genAttrs constructs a set, and mkShell receives a set describing the environment. Listing four platforms does not build all four whenever you enter your local shell.

11. Evaluation, building and reproducibility

Evaluating example.nix produces a value. Package definitions describe derivations: build instructions with declared inputs and outputs. Nix can obtain suitable outputs from a binary cache or build them. Builders may execute shell scripts or compilers; evaluating the surrounding Nix expression is not the same as executing those build commands.

Keep flake.nix and flake.lock together in version control. Review dependency updates and rerun your checks before sharing a new toolchain. If your directory becomes a Git repository, stage newly added Nix files: untracked files may be excluded from a flake’s source.

A lock file does not automatically pin dependencies downloaded independently by pip or npm. Keep application dependency locks too, and test on the platforms you support. Identical declared tool versions do not make Linux and macOS identical runtime environments.

A development shell is not a security sandbox. Commands retain your account’s permissions and can write files or access the network. Exiting restores the parent shell environment, but does not delete packages from the Nix store or undo application changes. Use a VM or container when a separate runtime boundary is needed.

Common beginner mistakes

SymptomWhat to check
Missing semicolonAttribute assignments and let bindings normally end in ;.
Commas in a listUse whitespace: [ "one" "two" ].
Undefined variableCheck spelling, scope and function arguments.
Unexpected function argumentCheck the function’s set pattern; ... permits additional attributes when intended.
Shell substitution errorSingle-quote inline expressions containing ${...}.
Shell keeps showing > after pastingFinish the heredoc with EOF alone on a line, without indentation.
Flake ignores a new fileCheck whether Git knows about that file.
Experimental feature errorUse the nx helper or explicit feature flags.
Configuration evaluates but nothing changesEvaluation alone does not activate a NixOS configuration.

For more context on an error, try:

nx eval --show-trace --file ./example.nix

Start with the relevant source location and error message rather than changing unrelated settings.

What to practise next

Extend service.nix with an enabled argument defaulting to true. Add another service in example.nix and return a list of both records. Then change one package in the development shell and verify its command with nx develop -c.

Once those exercises feel comfortable, explore package derivations, NixOS modules and language-specific build helpers. Keep the first real project small: describe a useful environment, share its input revisions and define a check that demonstrates it works.

Official references