| | |

Netlify 05 🌐 File-Based Configuration (netlify.toml) — Mastering build commands, context overrides, and monorepo base directories

⏱️ Estimated read: 10 min | |

The netlify.toml file is the manifest for your web project’s infrastructure. While the Netlify web dashboard provides a user-friendly interface for managing site settings, the netlify.toml file implements “Configuration as Code,” allowing developers to define build pipelines, routing logic, and environment variables directly within the version-controlled repository. This approach ensures that every change to the infrastructure is tracked, peer-reviewed, and synchronized across the entire engineering team, eliminating the risks associated with manual configuration drift.

Located at the root of the repository, the file is parsed by Netlify’s build bot at the start of every deployment. It dictates how the build container should behave: which command to run, where the generated assets will be stored, and how serverless functions should be bundled. Because it supports conditional logic based on deployment contexts, a single netlify.toml can manage a complex lifecycle where a production site uses strict security headers while a staging site uses a different API endpoint and relaxed authentication rules.

This chapter covers the deep configuration of the build pipeline, the implementation of context-specific overrides for diverse deployment scenarios, and the orchestration of monorepo structures using base directories and ignore commands. The sections that follow explore the syntax and hierarchy of build settings, the mechanics of context-aware environment variables, and the specialized strategies required for managing multiple projects within a single Git repository.

Key point: The netlify.toml file acts as the authoritative source of truth for site configuration, enabling reproducible builds and context-specific infrastructure logic that lives alongside your application code.


Why X exists

The configuration drift problem. Manually changing build settings in a web UI creates a “black box” where developers don’t know when or why a setting was changed. By moving configuration into a TOML file, every infrastructure change is captured in the Git history, making it transparent and reversible.

The “works on my machine” build problem. Without a shared configuration file, different developers might use different build commands or output directories locally. netlify.toml ensures the build container uses the exact same parameters as the local netlify dev environment, guaranteeing parity.

The monorepo complexity problem. Modern engineering often involves multiple applications (e.g., a documentation site, a dashboard, and a landing page) living in a single repository. netlify.toml provides the base and ignore parameters needed to isolate these builds so that a change in one project doesn’t trigger unnecessary builds in others.

The context-specific requirement. High-performance applications require different settings for different environments. Production needs aggressive caching and minification, while previews might need debug logs and mock APIs. File-based configuration allows these overrides to be defined once and applied automatically.

The team synchronization problem. When a project moves from Vite to Next.js or changes its distribution folder from dist to build, every team member needs to update their settings. A version-controlled configuration file updates everyone’s environment simultaneously upon the next git pull.


a. The Build Pipeline and Publish Settings

The [build] block is the most fundamental section of the netlify.toml file. It defines the core operations Netlify performs after cloning your repository. The command specifies the shell script to run (e.g., npm run build), while the publish directory tells Netlify which folder contains the final HTML, CSS, and JS files to be deployed to the CDN.

[build]
  # The command to compile your site
  command = "npm run build"

  # The directory containing the static assets for deployment
  publish = "dist"

  # The directory where serverless functions are located
  functions = "netlify/functions"

If your project uses a framework that requires a specific Node.js or Ruby version, you can define these in the [build.environment] sub-section. This ensures the build container is provisioned with the correct runtimes before your build command even starts. Netlify’s build bot looks for these variables to configure the internal environment of the Linux container.

The publish path is relative to the root of the repository (or the base directory if one is defined). It is crucial that this path matches exactly what your build tool generates; if your build tool outputs to a folder named out but your TOML file points to dist, the deployment will result in a “Page Not Found” error because no assets were uploaded.


b. Context Overrides and Variable Scoping

Netlify’s power lies in its ability to adapt to the deployment lifecycle. Through [context.<name>] blocks, you can override any global build setting. The three primary contexts are production (the main branch), deploy-preview (pull requests), and branch-deploy (non-main tracked branches).

# Default settings
[build]
  command = "npm run build"

# Override for Production only
[context.production]
  command = "npm run build:prod"
  [context.production.environment]
    API_URL = "https://api.myapp.com"

# Override for all Pull Requests
[context.deploy-preview]
  command = "npm run build:preview"
  [context.deploy-preview.environment]
    API_URL = "https://staging.api.myapp.com"

Overrides follow a hierarchical merging logic. Netlify first loads the base [build] settings, then merges the specific context block. This allows you to keep your configuration “DRY” (Don’t Repeat Yourself) by only defining the differences in the context blocks.

Environment variables defined in these blocks are particularly useful for steering frontend code. For example, a React application can use process.env.API_URL to determine whether to fetch data from a live production database or a staging environment, based entirely on which context Netlify is currently building.


c. Monorepo Orchestration and Base Directories

In a monorepo, the root of the Git repository is not the root of the web project. The base directory setting tells Netlify to change the working directory to a specific subfolder before running the build. This is essential for projects using workspaces (like Lerna, Nx, or pnpm workspaces).

[build]
  # Navigate to this folder before running 'command'
  base = "packages/marketing-site"
  command = "npm run build"
  publish = "dist"

  # Only build if files in this project changed
  ignore = "git diff --quiet HEAD^ HEAD ."

The ignore command is a powerful optimization for monorepos. It is a shell script that Netlify executes to decide if a build is necessary. If the script exits with a status code of 0, the build is cancelled. The common pattern git diff --quiet HEAD^ HEAD . checks if any files within the current base directory have changed since the last commit. If the changes were in a different package (e.g., a backend folder), Netlify skips the frontend build, saving build minutes and developer time.

When using a base directory, all other paths (like publish and functions) become relative to that base. This creates a sandbox environment where the specific sub-project behaves as if it were a standalone repository, while still benefiting from shared dependencies and shared Git history.


Complete Example Session

# ============================================
# PART 1: BASE PROJECT STRUCTURE
# ============================================
[build]
  base = "apps/dashboard" # Working directory for monorepo
  command = "npm run build" # Standard build script
  publish = "build" # Artifact folder
  functions = "api" # Serverless functions folder

# ============================================
# PART 2: GLOBAL ENVIRONMENT
# ============================================
[build.environment]
  NODE_VERSION = "20" # Force Node 20 runtime
  NPM_FLAGS = "--no-audit" # Speed up installs

# ============================================
# PART 3: PRODUCTION SPECIFICS
# ============================================
[context.production]
  command = "npm run build:prod"
  [context.production.environment]
    SITE_URL = "https://dashboard.example.com"

# ============================================
# PART 4: STAGING BRANCH CONFIG
# ============================================
[context.staging] # Targets a branch named 'staging'
  command = "npm run build:staging"
  [context.staging.environment]
    SITE_URL = "https://staging-dashboard.example.com"

# ============================================
# PART 5: PULL REQUEST PREVIEWS
# ============================================
[context.deploy-preview]
  [context.deploy-preview.environment]
    DEBUG = "true" # Enable verbose logging
    SITE_URL = "https://preview.example.com"

# ============================================
# PART 6: THE IGNORE SCRIPT
# ============================================
[build]
  # Skip build if no files in 'apps/dashboard' changed
  ignore = "git diff --quiet HEAD^ HEAD ."

# ============================================
# PART 7: GLOBAL REDIRECTS
# ============================================
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200 # SPA fallback

# ============================================
# PART 8: SECURITY HEADERS
# ============================================
[[headers]]
  for = "/*"
  [headers.values]
    X-Frame-Options = "DENY"
    X-Content-Type-Options = "nosniff"

# ============================================
# PART 9: EDGE FUNCTIONS
# ============================================
[[edge_functions]]
  path = "/admin/*"
  function = "auth-check"

# ============================================
# PART 10: ASSET OPTIMIZATION
# ============================================
[build.processing]
  skip_processing = false
  [build.processing.css]
    bundle = true
    minify = true

The example above demonstrates a sophisticated configuration that manages a monorepo application with context-specific environments, custom routing, security headers, and edge-level authentication.


Quick Reference

Build Settings

PropertyDescriptionDefault
baseDirectory to change to before buildRepo Root
commandThe shell command to runNone
publishDirectory of files to deployRepo Root
functionsDirectory of serverless functionsnetlify/functions
ignoreScript to determine if build should runAlways build

Context Overrides

ContextTriggerUsage
productionPrimary branch pushLive site settings
deploy-previewPull Request / Merge RequestQA and review settings
branch-deployAny other tracked branchStaging / Development
devnetlify dev commandLocal environment emulation

Common Environment Variables

VariableUsage
NODE_VERSIONSets Node.js version (e.g., 18, 20.1)
NPM_VERSIONSets specific npm version
YARN_VERSIONSets specific Yarn version
HUGO_VERSIONSets specific Hugo version

Best Practices

✅ Do This:

# Use context-specific API endpoints
[context.production.environment]
  API_URL = "https://api.example.com"                         # ✅

# Set an explicit Node version for reproducibility
[build.environment]
  NODE_VERSION = "20"                                         # ✅

# Use the ignore command in monorepos to save build minutes
ignore = "git diff --quiet HEAD^ HEAD ."                      # ✅

# Place netlify.toml in the root of your repository
# (Even if your app is in a subfolder)                       # ✅

❌ Don’t Do This:

# Don't hardcode sensitive API keys in the TOML file
# Use the Netlify UI for secrets                             # ❌

# Don't use absolute paths for publish directories
publish = "/home/user/project/dist"                          # ❌

# Don't forget to include the base directory in ignore paths
# if not using the default '.'                               # ❌

# Don't duplicate the entire [build] block in contexts
# Only include the properties that change                    # ❌

Common Pitfalls

PitfallWhy It HappensFix
Build fails on “folder not found”publish directory doesn’t match build tool outputCheck build tool config (e.g., vite.config.js)
Wrong Node version usedNODE_VERSION not defined in TOMLAdd NODE_VERSION to [build.environment]
Redirects ignoredRedirects defined in _redirects but overridden in TOMLUse only TOML for complex redirect logic
Monorepo builds every timeignore command missing or incorrectAdd git diff check to the [build] block
Local dev differs from Prodnetlify.toml missing [context.dev]Add local-only overrides for development

Real-World Examples

1. Simple Vite/React App

[build]
  command = "npm run build"
  publish = "dist"

2. Next.js with Serverless Functions

[build]
  command = "npm run build"
  publish = ".next"

3. Hugo Static Site with version pin

[build]
  command = "hugo"
  publish = "public"
[build.environment]
  HUGO_VERSION = "0.121.0"

4. Monorepo sub-project with ignore logic

[build]
  base = "apps/blog"
  ignore = "git diff --quiet HEAD^ HEAD ."

5. Custom Staging Branch URL

[context.staging.environment]
  API_URL = "https://staging-api.example.com"

6. SPA Fallback Redirect

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

7. Proxying to an external API

[[redirects]]
  from = "/api/*"
  to = "https://backend.com/:splat"
  status = 200

8. Forcing HTTPS with 301

[[redirects]]
  from = "http://*"
  to = "https://:splat"
  status = 301
  force = true

9. Disabling indexing for Previews

[[context.deploy-preview.headers]]
  for = "/*"
  [context.deploy-preview.headers.values]
    X-Robots-Tag = "noindex"

10. Edge Function for A/B Testing

[[edge_functions]]
  path = "/"
  function = "split-test"

Visual

The netlify.toml Hierarchy

┌─────────────────────────────────────────────────────────┐
│ CONFIGURATION MERGING ORDER                             │
│                                                         │
│  1. [build] (Global Defaults)                           │
│          │                                              │
│          ▼                                              │
│  2. [context.name] (Specific Overrides)                 │
│          │                                              │
│          ▼                                              │
│  3. Netlify Dashboard (UI Overrides / Secrets)          │
│                                                         │
│  Final Build Configuration = (1 + 2 + 3)                │
└─────────────────────────────────────────────────────────┘

Monorepo Working Directory Flow

┌─────────────────────────────────────────────────────────┐
│ MONOREPO BUILD EXECUTION                                │
│                                                         │
│  Repo Root/                                             │
│  ├── apps/                                              │
│  │   └── dashboard/  ◄─── [base] Directory              │
│  │       ├── dist/   ◄─── [publish] Relative to base    │
│  │       └── api/    ◄─── [functions] Relative to base  │
│  └── netlify.toml    ◄─── Located at Root               │
│                                                         │
│  Build process: CD into dashboard -> Run command        │
└─────────────────────────────────────────────────────────┘

The Ignore Command Logic

┌─────────────────────────────────────────────────────────┐
│ BUILD IGNORE LOGIC                                      │
│                                                         │
│  Push Event Detected                                    │
│          │                                              │
│          ▼                                              │
│  Run Ignore Script: "git diff ..."                      │
│         / \                                             │
│        /   \                                            │
│   Exit 0    Exit 1                                      │
│     │         │                                         │
│     ▼         ▼                                         │
│ Cancel Build  Proceed to npm install                    │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
File Namenetlify.toml (lowercase)
LocationRoot of the repository
FormatTOML (Tom’s Obvious, Minimal Language)
Contextsproduction, deploy-preview, branch-deploy
Key Block[build]
Path HandlingRelative to base directory
PriorityContext blocks override Global blocks
Local Toolnetlify dev respects this file

Key takeaways:

  • Use netlify.toml for version-controlled infrastructure. It ensures your entire team uses the same build settings and environment variables.
  • Master the context overrides. Defining different build commands and variables for production versus staging prevents configuration errors during deployment.
  • Optimize monorepos with base and ignore. Avoid unnecessary builds and minutes by isolating sub-projects and only triggering builds when relevant files change.
  • Keep secrets out of TOML. Never put private API keys or passwords in the file; use the Netlify UI “Environment Variables” section for sensitive data.
  • Redirects and Headers live here. Use the TOML file to manage complex routing and security policies globally across your application.

Remember: The netlify.toml file is the bridge between your source code and the Netlify platform. By moving your configuration into this file, you create a transparent, reproducible, and highly flexible deployment pipeline that grows with your application’s complexity.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!