Netlify: env vars not loading in functions [2026 fix]
Netlify functions can't access env vars because they're not deployed to the functions folder or netlify.toml is misconfigured.
Netlify: env vars not loading in functions [2026 fix]
TL;DR
Cause: Environment variables defined in Netlify UI aren't automatically injected into serverless functions unless they're explicitly configured in netlify.toml or the functions are in the correct directory.
Fix: Add your function directory and env vars to netlify.toml, then redeploy—variables won't load in existing deployments.
---
Real Console Error Messages
Here are exact errors you'll see at 2am:
``` 1. TypeError: Cannot read property 'API_KEY' of undefined at Object.<anonymous> (/var/task/index.js:12:45) at Module._load (internal/modules/esm_loader.js:569:15) ```
``` 2. ReferenceError: process.env.DATABASE_URL is not defined at exports.handler (/var/task/netlify/functions/api.js:5:8) ```
``` 3. Error: Missing required environment variable: STRIPE_KEY at initializeStripe (file:///var/task/handler.mjs:23:4) ```
``` 4. [Function] Error: env var 'NEXT_PUBLIC_API_URL' loaded as undefined Stack trace at runtime (200 response but broken data) ```
``` 5. Failed to load serverless function: process.env is null Deployment succeeded but function invocation failed ```
---
Broken Code vs. Fix
Problem 1: Missing netlify.toml Configuration
BROKEN: ```toml
netlify.toml (incomplete)
[build] command = "npm run build" publish = "dist"Functions defined in UI only—NOT accessible in function code
```FIXED: ```toml
netlify.toml (correct)
[build] command = "npm run build" publish = "dist" functions = "netlify/functions"[[env]] context = "production" [env.production.environment] API_KEY = "your-key-here" DATABASE_URL = "postgres://..." STRIPE_SECRET_KEY = "sk_live_..." ```
Problem 2: Function Accessing Variables Incorrectly
BROKEN: ```javascript // netlify/functions/api.js exports.handler = async (event, context) => { // ❌ Trying to access undefined object const apiKey = process.env.API_KEY; // Returns undefined const dbUrl = process.env.DATABASE_URL; // Returns undefined return { statusCode: 200, body: JSON.stringify({ apiKey, dbUrl }) // Both null }; }; ```
FIXED: ```javascript // netlify/functions/api.js exports.handler = async (event, context) => { // ✅ Explicitly check and validate const apiKey = process.env.API_KEY; const dbUrl = process.env.DATABASE_URL; if (!apiKey || !dbUrl) { return { statusCode: 500, body: JSON.stringify({ error: "Missing environment variables", missing: [ !apiKey && 'API_KEY', !dbUrl && 'DATABASE_URL' ].filter(Boolean) }) }; } return { statusCode: 200, body: JSON.stringify({ success: true, keyLoaded: !!apiKey }) }; }; ```
Problem 3: Wrong Deployment Trigger
BROKEN: ```bash
❌ Just changing env vars in UI without redeploying
git push # Old deployment still active, new vars ignored ```FIXED: ```bash
✅ Always redeploy after env var changes
git push # Triggers new buildOR manually trigger via Netlify UI: Site settings > Deploys > Trigger deploy
```---
Critical Implementation Notes
Important: We're uncertain whether Netlify auto-injects UI-defined variables into functions in all 2026 versions. Test locally with netlify dev before production push.
netlify.toml environment variables take precedence over UI settingsNEXT_PUBLIC_* prefix is for Next.js frontend only—functions need unprefixed vars---
Still broken? Check these too
1. Functions in wrong directory: Netlify searches netlify/functions/ by default. If yours are in functions/ or .netlify/functions/, update the functions path in netlify.toml.
2. Context mismatch: You set production env vars but deployed to preview/staging. Use [[env.preview]] or [[env.branch-deploy]] blocks in netlify.toml for non-production contexts.
3. Secrets exposed in logs: Never commit netlify.toml with real API keys. Use Netlify UI for sensitive values, then reference in netlify.toml as ${API_KEY} only if absolutely necessary (prefer UI-only storage).
---
Verification
Test locally before pushing: ```bash netlify dev # Runs functions with env vars loaded curl http://localhost:8888/.netlify/functions/api ```
Check deployed function: ```bash curl https://yoursite.netlify.app/.netlify/functions/api ```
---
Related Resources
---
Found a different variation? Drop it in the comments—especially if you hit this with Deno functions or edge functions, which have different env var handling.