| | |

Netlify 03 ๐ŸŒ Environment Variables & Scopes โ€” Configuring context-specific values, secrets, and runtime scopes

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

Environment variables serve as the nervous system of modern web applications, facilitating the separation of sensitive configuration from source code. In a traditional server environment, these variables are often managed through .env files or system-level configuration; however, in a distributed serverless architecture like Netlify, environment variables must be managed across multiple lifecycle stages, including build-time compilation, serverless function execution, and Edge function routing. Netlify provides a centralized management system that allows developers to define these values with granular control over where and when they are exposed.

Managing these variables effectively is critical for security and environment parity. A secret used to access a production database should never be available to a pull request preview build, nor should it be accidentally bundled into a public JavaScript file during the build process. Netlify’s environment variable system handles this through “scopes” and “contexts,” ensuring that variables are only injected into the environments where they are strictly necessary. This prevents accidental credential leakage and allows a single codebase to adapt its behavior across development, staging, and production environments.

This chapter covers the creation and management of environment variables via the Netlify UI and CLI, the implementation of context-specific overrides, and the critical distinction between build-time and runtime scopes. The sections that follow walk through the configuration of sensitive secrets, the scoping of variables to specific deployment targets, and the usage of these variables within the build process and serverless functions.

Key point: Environment variables in Netlify are encrypted at rest and can be scoped to specific deployment contexts (production, branch-deploys, or previews) and runtime environments (builds, functions, or edge), providing a secure way to manage configuration without code changes.


Why X exists

The credential leakage problem. Hardcoding API keys, database credentials, or private tokens directly into source code is one of the most common security vulnerabilities. Environment variables provide a mechanism to inject these secrets into the runtime environment without ever committing them to a version control system like Git.

The environment parity problem. Applications frequently need to communicate with different backends depending on their lifecycle stage. A development build might connect to a local mock server, a preview build to a staging API, and a production build to a live database. Variables allow the application to switch endpoints dynamically based on the deployment context.

The build-time vs. runtime distinction. Some variables are only needed during the compilation phase (e.g., a Hugo or Vite optimization flag), while others are required during the execution of serverless functions (e.g., a Stripe secret key). Scoping variables prevents the build container from being cluttered with unnecessary data and limits the attack surface.

The feature flagging trade-off. Developers often use environment variables as lightweight feature flags. By changing a variable value in the Netlify dashboard and triggering a redeploy, teams can toggle application features on or off without writing new code or performing a full merge-to-main workflow.

The team collaboration friction. In a team environment, different developers might have different access levels to various third-party services. Centralizing these configurations in the Netlify dashboard ensures that every developer has access to the correct environment settings without sharing .env files manually over insecure channels.


a. Managing Variables via UI, CLI, and netlify.toml

Netlify provides three primary methods for managing environment variables. The Netlify UI (Dashboard) is the preferred method for sensitive secrets because variables entered there are encrypted at rest and never appear in the codebase. The Netlify CLI allows for rapid management and syncing of local .env files with the cloud environment. Finally, the netlify.toml file allows for configuration-as-code, though it should only be used for non-sensitive public settings.

# netlify.toml example for non-sensitive configuration
[build.environment]
  # Public build-time variable
  NODE_VERSION = "20.10.0"
  # Public feature flag
  ENABLE_BETA_UI = "true"

When using the Netlify UI, you can select specific “Scopes” for each variable. The “Builds” scope makes the variable available during the npm run build step. The “Functions” scope makes it available to Netlify Functions at runtime. The “Edge Functions” scope makes it available to the Deno-based Edge environment. Scoping a variable only to “Functions” ensures that it cannot be accidentally read by a build script and leaked into a public-facing JavaScript bundle.

For local development, the Netlify CLI command netlify dev automatically pulls variables from the cloud and injects them into your local server. This mimics the production environment perfectly, allowing you to test function logic that depends on those variables without manually maintaining a local .env file.


b. Scoping Variables to Deployment Contexts

Context-specific variables allow you to override global settings based on the type of deploy being executed. This is particularly useful for differentiating between production and staging environments. Netlify supports four main contexts: production, deploy-preview, branch-deploy, and dev.

# Overriding variables in netlify.toml per context
[context.production.environment]
  # Live production API
  API_ENDPOINT = "https://api.myapp.com"

[context.deploy-preview.environment]
  # Staging API for testing pull requests
  API_ENDPOINT = "https://staging-api.myapp.com"

In the Netlify Dashboard, you can achieve the same result with more security. When adding a variable, you can choose “All contexts” or “Specific contexts.” If you choose specific contexts, you can assign different values to the same variable key. For example, the DATABASE_URL key could have a value of db://prod for the production context and db://test for the deploy-preview context. When Netlify triggers a build for a Pull Request, it will automatically inject the db://test value, ensuring that the preview build never touches production data.


c. Build-Time vs. Runtime Variable Injection

Understanding when a variable is injected is critical for frontend developers. Variables injected during the “Builds” scope are available to the shell environment and the build tool (like Vite, Webpack, or Next.js). To use these variables in a frontend application, the build tool must explicitly “embed” them into the JavaScript code during compilation.

// Example in a React/Vite app
// These are embedded into the static JS file at build time
const apiKey = import.meta.env.VITE_APP_API_KEY;

In contrast, variables scoped to “Functions” are injected at “Runtime.” These variables are not bundled into the static assets but are available to the Node.js environment when a serverless function is invoked. This is where sensitive secrets belong. Because the client browser never downloads the serverless function code, the secrets remain hidden on the server-side.

// netlify/functions/get-data.js
exports.handler = async (event, context) => {
  // This variable is read at runtime in the cloud environment
  const secret = process.env.STRIPE_SECRET_KEY;
  // ... handle logic
};

This separation ensures that your frontend code only contains public configuration, while your backend (Functions) contains your sensitive secrets. Netlify’s “Secret Scanning” also monitors your repository to warn you if you accidentally commit a variable that should have been managed through the environment variable system.


Complete Example Session

# ============================================
# PART 1: GLOBAL BUILD CONFIG
# ============================================
[build]
  command = "npm run build"
  publish = "dist"

# ============================================
# PART 2: GLOBAL ENVIRONMENT DEFAULTS
# ============================================
[build.environment]
  # Default Node runtime for the build container
  NODE_VERSION = "20.x"
  # Public non-sensitive site setting
  SITE_LOCALE = "en-US"

# ============================================
# PART 3: PRODUCTION CONTEXT OVERRIDES
# ============================================
[context.production.environment]
  # Only production builds see this specific URL
  API_BASE_URL = "https://api.production.site"
  # Enable production-only optimizations
  COMPRESS_ASSETS = "true"

# ============================================
# PART 4: DEPLOY PREVIEW (PR) OVERRIDES
# ============================================
[context.deploy-preview.environment]
  # Previews use the staging backend
  API_BASE_URL = "https://api.staging.site"
  # Disable heavy optimizations for faster PR builds
  COMPRESS_ASSETS = "false"

# ============================================
# PART 5: CLI SYNCING (DASHBOARD)
# ============================================
# Note: Sensitive variables like STRIPE_KEY or DB_PASSWORD
# should be added via the Netlify Dashboard UI, NOT here.

# ============================================
# PART 6: SERVERLESS FUNCTION (NODE.JS)
# ============================================
# netlify/functions/hello.js
# exports.handler = async () => {
#   const key = process.env.SENSITIVE_API_KEY; // Read from Dashboard
#   return { statusCode: 200, body: "Success" };
# };

# ============================================
# PART 7: VITE FRONTEND (BUILD-TIME)
# ============================================
# .env.production
# VITE_PUBLIC_VAR=hello_world
# (Vite only embeds vars prefixed with VITE_)

# ============================================
# PART 8: BRANCH-SPECIFIC CONTEXT
# ============================================
[context.next-version.environment]
  # Settings for a specific long-lived feature branch
  FEATURE_EXPERIMENTAL_UI = "true"

# ============================================
# PART 9: REDIRECTS WITH VARS
# ============================================
[[redirects]]
  from = "/api/*"
  to = "https://external-service.com/:splat"
  status = 200
  # Note: Netlify does not support env vars inside redirects in TOML
  # unless using an Edge Function to proxy.

# ============================================
# PART 10: LOCAL DEV EXECUTION
# ============================================
# Run 'netlify dev' in terminal
# It merges local .env with Netlify Dashboard variables.

The session above illustrates how variables move from global defaults to context-specific overrides, and how they are consumed by both build scripts and serverless functions.


Quick Reference

Variable Management Methods

MethodBest ForSecurity LevelPersisted In
Netlify UISecrets/API KeysHigh (Encrypted)Netlify DB
netlify.tomlBuild ConfigLow (Public)Git Repo
Netlify CLILocal Dev / CIMediumLocal Machine
.env fileLocal OverridesLowLocal (Ignored)

Variable Scopes

ScopeInjected IntoLanguageExample Use
BuildsBuild ContainerNode/Go/Pythonnpm run build
FunctionsLambda RuntimeNode/GoAPI Credentials
EdgeEdge NetworkDeno / JSGeo-routing keys

Built-in Reserved Variables

VariableDescriptionValue Example
CONTEXTCurrent deploy typeproduction
URLMain site URLhttps://mysite.com
DEPLOY_URLUnique deploy URLhttps://65a1...--site.com
COMMIT_REFGit SHAa7d2f9...

Best Practices

โœ… Do This:

// Use serverless functions for sensitive API calls
const secret = process.env.API_KEY;                           // โœ…
// Scope variables to "Functions" only in the UI
// Use netlify.toml for versioning build settings
NODE_VERSION = "20.10.0"                                      // โœ…
// Use different values for production vs staging
[context.production.environment]                              // โœ…
// Use 'netlify dev' to test variables locally
// Prefix frontend variables if required by your framework (e.g., VITE_)

โŒ Don’t Do This:

// Hardcode secrets in your JS files
const apiKey = "12345-secret-key";                            // โŒ
// Put sensitive database passwords in netlify.toml
DB_PASS = "admin123"                                          // โŒ
// Commit your .env file to GitHub
// Assume variables in netlify.toml are secret
// Use build-time variables for runtime secrets

Common Pitfalls

PitfallWhy It HappensFix
Variables not in frontendVariables not prefixed (e.g. VITE_)Add required prefix for build tool
Local dev missing varsNot using netlify devUse CLI to pull cloud variables
Deploy Preview failsVariables not scoped to “Previews”Update scope in Netlify UI settings
Functions can’t see varsScoped only to “Builds”Change scope to “All” or “Functions”
Stale values in buildValues changed but not redeployedTrigger “Clear cache and deploy site”
committed secretsAdding secrets to netlify.tomlMove secrets to Netlify UI and purge Git history

Real-World Examples

1. Pinning Node version

[build.environment]
NODE_VERSION = "20.x"

2. Switching API URL for PRs

[context.deploy-preview.environment]
API_URL = "https://dev.api.example.com"

3. Using Vite environment variables

const url = import.meta.env.VITE_BACKEND_URL;

4. Reading secret in Netlify Function

const key = process.env.STRIPE_SECRET_KEY;

5. CLI: List all variables

netlify env:list

6. CLI: Set a variable

netlify env:set MY_VAR value

7. Disabling build cache via var

[build.environment]
NETLIFY_SKIP_BUILD_CACHE = "true"

8. Context-aware feature flag

[context.production.environment]
SHOW_ADS = "true"

9. Setting timezone for builds

[build.environment]
TZ = "America/New_York"

10. Local dev with specific context

netlify dev --context deploy-preview

Visual

Variable Scoping Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ NETLIFY VARIABLE SCOPING                                โ”‚
โ”‚                                                         โ”‚
โ”‚  [ UI DASHBOARD ] โ”€โ”€โ”€โ”ฌโ”€โ”€โ–บ Builds (Shell Environment)    โ”‚
โ”‚    (Encrypted)       โ”œโ”€โ”€โ–บ Functions (Runtime Node.js)   โ”‚
โ”‚                      โ””โ”€โ”€โ–บ Edge (Deno Runtime)           โ”‚
โ”‚                                                         โ”‚
โ”‚  [ netlify.toml ] โ”€โ”€โ”€โ–บ Builds Only (Public)             โ”‚
โ”‚    (Git Versioned)                                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Context Overriding Logic

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ CONTEXT OVERRIDES                                       โ”‚
โ”‚                                                         โ”‚
โ”‚  Global Settings: API_KEY = "111"                       โ”‚
โ”‚                                                         โ”‚
โ”‚  Trigger: Pull Request (Deploy Preview)                 โ”‚
โ”‚    Is there an override for [deploy-preview]?           โ”‚
โ”‚    YES โ”€โ”€โ–บ Inject "222"                                 โ”‚
โ”‚                                                         โ”‚
โ”‚  Trigger: Main Branch Push (Production)                 โ”‚
โ”‚    Is there an override for [production]?               โ”‚
โ”‚    NO  โ”€โ”€โ–บ Inject Global "111"                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Local Development Sync

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ LOCAL SYNC (netlify dev)                                โ”‚
โ”‚                                                         โ”‚
โ”‚  Cloud Vars (Netlify) โ”€โ”€โ”                               โ”‚
โ”‚                         โ”‚                               โ”‚
โ”‚  Local .env File      โ”€โ”€โ”ผโ”€โ”€โ–บ Merged Runtime Environment โ”‚
โ”‚                         โ”‚                               โ”‚
โ”‚  netlify.toml Vars    โ”€โ”€โ”˜                               โ”‚
โ”‚                                                         โ”‚
โ”‚  (Secrets never saved to disk, only held in memory)     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
EncryptionEncrypted at rest (UI variables)
PriorityUI > Context-TOML > Global-TOML
VisibilityTOML is public; UI is private
Local ToolNetlify CLI (netlify dev)
ScopesBuilds, Functions, Edge
ContextsProduction, Preview, Branch, Dev
Limit1000 variables per site
Max Size64KB per variable

Key takeaways:

  • Use the Netlify UI for secrets. Variables added via the dashboard are encrypted and can be strictly scoped to prevent them from being exposed to the client-side build or unauthorized branches.
  • Differentiate between Build-time and Runtime. Build-time variables are for compilers (like Vite), while Runtime variables are for Serverless Functions. Scoping variables correctly minimizes security risks.
  • Leverage contexts for environment parity. Use context overrides in netlify.toml or the UI to point your application to different APIs for production versus pull request previews.
  • Frameworks require specific prefixes. Most modern frontend tools (Vite, Next.js) will ignore environment variables during the build unless they are prefixed (e.g., VITE_ or NEXT_PUBLIC_).
  • Test locally with the CLI. netlify dev is the essential tool for testing how your environment variables will behave in production without actually deploying.

Remember: Environment variables are the boundary between your code and your infrastructure. By correctly using scopes and contexts, you ensure that your application remains secure, your secrets remain hidden, and your development workflow remains consistent across all stages of the deployment pipeline.

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!