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 silent failures.

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

TL;DR

Cause: Netlify Functions aren't reading env vars because your netlify.toml doesn't declare the functions directory OR env vars aren't properly exposed to the function runtime.

Fix: Add functions = "netlify/functions" to netlify.toml and ensure env vars are set in Netlify UI (Settings > Build & Deploy > Environment) OR committed to .env file during build.

---

Real Console Error Messages

``` 1. TypeError: Cannot read property 'API_KEY' of undefined at Object.<anonymous> (/var/task/netlify/functions/api.js:5:15)

2. ReferenceError: process is not defined at eval (/var/task/netlify/functions/fetch-data.js:8:7)

3. Error: STRIPE_SECRET_KEY environment variable not set at requireSecret (/var/task/node_modules/.../stripe.js:42:1)

4. [Functions] Error in function : TypeError: process.env.DATABASE_URL is undefined at connectDB (/var/task/netlify/functions/database.js:12:3)

5. Build error: functions directory not found. Looked in: netlify/functions, functions, .netlify/functions ```

---

The Problem: Code Comparison

❌ BROKEN CODE

netlify.toml (missing or incomplete): ```toml [build] command = "npm run build" publish = "dist" ```

netlify/functions/api.js: ```javascript const API_KEY = process.env.API_KEY; const DB_URL = process.env.DATABASE_URL;

exports.handler = async (event) => { console.log("API Key:", API_KEY); // logs: undefined return { statusCode: 500, body: JSON.stringify({ error: "Env vars missing" }) }; }; ```

---

✅ FIXED CODE

netlify.toml (CORRECTED): ```toml [build] command = "npm run build" publish = "dist" functions = "netlify/functions"

[[redirects]] from = "/api/*" to = "/.netlify/functions/:splat" status = 200 ```

netlify/functions/api.js (same code, now works): ```javascript const API_KEY = process.env.API_KEY; const DB_URL = process.env.DATABASE_URL;

exports.handler = async (event) => { if (!API_KEY || !DB_URL) { return { statusCode: 500, body: JSON.stringify({ error: "Env vars not configured" }) }; } console.log("API Key:", API_KEY); // logs: actual value return { statusCode: 200, body: JSON.stringify({ success: true }) }; }; ```

Environment Setup (Netlify UI): 1. Go to your Netlify site dashboard 2. Click SettingsBuild & DeployEnvironment 3. Add new environment variables: - Key: API_KEY → Value: your_actual_key - Key: DATABASE_URL → Value: your_db_connection_string 4. Redeploy your site

---

Version-Specific Notes

⚠️ Important: As of 2026, Netlify Functions support both CommonJS (exports.handler) and ES modules (export const handler). We're uncertain whether all legacy Node 14 bundling behavior persists—if you're targeting older runtimes, test locally with netlify functions:invoke first.

If using TypeScript, ensure your tsconfig.json has "esModuleInterop": true to avoid require/import conflicts.

---

Verification Checklist

1. File structure is correct: ``` project-root/ ├── netlify.toml ├── netlify/ │ └── functions/ │ ├── api.js │ └── fetch-data.js └── package.json ```

2. netlify.toml contains functions directive: ```bash grep "functions =" netlify.toml ```

3. Env vars exist in Netlify UI or build env: ```bash # Local test (create .env file for local dev only) echo "API_KEY=test123" > .env netlify functions:invoke api ```

4. No .gitignore blocking function files: ```bash git check-ignore netlify/functions/*.js # Should return nothing ```

---

Still broken? Check these too

1. [Netlify Build Cache Issue](/guide=netlify-cache-busting): Old compiled functions cached—clear deploy cache in Site Settings > Deploys, then redeploy.

2. Function timeout or cold start delays: If using external APIs, increase timeout in netlify.toml: timeout = 30 (max 26 seconds for free tier).

3. [Wrong Node.js version](/guide=netlify-node-version): Check package.json runtime engine or set explicitly in UI (Settings > Build & Deploy > Environment > NODE_VERSION).

---

Official Resources

📖 [Netlify Functions Environment Variables - Official Docs](https://docs.netlify.com/functions/overview/?fn-language=js#environment-variables)

📖 [Netlify.toml Configuration Reference](https://docs.netlify.com/configure-builds/file-api-reference/)

---

Pro Tips for 2am Debugging

  • Add logging: console.log("Env vars:", Object.keys(process.env).filter(k => k.includes('API'))) to see what's actually loaded
  • Use netlify functions:invoke function-name --payload '{}' locally to test before pushing
  • Check Deploys tab > Deploy log for build-time errors (often hidden in UI)
  • Secrets set in UI take effect on next redeploy—manual netlify deploy won't help if you just added vars
  • ---

    Found a different variation? Drop it in the comments—especially if you're seeing this with edge functions, monorepos, or custom build plugins.

    🔥 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