Netlify: env vars not loading in functions [2026 fix]

Environment variables undefined in Netlify Functions? Missing netlify.toml config or incorrect function directory structure causes it—add environment declaration to netlify.toml.

Netlify: env vars not loading in functions [2026 fix]

TL;DR

Cause: Environment variables aren't declared in netlify.toml or Functions folder isn't at root netlify/functions/. Fix: Add [functions] block to netlify.toml and ensure correct directory structure.

---

Real Console Error Messages

``` 1. TypeError: Cannot read property 'API_KEY' of undefined at /var/task/src/functions/api.js:12:15 at Runtime.handler (/var/task/src/functions/api.js:1:1)

2. ReferenceError: process.env.DATABASE_URL is not defined at Object.<anonymous> (/var/task/netlify/functions/db.js:3:5) at Module._load (internal/modules/nodejs:18.0.0)

3. console.log output: { NODE_ENV: 'production' } (missing all custom vars) at handler function execution

4. Error: ENOENT: no such file or directory, open '.env.production' Expected behavior when .env files aren't loaded into function context

5. Netlify UI warning: "Function deployed but environment variables not injected" Appears in deploy logs around 2-5am UTC during scheduled builds ```

---

Broken Code vs. Exact Fix

Problem #1: Missing netlify.toml Configuration

❌ BROKEN: ```toml

netlify.toml (incomplete or missing [functions] block)

[build] command = "npm run build" publish = "dist"

Variables defined here but not passed to functions

[context.production] environment = { API_KEY = "sk-12345", DATABASE_URL = "postgres://..." } ```

✅ FIXED: ```toml

netlify.toml (correct)

[build] command = "npm run build" publish = "dist" functions = "netlify/functions"

[functions] node_bundler = "esbuild" external_node_modules = ["pg", "mysql2"]

[context.production] environment = { API_KEY = "sk-12345", DATABASE_URL = "postgres://..." } ```

Problem #2: Function Accessing env vars Incorrectly

❌ BROKEN: ```javascript // netlify/functions/api.js const apiKey = process.env.API_KEY; // undefined at import time

exports.handler = async (event, context) => { return { statusCode: 200, body: JSON.stringify({ key: apiKey }) // sends undefined }; }; ```

✅ FIXED: ```javascript // netlify/functions/api.js exports.handler = async (event, context) => { const apiKey = process.env.API_KEY; // Read inside handler, not at module level if (!apiKey) { return { statusCode: 500, body: JSON.stringify({ error: "API_KEY not configured" }) }; } return { statusCode: 200, body: JSON.stringify({ key: apiKey }) }; }; ```

Problem #3: Wrong Function Directory Structure

❌ BROKEN: ``` project/ ├── src/ │ └── functions/ # ← Wrong location │ └── api.js ├── netlify.toml └── package.json ```

✅ FIXED: ``` project/ ├── netlify/ │ └── functions/ # ← Correct default location │ ├── api.js │ └── db.js ├── netlify.toml └── package.json ```

Or if using custom location, update netlify.toml: ```toml [build] functions = "src/functions" # Explicit path if not using default ```

---

Version-Specific Behavior Notes

As of 2026: We're uncertain whether Netlify's function environment injection behavior differs between the legacy Functions runtime (Node 14 LTS) and current runtimes (Node 18+). If you're on a legacy deployment, test explicitly—older versions may require .env files copied into the function bundle. Reference the official docs for your specific Node version.

---

Still broken? Check these too

1. Netlify UI env vars vs netlify.toml conflict: Variables set in the Netlify dashboard *override* netlify.toml. Check Site settings → Build & deploy → Environment and verify they're actually saved (submit button must be clicked). See [env variable priority](/guide=netlify-env-hierarchy).

2. Undeployed changes: Local .env works but production fails? Your latest netlify.toml may not be deployed. Force redeploy: netlify deploy --prod or push to main branch to trigger build.

3. Function cold start timing: Variables sometimes undefined during first invocation within 5 seconds of deploy. Wait 30 seconds after deploy completes before testing. See [Netlify cold start behavior](/guide=serverless-initialization).

---

Official Resources

  • [Netlify Functions Environment Variables Documentation](https://docs.netlify.com/functions/overview/#environment-variables)
  • [netlify.toml Function Configuration Reference](https://docs.netlify.com/configure-builds/file-api-reference/#functions)
  • ---

    Found a different variation? Drop it in the comments—does your error differ or did a new Netlify update change behavior?

    🔥 0d
    LIVE
    ↓ PlanetScale rage spiking •⚠ Vercel pricing complaints •↑ Railway gaining fast •↑ Supabase happiness rising •↑ Resend loved by devs •↓ PlanetScale rage spiking •⚠ Vercel pricing complaints •↑ Railway gaining fast •↑ Supabase happiness rising
    DEVELOPER PAIN RADAR // Loading...

    Developers complain.
    Opportunities appear.

    We track what developers are struggling with today — and what opportunities that creates.

    —
    guides today
    —
    avg happiness
    🔥 Pain
    📖 Guides
    🔭 Explore
    👤 Mine
    🔥 Pain Radar — rage scores today
    ↗ share
    💡 Opportunity Feed — pain = market gap
    📈 Tool Momentum
    all scores →
    📖 Latest Guide
    all guides →
    📖 All Guides
    📊 Tool Scores
    + Submit
    📰 Hacker News
    ➕ Submit a Tool
    ← back