Netlify 02 ๐ Deploy Contexts & Previews โ Managing Production, Deploy Previews, and Branch deploys
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
| Context | Trigger Source | Visibility |
|---|---|---|
production | Push to Main branch | Public |
deploy-preview | Open Pull Request | Shared via PR URL |
branch-deploy | Push to any tracked branch | Unique subdomain |
dev | netlify dev CLI | Localhost |
Variable Scoping
| Scope | Definition Location | Hierarchy |
|---|---|---|
| Global | [build.environment] | Lowest |
| Context | [context.x.environment] | Medium |
| UI/Secret | Netlify Dashboard | Highest (Overrides all) |
Context Overrides
| Feature | production | deploy-preview | branch-deploy |
|---|---|---|---|
| Commands | Optimized | Debug/Dev | Staging |
| Redirects | Strict | Open | Standard |
| SEO | Indexed | No-Index | No-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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Prod DB in Preview | Default variables used | Override in [context.deploy-preview] |
| Preview indexing | Search bots crawl previews | Set X-Robots-Tag: noindex via headers |
| Configuration clash | Order of operations in TOML | Place global blocks at the top |
| Missing Env Var | Typo in context name | Verify block name matches Git branch name |
| Build script mismatch | Dependency not installed | Use 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
| Item | Value |
|---|---|
| Production context | Triggered by primary branch push |
| Preview context | Triggered by Pull Request |
| Staging context | Triggered by secondary branch |
| Override hierarchy | UI > Context > Global |
| Config file | netlify.toml |
| Security | Use UI for secret keys |
| Transience | Previews are ephemeral |
| Indexing | Use noindex for previews |
Key takeaways:
- Deploy contexts enable environment isolation. By using
[context.<name>]blocks in yournetlify.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
productioncontext 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.
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!