Netlify: env vars not loading in functions [2026 fix]
Env vars undefined in Netlify Functions because they're not published to the functions build context. Deploy with netlify.toml configured.
Netlify: env vars not loading in functions [2026 fix]
TL;DR
Cause: Environment variables set in Netlify UI aren't automatically available to serverless functions unless explicitly configured innetlify.toml or .env files.
Fix: Add environment context to your netlify.toml and redeploy, or use process.env with proper scoping in your function files.---
Real Console Error Messages
Here are exact errors you'll see at 2am:
``` Error: Cannot read property 'DATABASE_URL' of undefined at /var/task/functions/api.js:12:15 ```
``` ReferenceError: process is not defined at Runtime.handler (/var/task/lambda/query.js:45:8) ```
``` TypeError: Cannot read properties of undefined (reading 'API_KEY') at Object.<anonymous> (/var/task/functions/stripe-webhook.js:3:5) ```
``` fetch failed: Error: getaddrinfo ENOTFOUND api.example.com (env var with API endpoint is undefined) ```
``` Warning: environment variable REACT_APP_PUBLIC_KEY not available during build ```
---
The Problem: Broken vs. Fixed Code
❌ BROKEN: No netlify.toml Configuration
netlify.toml (missing or incomplete): ```toml [build] command = "npm run build" publish = "dist" ```
functions/api.js: ```javascript exports.handler = async (event) => { // ❌ This will be undefined at runtime const dbUrl = process.env.DATABASE_URL; const apiKey = process.env.API_KEY; console.log(dbUrl); // logs undefined return { statusCode: 500 }; }; ```
✅ FIXED: Explicit Environment Configuration
netlify.toml (CORRECT): ```toml [build] command = "npm run build" publish = "dist"
[functions] node_bundler = "esbuild"
[[redirects]] from = "/api/*" to = "/.netlify/functions/:splat" status = 200
[context.production] environment = { DATABASE_URL = "postgres://...", API_KEY = "sk_live_..." }
[context.deploy-preview] environment = { DATABASE_URL = "postgres://staging...", API_KEY = "sk_test_..." } ```
functions/api.js (CORRECT):
```javascript
exports.handler = async (event) => {
// ✅ Now properly injected at function runtime
const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;
if (!dbUrl || !apiKey) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Missing environment variables' })
};
}
console.log(Connecting to ${dbUrl});
return { statusCode: 200, body: JSON.stringify({ success: true }) };
};
```
Alternative: Using .env.production file ```bash
.env.production (commit-safe, or use .gitignore)
DATABASE_URL=postgres://user:pass@host/db API_KEY=sk_live_abc123def456 ```Then in netlify.toml:
```toml
[build]
command = "npm run build"
```
Netlify auto-loads .env.production during the build.
---
Why This Happens
1. UI env vars only apply to build time (pre-rendering, static generation) 2. Functions run in Lambda isolation – they don't inherit the build environment unless explicitly passed 3. Context matters – production, preview, and dev have separate env scopes 4. Timing issue – variables must be set BEFORE deployment, not after
---
Step-by-Step Fix (Right Now)
1. Check Netlify dashboard: Site Settings → Environment Variables. Verify vars exist.
2. Update netlify.toml: Add explicit [context.production] environment block (see above).
3. For secrets: Use Netlify UI to set them, ensure netlify.toml references by name.
4. Redeploy: Push to main branch or manually trigger deploy (don't rebuild – redeploy).
5. Test function: Call your function endpoint and check CloudWatch logs.
---
Still broken? Check these too
Issue #1: Secrets not masked in logs
If you seeAPI_KEY=undefined in logs, your env var name is misspelled in netlify.toml. Check case sensitivity (they're case-sensitive).Issue #2: Functions work locally but fail on Netlify
You're using.env locally (which works), but Netlify functions don't read .env at runtime. Use netlify dev to test with actual Netlify environment setup: npm install -g netlify-cli && netlify dev.Issue #3: Cold starts and slow function initialization
Environment variables load fresh per invocation. If you have large secrets, consider using [AWS Secrets Manager integration](/?guide=netlify-secrets-manager) or [Parameter Store](/?guide=aws-parameter-store).---
Version Notes
I'm uncertain whether Netlify will fully auto-parse .env files in all 2026 runtimes – the safest approach remains explicit netlify.toml configuration. The esbuild bundler (set via node_bundler = "esbuild") has different tree-shaking behavior than the older zisi – verify your environment config works by checking build logs.
---
Official Resources
---
Found a different variation? Drop it in the comments.