NIX Nix
AI-powered detection and analysis of Nix files.
Instant NIX File Detection
Use our advanced AI-powered tool to instantly detect and analyze Nix files with precision and speed.
File Information
Nix
Code
.nix
text/x-nix
Nix Expression Language (.nix)
Nix is a purely functional package manager and configuration language that enables reproducible and declarative system configurations. Created by Eelco Dolstra in 2003, Nix uses a domain-specific functional language to describe packages, their dependencies, and system configurations. The Nix language is lazy, dynamically typed, and designed specifically for managing software packages and system configurations in a reproducible manner.
Technical Overview
The Nix language is used to write expressions that describe how to build packages, configure systems, and manage dependencies. It emphasizes purity, immutability, and reproducibility. All builds are performed in isolated environments, and the same Nix expression will always produce the same result regardless of the host system state.
Key Features
- Purely Functional: No side effects, immutable data structures
- Lazy Evaluation: Expressions are evaluated only when needed
- Reproducible Builds: Same inputs always produce same outputs
- Declarative Configuration: Describe what you want, not how to get it
- Atomic Upgrades: All-or-nothing package installations and upgrades
- Multiple Versions: Different versions of packages can coexist
Nix Language Syntax
Basic Data Types and Expressions
# Comments start with hash
# This is a simple Nix expression
# Basic values
let
# Integers
num = 42;
negNum = -10;
# Floats
pi = 3.14159;
# Strings
greeting = "Hello, World!";
name = "Nix";
interpolated = "Hello, ${name}!";
# Multi-line strings
multiline = ''
This is a multi-line string.
Indentation is automatically stripped.
Variables can be interpolated: ${name}
'';
# Booleans
isTrue = true;
isFalse = false;
# Null
nothing = null;
# Paths
currentDir = ./.;
configFile = ./config.nix;
absolutePath = /etc/nixos/configuration.nix;
# URIs
homepage = https://nixos.org;
in {
# This is an attribute set (like a dictionary/object)
inherit num pi greeting; # shorthand for num = num; pi = pi; etc.
message = interpolated;
config = {
debug = isTrue;
logLevel = "info";
features = {
enableFeatureX = true;
enableFeatureY = false;
};
};
}
Lists and Attribute Sets
let
# Lists (arrays)
numbers = [ 1 2 3 4 5 ];
strings = [ "apple" "banana" "cherry" ];
mixed = [ 1 "hello" true null ];
# List operations
concatenated = numbers ++ [ 6 7 8 ];
head = builtins.head numbers; # 1
tail = builtins.tail numbers; # [ 2 3 4 5 ]
length = builtins.length numbers; # 5
# Attribute sets (objects/dictionaries)
person = {
name = "Alice";
age = 30;
email = "[email protected]";
address = {
street = "123 Main St";
city = "Anytown";
zipcode = "12345";
};
};
# Accessing attributes
personName = person.name;
personAge = person.age;
personCity = person.address.city;
# Dynamic attribute access
attrName = "email";
personEmail = person.${attrName};
# Attribute set operations
updatedPerson = person // {
age = 31; # Override age
phone = "+1-555-0123"; # Add new attribute
};
# Recursive attribute sets
rec {
a = 1;
b = a + 2; # Can reference 'a'
c = b * 3; # Can reference 'b'
};
in {
inherit numbers strings person updatedPerson;
info = {
personName = personName;
listLength = length;
firstNumber = head;
};
}
Functions
let
# Simple function
add = x: y: x + y;
# Function with single parameter
square = x: x * x;
# Function with attribute set parameter
greet = { name, age ? 25 }: "Hello, ${name}! You are ${toString age} years old.";
# Function with rest parameters
mkPackage = { name, version, ... }@args: {
inherit name version;
meta = args.meta or {};
buildInputs = args.buildInputs or [];
};
# Higher-order function
map = f: list:
if list == []
then []
else [ (f (builtins.head list)) ] ++ map f (builtins.tail list);
# Conditional expression
max = x: y: if x > y then x else y;
# Pattern matching with attribute sets
processUser = user:
if user ? admin && user.admin
then "Admin user: ${user.name}"
else "Regular user: ${user.name}";
# Using let...in within functions
calculateArea = { width, height }:
let
area = width * height;
perimeter = 2 * (width + height);
in {
inherit area perimeter;
description = "Rectangle: ${toString width}x${toString height}";
};
in {
# Function calls
sum = add 5 3; # 8
squared = square 4; # 16
greeting = greet { name = "Bob"; age = 35; };
# Using default parameters
defaultGreeting = greet { name = "Charlie"; }; # age defaults to 25
# Mapping over lists
squaredNumbers = map square [ 1 2 3 4 5 ]; # [ 1 4 9 16 25 ]
# Package example
myPackage = mkPackage {
name = "hello";
version = "2.12.1";
meta = { description = "A program that prints Hello, World!"; };
buildInputs = [ "gcc" "make" ];
};
}
Advanced Language Features
let
# Imports and composition
utils = import ./utils.nix;
config = import ./config.nix;
# With expressions (bring attributes into scope)
mathOps = {
add = x: y: x + y;
multiply = x: y: x * y;
divide = x: y: x / y;
};
calculation = with mathOps; add 10 (multiply 3 4); # 22
# Assert expressions
safeDivide = x: y:
assert y != 0;
x / y;
# Derivations (basic package building)
hello = derivation {
name = "hello-2.12.1";
system = "x86_64-linux";
builder = "${bash}/bin/bash";
args = [ "-c" "echo Hello > $out" ];
src = fetchurl {
url = "https://ftp.gnu.org/gnu/hello/hello-2.12.1.tar.gz";
sha256 = "086vqwk2wl8zfs47sq2xpjc9k066ilmb8z6dn0q6ymwjzlm196cd";
};
};
# String interpolation and escaping
shellScript = ''
#!/bin/bash
echo "Current directory: $(pwd)"
echo "User: $USER"
echo "Nix store: ${builtins.storeDir}"
'';
# File and directory operations
configFiles = {
"nginx.conf" = ./configs/nginx.conf;
"app.yaml" = ./configs/app.yaml;
};
in {
inherit calculation hello;
script = shellScript;
configs = configFiles;
}
Package Definitions
Simple Package
# hello.nix - Simple package definition
{ lib, stdenv, fetchurl }:
stdenv.mkDerivation rec {
pname = "hello";
version = "2.12.1";
src = fetchurl {
url = "mirror://gnu/hello/hello-${version}.tar.gz";
sha256 = "086vqwk2wl8zfs47sq2xpjc9k066ilmb8z6dn0q6ymwjzlm196cd";
};
# Build phases
configurePhase = ''
./configure --prefix=$out
'';
buildPhase = ''
make
'';
installPhase = ''
make install
'';
# Metadata
meta = with lib; {
description = "A program that prints Hello, World!";
homepage = "https://www.gnu.org/software/hello/";
license = licenses.gpl3Plus;
maintainers = with maintainers; [ eelco ];
platforms = platforms.all;
};
}
Complex Package with Dependencies
# nodejs-app.nix - More complex package
{ lib
, stdenv
, fetchFromGitHub
, nodejs
, yarn
, python3
, pkg-config
, libpng
, libjpeg
, makeWrapper
}:
stdenv.mkDerivation rec {
pname = "my-nodejs-app";
version = "1.0.0";
src = fetchFromGitHub {
owner = "myorg";
repo = "my-nodejs-app";
rev = "v${version}";
sha256 = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
};
nativeBuildInputs = [
nodejs
yarn
python3
pkg-config
makeWrapper
];
buildInputs = [
libpng
libjpeg
];
# Custom build phases
configurePhase = ''
export HOME=$TMPDIR
yarn config --offline set yarn-offline-mirror $yarncache
yarn install --offline --frozen-lockfile --ignore-scripts --no-progress --non-interactive
patchShebangs node_modules/
'';
buildPhase = ''
yarn run build
'';
installPhase = ''
mkdir -p $out/lib/node_modules/${pname}
cp -r . $out/lib/node_modules/${pname}
mkdir -p $out/bin
makeWrapper ${nodejs}/bin/node $out/bin/${pname} \
--add-flags "$out/lib/node_modules/${pname}/dist/index.js"
'';
# Environment variables for runtime
passthru = {
updateScript = ./update.sh;
};
meta = with lib; {
description = "A Node.js application";
homepage = "https://github.com/myorg/my-nodejs-app";
license = licenses.mit;
maintainers = with maintainers; [ username ];
platforms = platforms.linux ++ platforms.darwin;
};
}
NixOS Configuration
System Configuration
# /etc/nixos/configuration.nix
{ config, pkgs, ... }:
{
imports = [
./hardware-configuration.nix
./services.nix
./users.nix
];
# Boot configuration
boot.loader.systemd-boot.enable = true;
boot.loader.efi.canTouchEfiVariables = true;
boot.kernelPackages = pkgs.linuxPackages_latest;
# Networking
networking = {
hostName = "nixos-desktop";
networkmanager.enable = true;
firewall = {
enable = true;
allowedTCPPorts = [ 22 80 443 8080 ];
allowedUDPPorts = [ 53 ];
};
};
# Time zone and internationalization
time.timeZone = "America/New_York";
i18n.defaultLocale = "en_US.UTF-8";
# Desktop environment
services.xserver = {
enable = true;
displayManager.gdm.enable = true;
desktopManager.gnome.enable = true;
layout = "us";
};
# Audio
sound.enable = true;
hardware.pulseaudio.enable = false;
security.rtkit.enable = true;
services.pipewire = {
enable = true;
alsa.enable = true;
alsa.support32Bit = true;
pulse.enable = true;
};
# System packages
environment.systemPackages = with pkgs; [
# Essential tools
vim
wget
curl
git
htop
tree
unzip
# Development
gcc
nodejs
python3
docker
docker-compose
# Desktop applications
firefox
vscode
discord
spotify
# Custom packages
(import ./custom-packages/my-app.nix { inherit pkgs; })
];
# Services
services = {
openssh = {
enable = true;
settings.PasswordAuthentication = false;
settings.PermitRootLogin = "no";
};
postgresql = {
enable = true;
package = pkgs.postgresql_14;
dataDir = "/var/lib/postgresql/14";
authentication = pkgs.lib.mkOverride 10 ''
local all all trust
host all all 127.0.0.1/32 trust
host all all ::1/128 trust
'';
};
redis.enable = true;
nginx.enable = true;
};
# Docker configuration
virtualisation.docker = {
enable = true;
autoPrune.enable = true;
};
# User configuration
users.users.alice = {
isNormalUser = true;
description = "Alice";
extraGroups = [ "networkmanager" "wheel" "docker" ];
shell = pkgs.zsh;
openssh.authorizedKeys.keys = [
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC..."
];
};
# ZSH configuration
programs.zsh = {
enable = true;
enableCompletion = true;
ohMyZsh = {
enable = true;
theme = "robbyrussell";
plugins = [ "git" "sudo" "docker" "kubectl" ];
};
};
# System state version
system.stateVersion = "23.05";
}
Home Manager Configuration
# home.nix - User environment configuration
{ config, pkgs, ... }:
{
# User information
home.username = "alice";
home.homeDirectory = "/home/alice";
home.stateVersion = "23.05";
# Packages available to user
home.packages = with pkgs; [
# CLI tools
fzf
ripgrep
fd
bat
exa
delta
# Development
rustup
go
terraform
kubectl
helm
# Media
vlc
gimp
inkscape
# Fonts
(nerdfonts.override { fonts = [ "FiraCode" "JetBrainsMono" ]; })
];
# Program configurations
programs = {
# Git configuration
git = {
enable = true;
userName = "Alice";
userEmail = "[email protected]";
extraConfig = {
core.editor = "vim";
init.defaultBranch = "main";
pull.rebase = true;
};
delta.enable = true;
};
# Vim configuration
vim = {
enable = true;
plugins = with pkgs.vimPlugins; [
vim-nix
vim-airline
nerdtree
fzf-vim
];
extraConfig = ''
set number
set relativenumber
set expandtab
set tabstop=2
set shiftwidth=2
syntax on
'';
};
# Terminal emulator
alacritty = {
enable = true;
settings = {
window.opacity = 0.9;
font = {
normal.family = "JetBrains Mono";
size = 12.0;
};
colors = {
primary = {
background = "0x1d1f21";
foreground = "0xc5c8c6";
};
};
};
};
# Shell configuration
zsh = {
enable = true;
enableAutosuggestions = true;
enableSyntaxHighlighting = true;
shellAliases = {
ll = "exa -l";
la = "exa -la";
grep = "rg";
cat = "bat";
find = "fd";
};
oh-my-zsh = {
enable = true;
theme = "agnoster";
plugins = [
"git"
"docker"
"kubectl"
"terraform"
"rust"
"golang"
];
};
};
# Browser
firefox = {
enable = true;
profiles.default = {
settings = {
"browser.startup.homepage" = "https://nixos.org";
"privacy.trackingprotection.enabled" = true;
};
extensions = with pkgs.nur.repos.rycee.firefox-addons; [
ublock-origin
privacy-badger
decentraleyes
];
};
};
};
# Environment variables
home.sessionVariables = {
EDITOR = "vim";
BROWSER = "firefox";
TERMINAL = "alacritty";
};
# Service management
services = {
# Syncthing for file synchronization
syncthing.enable = true;
# GPG agent
gpg-agent = {
enable = true;
enableSshSupport = true;
pinentryFlavor = "gtk2";
};
};
# XDG configuration
xdg = {
enable = true;
userDirs = {
enable = true;
createDirectories = true;
};
};
# Font configuration
fonts.fontconfig.enable = true;
# Let Home Manager install and manage itself
programs.home-manager.enable = true;
}
Development Environments
Shell Environment (shell.nix)
# shell.nix - Development environment
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
buildInputs = with pkgs; [
# Build tools
gcc
cmake
pkg-config
# Languages
nodejs
yarn
python3
python3Packages.pip
python3Packages.virtualenv
rustc
cargo
go
# Databases
postgresql
redis
# Tools
git
curl
jq
docker
docker-compose
kubectl
# Development utilities
direnv
pre-commit
# LSP servers
nodePackages.typescript-language-server
nodePackages.pyright
rust-analyzer
gopls
];
# Environment variables
shellHook = ''
echo "Development environment loaded!"
echo "Node.js: $(node --version)"
echo "Python: $(python --version)"
echo "Rust: $(rustc --version)"
echo "Go: $(go version)"
# Set up Python virtual environment
if [ ! -d .venv ]; then
python -m venv .venv
fi
source .venv/bin/activate
# Install Python dependencies if requirements.txt exists
if [ -f requirements.txt ]; then
pip install -r requirements.txt
fi
# Set environment variables
export DATABASE_URL="postgresql://localhost/devdb"
export REDIS_URL="redis://localhost:6379"
'';
# Additional environment variables
env = {
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
GOPATH = "./go";
NODE_ENV = "development";
};
}
Flake-based Project
# flake.nix - Modern Nix project configuration
{
description = "My development project";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
rust-overlay.url = "github:oxalica/rust-overlay";
};
outputs = { self, nixpkgs, flake-utils, rust-overlay }:
flake-utils.lib.eachDefaultSystem (system:
let
overlays = [ (import rust-overlay) ];
pkgs = import nixpkgs {
inherit system overlays;
};
rustVersion = pkgs.rust-bin.stable.latest.default;
buildInputs = with pkgs; [
rustVersion
pkg-config
openssl
] ++ lib.optionals stdenv.isDarwin [
libiconv
darwin.apple_sdk.frameworks.Security
];
nativeBuildInputs = with pkgs; [
cargo
rustc
];
in
{
devShells.default = pkgs.mkShell {
inherit buildInputs nativeBuildInputs;
shellHook = ''
echo "Rust development environment"
echo "Rust version: $(rustc --version)"
echo "Cargo version: $(cargo --version)"
'';
};
packages.default = pkgs.rustPlatform.buildRustPackage {
pname = "my-rust-app";
version = "0.1.0";
src = ./.;
cargoLock.lockFile = ./Cargo.lock;
inherit buildInputs nativeBuildInputs;
};
apps.default = flake-utils.lib.mkApp {
drv = self.packages.${system}.default;
};
});
}
File Format Details
- MIME Type:
text/plain
- File Extension:
.nix
- Language: Nix expression language
- Character Encoding: UTF-8
- Evaluation: Lazy evaluation with memoization
The Nix language provides a powerful foundation for reproducible package management and system configuration. Its purely functional approach ensures that builds are deterministic and systems can be reliably reproduced across different environments. The language's design makes it particularly well-suited for DevOps, continuous integration, and managing complex software dependencies.
AI-Powered NIX File Analysis
Instant Detection
Quickly identify Nix files with high accuracy using Google's advanced Magika AI technology.
Security Analysis
Analyze file structure and metadata to ensure the file is legitimate and safe to use.
Detailed Information
Get comprehensive details about file type, MIME type, and other technical specifications.
Privacy First
All analysis happens in your browser - no files are uploaded to our servers.
Related File Types
Explore other file types in the Code category and discover more formats:
Start Analyzing NIX Files Now
Use our free AI-powered tool to detect and analyze Nix files instantly with Google's Magika technology.
⚡ Try File Detection Tool