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

Env vars undefined in Netlify Functions? Move them from .env to netlify.toml [env] or Functions UI—functions don't auto-inherit root .env files.

Netlify: Env Vars Not Loading in Functions [2026 Fix]

TL;DR

Cause: Netlify Functions don't automatically read .env files from your project root—they only load variables defined in netlify.toml, the Netlify dashboard, or .env.production.

Fix: Define environment variables in netlify.toml under [env] or configure them via the Netlify dashboard UI instead of relying on local .env files.

---

Real Console Error Messages

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

2. console.log(process.env.DATABASE_URL) // outputs: undefined at Object.<anonymous> (/var/task/functions/query.js:8:5)

3. fetch(${process.env.API_ENDPOINT}/users) // fails with ENOTFOUND Error: getaddrinfo ENOTFOUND undefined at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)

4. ReferenceError: process is not defined at handler (functions/auth.js:1:15) [Node 18+ strict mode]

5. Netlify deploy logs: "No environment variables found for function context" ```

---

Broken Code → Fixed Code

❌ BROKEN: Relying on .env

```javascript // .env (in project root) API_KEY=sk_live_12345 DATABASE_URL=postgresql://user:pass@localhost REACT_APP_SECRET=mysecret

// netlify/functions/api.js exports.handler = async (event) => { console.log(process.env.API_KEY); // undefined in production const response = await fetch(https://api.example.com/data, { headers: { Authorization: Bearer ${process.env.API_KEY} } }); return { statusCode: 200, body: JSON.stringify(response) }; }; ```

✅ FIXED: Define in netlify.toml

```toml

netlify.toml (at project root)

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

[env] [env.production] API_KEY = "sk_live_12345" DATABASE_URL = "postgresql://user:pass@localhost" REACT_APP_SECRET = "mysecret"

[env.develop] API_KEY = "sk_test_67890" DATABASE_URL = "postgresql://dev:dev@localhost" ```

```javascript // netlify/functions/api.js (SAME CODE, NOW WORKS) exports.handler = async (event) => { console.log(process.env.API_KEY); // "sk_live_12345" ✓ const response = await fetch(https://api.example.com/data, { headers: { Authorization: Bearer ${process.env.API_KEY} } }); return { statusCode: 200, body: JSON.stringify(response) }; }; ```

Alternative: Dashboard UI Method

1. Go to Netlify Dashboard → Your Site → Site Settings 2. Navigate to Build & deploy → Environment 3. Click Edit variables → Add key/value pairs 4. Redeploy: netlify deploy --prod

---

Version Uncertainty Notes

  • Netlify Functions Node runtime (18.x+): Strict mode may throw ReferenceError: process is not defined if env vars aren't properly injected. Explicitly import if needed: const { env } = require('process');
  • netlify.toml syntax: The [env] context syntax has been stable since 2022, but confirm your Netlify CLI version matches your build image (node-version setting in netlify.toml).
  • Local vs. Production: netlify dev reads .env for local testing, but production deployments ignore it. This asymmetry causes the 2am panic.
  • ---

    Still Broken? Check These Too

    1. Function not redeployed after env var change - Netlify caches function bundles. Force a full rebuild: Delete node_modules/.cache, commit, and push again. Or use Deploys → Trigger deploy in dashboard.

    2. Wrong environment context deployed - Check your branch in Site Settings �� Build & deploy → Deploy contexts. Preview branches may deploy under [env.develop] instead of [env.production]. Verify which context your function is reading with console.log(process.env.CONTEXT).

    3. Trailing whitespace or syntax errors in netlify.toml - TOML is whitespace-sensitive. Invalid TOML silently fails without error. Validate using [TOML Checker](https://www.toml-checker.com) or run netlify deploy --dry-run locally.

    ---

    Related Guides

  • [Netlify Functions cold start timeout issues](/?guide=netlify-cold-start-timeout)
  • [Build environment vs. runtime environment confusion](/?guide=env-context-layers)
  • ---

    Official Resources

  • [Netlify Functions Documentation](https://docs.netlify.com/functions/overview/)
  • [Environment Variables Reference](https://docs.netlify.com/build-release-manage/configure-builds/file-based-configuration/#environment)
  • [Netlify CLI Environment Docs](https://cli.netlify.com/)
  • ---

    Pro tip: Use netlify dev locally before deploying. It simulates your netlify.toml environment and catches issues like this at 2pm instead of 2am.

    Found a different variation? Drop it in the comments below—Netlify's behavior differs slightly across runtimes (Node vs. Python vs. Go) and I want to hear about edge cases you've hit.

    🔥 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