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

Environment variables undefined in Netlify Functions because they're not declared in netlify.toml or missing from build context.

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

TL;DR

Cause: Environment variables aren't exposed to Netlify Functions via netlify.toml configuration or aren't properly set in your build environment. Fix: Add environment block to netlify.toml under [functions] or use Netlify UI to set variables with the correct scope.

---

Exact Error Messages You'll See

``` ReferenceError: Cannot read property 'undefined' of process.env.DATABASE_URL at /var/task/src/functions/api.js:12:15

TypeError: process.env.STRIPE_KEY is undefined at Object.<anonymous> (/var/task/src/functions/payment.js:5:1)

WARNING: Environment variable MY_API_KEY not set at config.js line 23

Error: ENOENT: no such file or directory, open '/var/task/.env' at Object.openSync (fs.js:476:3)

502 Bad Gateway - function invocation failed: process.env is undefined in function context ```

---

The Problem: Side-by-Side Comparison

❌ Broken Code Setup

netlify.toml (missing environment block): ```toml [build] command = "npm run build" functions = "netlify/functions"

No [functions] section!

```

netlify/functions/api.js: ```javascript const dbUrl = process.env.DATABASE_URL; // undefined! const apiKey = process.env.STRIPE_KEY; // undefined!

exports.handler = async (event) => { const connection = await connect(dbUrl); // crashes return { statusCode: 200, body: "ok" }; }; ```

---

✅ Correct Code (The Fix)

netlify.toml (with environment variables): ```toml [build] command = "npm run build" functions = "netlify/functions"

[functions] environment = { DATABASE_URL = "postgres://...", STRIPE_KEY = "sk_live_..." } ```

netlify/functions/api.js (unchanged, now works): ```javascript const dbUrl = process.env.DATABASE_URL; // now defined! const apiKey = process.env.STRIPE_KEY; // now defined!

exports.handler = async (event) => { const connection = await connect(dbUrl); // works! return { statusCode: 200, body: "ok" }; }; ```

---

Three Methods to Set Environment Variables

Method 1: netlify.toml (Best for dev/non-secrets)

```toml [functions] environment = { NODE_ENV = "production", PUBLIC_API_URL = "https://api.example.com" } ```

Method 2: Netlify UI (Best for secrets)

Dashboard → Site settings → Build & deploy → Environment: 1. Click "Edit variables" 2. Add each variable individually 3. Secrets are encrypted and never logged

Method 3: netlify.toml with context (for multiple environments)

```toml [functions] environment = { ENVIRONMENT = "production" }

[context.deploy-preview.functions] environment = { ENVIRONMENT = "staging" } ```

Note: We're uncertain whether the exact [functions] syntax behavior changed between Netlify's 2024-2026 runtime versions. Check your build logs for confirmation.

---

Why This Happens

Netlify Functions run in an isolated Lambda-like environment that doesn't automatically inherit:

  • Local .env files (they're not deployed)
  • Build-time environment variables (they're separate from runtime)
  • System environment variables from your machine
  • You must explicitly declare what functions need via netlify.toml or the UI.

    ---

    Still Broken? Check These Too

    1. Variables scoped to build, not functions — If you set vars in the UI under "Build & deploy → Environment," they apply to your build command only. Functions need explicit [functions] config. [Netlify environment scope guide](/?guide=env-scopes)

    2. Function can't access .env files — Netlify Functions never have filesystem access to .env. Remove require('dotenv').config() and rely on process.env alone. [Dotenv issues in serverless](/?guide=dotenv-serverless)

    3. Secrets exposed in netlify.toml — Never commit real API keys to netlify.toml. Use UI or encrypted secrets. Prefer the Netlify UI for anything sensitive.

    ---

    Verification Checklist

  • [ ] Added [functions] section to netlify.toml
  • [ ] All env vars listed in environment = { ... }
  • [ ] If using UI, confirmed variables appear under Build & deploy → Environment → Functions
  • [ ] Ran netlify deploy (not just local netlify dev)
  • [ ] Checked function logs in Netlify dashboard (Functions tab) for the actual error
  • [ ] Redeployed after adding/changing variables
  • ---

    Official Resources

    📖 [Netlify Functions Environment Variables](https://docs.netlify.com/functions/overview/#environment-variables)

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

    ---

    Quick Test

    Add this to a function to debug: ```javascript exports.handler = async () => { return { statusCode: 200, body: JSON.stringify({ dbUrl: process.env.DATABASE_URL ? "SET" : "MISSING", allVars: Object.keys(process.env).sort() }) }; }; ``` Deploy and call it. If your var doesn't appear in allVars, it wasn't configured correctly.

    ---

    Found a different variation? Drop it in the comments.

    🔥 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