| | |

Netlify 02 ๐ŸŒ Deploy Contexts & Previews โ€” Managing Production, Deploy Previews, and Branch deploys

โฑ๏ธ Estimated read: 9 min | |

Netlify operates on an event-driven model where the lifecycle of a codebase is segmented into discrete, configurable states. These states, known as “Deploy Contexts,” allow developers to alter build commands, environment variables, HTTP headers, and redirect rules dynamically based on the Git event that triggered the deployment. By categorizing builds into specific contextsโ€”such as production, pull request previews, and branch-specific deploymentsโ€”developers can enforce environment parity without managing multiple, disjointed infrastructure configurations.

Deploy contexts act as an inheritance chain within the netlify.toml file, where global settings provide a baseline and context-specific blocks provide the overrides. This modular architecture is essential for modern frontend workflows, where the requirements for a high-performance production build differ significantly from the requirements for an ephemeral, debug-enabled preview build created during a code review process.

This chapter details the mechanics of context management, the logical flow of build triggers, and the strict scoping rules for environment variables. The sections that follow define the primary context types, demonstrate how to implement context-specific overrides in configuration files, and illustrate how these configurations dictate the behavior of your deployment pipeline.

Key point: Deploy contexts are the primary mechanism for differentiating configuration, environment variables, and build behaviors based on the specific Git-triggered lifecycle event; production builds represent the immutable source of truth, deploy-previews provide transient environments for review, and branch-deploys facilitate persistent staging.


Why X exists

The “one size fits all” configuration problem. Applications often require different compilation steps for development, staging, and production. Without context awareness, developers are forced to hard-code environment checks inside build scripts (like if (process.env.NODE_ENV === 'production')), which bloats the client-side bundle and exposes configuration logic.

The “manual staging environment” problem. Before context-aware previews, teams had to maintain separate servers or infrastructure-as-code pipelines for staging and QA. Managing these environments independently leads to “configuration drift,” where the staging environment behaves differently than production due to subtle discrepancies in setup or dependencies.

The “environment variable leakage” problem. Storing production secrets (like API keys or database URLs) alongside staging secrets in a single global configuration file is a significant security risk. Contexts allow for strict scoping, ensuring that only the relevant variables are injected into the build container based on the deployment target.

The “testing in production” safety problem. Deploying unstable features directly to the production branch creates user-facing instability. Contexts enforce a workflow where code must traverse through specific deployment lifecycle phasesโ€”from branch-specific testing to pull request reviewโ€”before ever reaching the production context.

The “temporary infrastructure” management problem. Creating and destroying infrastructure for every pull request is operationally expensive. Netlify contexts solve this by providing ephemeral, URL-based preview environments that are automatically provisioned and garbage-collected, removing the need for manual infrastructure management.


a. Defining Contexts in netlify.toml

Netlify categorizes every deployment into a specific context: production, deploy-preview, branch-deploy, or dev. You define these within the netlify.toml file using the [context.<name>] syntax. Settings defined in these blocks override the global settings, allowing you to tailor the behavior of your CI/CD pipeline per scenario.

# Global settings apply to all contexts
[build]
  command = "npm run build"
  publish = "dist"

# Production context overrides
[context.production]
  command = "npm run build:prod" # Optimized, minified production build

# Pull Request preview overrides
[context.deploy-preview]
  command = "npm run build:preview" # Faster build with sourcemaps enabled

The build system evaluates these blocks hierarchically. It first loads the global [build] settings and then merges the settings from the matching [context] block. If a property is defined in both the global block and the context block, the context block takes precedence. This merging behavior is atomic and happens at the start of the build process.

b. The Anatomy of Triggered Contexts

Each context is tied to specific Git activity. The production context is triggered by pushes to the primary branch (usually main or master). This is the only context that serves traffic to the primary production domain. The system ensures that only code that has been successfully merged into the primary branch enters this state, guaranteeing that the live site remains stable.

# Staging branch configuration
[context.staging]
  command = "npm run build:staging"
  [context.staging.environment]
    API_URL = "https://staging.api.example.com"

The deploy-preview context is unique; it is ephemeral and generated automatically whenever a pull request is opened or updated. Netlify assigns a unique, temporary URL to every preview, such as https://deploy-preview-123--yoursite.netlify.app. These are transient; once the PR is closed or merged, the preview environment is eventually decommissioned. The branch-deploy context is used for any other branch you explicitly track, allowing for persistent staging environments (e.g., a staging branch that always points to staging.yoursite.com).

c. Scoping Environment Variables

Environment variables are the most sensitive part of context management. You can define variables in the Netlify UI or within netlify.toml. When defined in the [context.<name>.environment] block, the variable is scoped strictly to that context. This prevents sensitive production credentials from leaking into preview environments.

[context.production.environment]
  DB_API_KEY = "prod_secret_key_dont_leak" # Accessible only in production

[context.deploy-preview.environment]
  DB_API_KEY = "mock_test_key" # Accessible only in preview builds

It is a best practice to define non-sensitive build-time configuration variables (like API_URL or FEATURE_FLAGS) in netlify.toml and leave sensitive, secret keys (like STRIPE_SECRET) in the Netlify UIโ€™s “Environment Variables” section. The UI-defined variables override the file-defined ones, providing a secondary layer of security where the most critical credentials are never committed to the source code repository.


Complete Example Session

# ============================================
# PART 1: GLOBAL BUILD DEFAULTS
# ============================================
[build]
  command = "npm run build"
  publish = "dist"
  functions = "netlify/functions"

# ============================================
# PART 2: PRODUCTION CONTEXT
# ============================================
[context.production]
  command = "npm run build:prod"
  [context.production.environment]
    NODE_ENV = "production"
    API_URL = "https://api.example.com"

# ============================================
# PART 3: DEPLOY PREVIEW CONTEXT
# ============================================
[context.deploy-preview]
  command = "npm run build:dev"
  [context.deploy-preview.environment]
    NODE_ENV = "development"
    API_URL = "https://sandbox.api.example.com" # Points to test API

# ============================================
# PART 4: STAGING BRANCH CONTEXT
# ============================================
[context.staging]
  command = "npm run build:staging"
  [context.staging.environment]
    NODE_ENV = "staging"
    API_URL = "https://staging.api.example.com"

# ============================================
# PART 5: REDIRECTS BY CONTEXT
# ============================================
[[context.production.redirects]]
  from = "/admin/*"
  to = "/forbidden"
  status = 403 # Secure admin panel in production

# ============================================
# PART 6: SHARED REDIRECTS (GLOBAL)
# ============================================
[[redirects]]
  from = "/api/*"
  to = "https://backend.example.com/:splat"
  status = 200

# ============================================
# PART 7: CUSTOM HEADER OVERRIDES
# ============================================
[[context.production.headers]]
  for = "/*"
  [context.production.headers.values]
    Strict-Transport-Security = "max-age=63072000; includeSubDomains; preload"

# ============================================
# PART 8: EDGE FUNCTION HANDLERS
# ============================================
[[edge_functions]]
  path = "/geo"
  function = "geo-handler"

# ============================================
# PART 9: BRANCH DEPLOY PROTECTION
# ============================================
[context.branch-deploy]
  [context.branch-deploy.environment]
    NO_INDEX = "true" # Prevent SEO crawlers on branch deploys

# ============================================
# PART 10: BUILD SETTINGS FINALIZATION
# ============================================
[build.environment]
  NPM_VERSION = "10.0.0" # Global default

The example above demonstrates a layered configuration where global defaults provide the structure, and context-specific blocks specialize that structure for production, previews, staging, and branch deployments.


Quick Reference

Context Trigger Events

ContextTrigger SourceVisibility
productionPush to Main branchPublic
deploy-previewOpen Pull RequestShared via PR URL
branch-deployPush to any tracked branchUnique subdomain
devnetlify dev CLILocalhost

Variable Scoping

ScopeDefinition LocationHierarchy
Global[build.environment]Lowest
Context[context.x.environment]Medium
UI/SecretNetlify DashboardHighest (Overrides all)

Context Overrides

Featureproductiondeploy-previewbranch-deploy
CommandsOptimizedDebug/DevStaging
RedirectsStrictOpenStandard
SEOIndexedNo-IndexNo-Index

Best Practices

โœ… Do This:

# Use clear names for context staging
[context.staging]                                              # โœ…

# Explicitly set NO_INDEX for non-production contexts
[context.deploy-preview.environment]
  NO_INDEX = "true"                                            # โœ…

# Override API endpoints per context
API_URL = "https://prod.api.com"                               # โœ…

# Keep the global build block lean
[build]
  publish = "dist"                                             # โœ…

โŒ Don’t Do This:

# Don't put sensitive keys in netlify.toml
SECRET_KEY = "12345"                                           # โŒ

# Don't use production APIs in preview contexts
API_URL = "https://prod.api.com" # Should be sandbox            # โŒ

# Don't try to override global functions path in contexts
# Functions path must be global                                # โŒ

# Don't use deploy-previews for long-term storage
# They are ephemeral                                           # โŒ

Common Pitfalls

PitfallWhy It HappensFix
Prod DB in PreviewDefault variables usedOverride in [context.deploy-preview]
Preview indexingSearch bots crawl previewsSet X-Robots-Tag: noindex via headers
Configuration clashOrder of operations in TOMLPlace global blocks at the top
Missing Env VarTypo in context nameVerify block name matches Git branch name
Build script mismatchDependency not installedUse build.command to install specific deps

Real-World Examples

1. Production build command

[context.production]
  command = "npm run build:prod"

2. Preview build command

[context.deploy-preview]
  command = "npm run build:dev"

3. Staging variable injection

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

4. Disabling SEO for previews

[context.deploy-preview.environment]
  NO_INDEX = "true"

5. Redirecting admin in production

[[context.production.redirects]]
  from = "/admin"
  to = "/login"

6. Custom headers for production security

[[context.production.headers]]
  for = "/*"
  [context.production.headers.values]
    Content-Security-Policy = "..."

7. Global Node version enforcement

[build.environment]
  NODE_VERSION = "20"

8. Staging branch specific subdomains

# Netlify auto-handles, but use context to verify
[context.staging]
  publish = "dist/staging"

9. Disabling Netlify Identity in local dev

[context.dev.environment]
  IDENTITY_MOCK = "true"

10. Forcing HTTPS redirects in production

[[context.production.redirects]]
  from = "http://*"
  to = "https://:splat"
  status = 301

Visual

Context Hierarchy and Overrides

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ CONFIGURATION HIERARCHY                                 โ”‚
โ”‚                                                         โ”‚
โ”‚ 1. Global Defaults [build] โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                 โ”‚
โ”‚                                       โ”‚                 โ”‚
โ”‚ 2. Context Specific [context.x] โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€ Overrides     โ”‚
โ”‚                                       โ”‚                 โ”‚
โ”‚ 3. UI/Secret Variables (Dashboard) โ”€โ”€โ”€โ”ดโ”€โ”€ Top Priority  โ”‚
โ”‚                                                         โ”‚
โ”‚ Result: Merged Config โ†’ Build Container                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Lifecycle of a Pull Request Preview

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ DEPLOY PREVIEW FLOW                                     โ”‚
โ”‚                                                         โ”‚
โ”‚ Git Push (Branch X) โ”€โ”€โ–บ PR Created โ”€โ”€โ–บ Trigger Build    โ”‚
โ”‚                                                         โ”‚
โ”‚ Build Context: [context.deploy-preview]                 โ”‚
โ”‚                                                         โ”‚
โ”‚ Result: Unique URL (https://deploy-preview-N...)        โ”‚
โ”‚                                                         โ”‚
โ”‚ PR Merged โ”€โ”€โ–บ Destroy Preview Environment               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Environment Variable Scoping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ SCOPING LOGIC                                           โ”‚
โ”‚                                                         โ”‚
โ”‚ Production Context  โ”‚  Deploy Preview Context           โ”‚
โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€           โ”‚
โ”‚ API=prod.api.com    โ”‚  API=sandbox.api.com              โ”‚
โ”‚ DB=true             โ”‚  DB=false                         โ”‚
โ”‚                     โ”‚                                   โ”‚
โ”‚ (Variables never leak across these boundaries)          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Production contextTriggered by primary branch push
Preview contextTriggered by Pull Request
Staging contextTriggered by secondary branch
Override hierarchyUI > Context > Global
Config filenetlify.toml
SecurityUse UI for secret keys
TransiencePreviews are ephemeral
IndexingUse noindex for previews

Key takeaways:

  • Deploy contexts enable environment isolation. By using [context.<name>] blocks in your netlify.toml, you define specific build behaviors, redirects, and headers for different stages of the development lifecycle.
  • Environment variables must be scoped. Always define context-specific variables within the context block to ensure production secrets do not leak into preview environments.
  • Production is the immutable source of truth. The production context should always be reserved for the main branch, ensuring stable code delivery to end-users.
  • Deploy previews are powerful review tools. These ephemeral environments allow teams to test features in isolation, with specific build configurations, before merging code.
  • Config order matters. Global settings provide the base, while context-specific settings apply the necessary overrides for production or staging scenarios.

Remember: Context management is the blueprint for a reliable CI/CD pipeline. By meticulously defining the differences between your production environment and your ephemeral preview/staging environments within netlify.toml, you eliminate configuration drift, enhance security, and create a scalable deployment strategy that safely guides code from development to production.

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!