How to configure environment variables on Netlify
Set environment variables on Netlify using the UI (Site settings > Environment variables), CLI (<code>netlify env:set</code>), or netlify.toml; select Builds scope for build access and Functions for runtime, choose deploy contexts like Production or Branch, mark secrets appropriately, and access via <code>$VAR_NAME</code> in builds. Test locally with <code>netlify dev</code>. Import from .env files for bulk setup.
Prerequisites
- A Netlify account and site connected to a Git repository
- Netlify CLI installed via <code>npm install -g netlify-cli</code>
- Basic knowledge of your build tool and framework
- A local .env file for development (never commit secrets)
- Access to site settings in Netlify dashboard
Step-by-Step Instructions
Access Environment Variables in Netlify UI
API_KEY) and value in the respective fields.Configure Scopes for Builds and Functions
netlify.toml are not available to functions, so use UI/CLI/API for function vars.Select Deploy Contexts
staging or release/*. This ensures context-specific values.Mark Sensitive Values as Secrets and Save
Import Variables from .env File
.env file (e.g., API_KEY=secretvalue
DB_URL=connectionstring). Set uniform Scopes and Contexts for all imported vars, then submit.Set Variables via Netlify CLI
npm install -g netlify-cli), then run netlify env:set VARIABLE_NAME "value" for single vars or netlify env:import .env for files. Authenticate with netlify login and select your site.Configure via netlify.toml File
netlify.toml in repo root with context-specific vars: [env]
[env.production]
API_KEY = "prodvalue"
[env.deploy-preview]
API_KEY = "previewvalue". Commit to trigger deploy. Avoid secrets here as it's public.Access Variables in Build Commands
netlify.toml or UI build settings, use Bash syntax: [build]
command = "echo $MY_VARIABLE && npm run build". Vars are available as $VAR_NAME during builds.Test Locally with Netlify Dev
netlify dev to simulate production environment, including functions and builds. Ensure CONTEXT=dev in local .env for accurate testing.Common Issues & Troubleshooting
Variables undefined during build (e.g., API key missing error)
Verify <strong>Builds</strong> scope is selected and deploy context matches (e.g., not Production-only on Branch deploy). Edit variable and redeploy.
Functions can't access variables at runtime
Add <strong>Functions</strong> scope (UI/CLI/API only; netlify.toml unsupported). Restart functions or redeploy.
Wrong value in specific context (e.g., preview uses prod key)
Set context-specific vars or branches. Check hierarchy: .env > UI/CLI > netlify.toml.
Local dev doesn't see variables
Select <strong>Local development</strong> context in UI, use <code>netlify dev</code>, and add <code>CONTEXT=dev</code> to local .env.
Client-side frameworks (React/Next.js) can't access vars
Use framework prefixes (e.g., <code>REACT_APP_</code>) and embed in build command for bundling.