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

Environment variables undefined in Netlify Functions? Missing netlify.toml config or .env file isn't deployed. Add environment variables to Netlify UI or netlify.toml.

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

TL;DR

Cause: Environment variables defined locally (.env) aren't automatically deployed to Netlify Functions; they must be configured in Netlify's UI or netlify.toml.

Fix: Add your variables to Site Settings → Environment Variables or commit them to netlify.toml in the [functions] section.

---

Real Console Error Messages

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

2. Error: STRIPE_KEY is not defined at handler (/.netlify/functions/payment:1:1)

3. ReferenceError: process.env.API_SECRET undefined at runtime Netlify Functions — 12:47:32 AM

4. Warning: Environment variable AUTH_TOKEN not found in build context During deploy to production

5. SyntaxError: Unexpected token 'u' in JSON at position 0 (Usually means env var containing JSON is undefined, causing JSON.parse(undefined)) ```

---

Broken Code vs. Exact Fix

❌ BROKEN: Local .env file only

```javascript // netlify/functions/query.js require('dotenv').config();

exports.handler = async (event) => { const db_url = process.env.DATABASE_URL; // ← undefined in production const connection = await connect(db_url); return { statusCode: 200, body: 'Connected' }; }; ```

``` .env (local only — NOT deployed) DATABASE_URL=postgres://user:pass@localhost/db API_KEY=sk_test_123456 ```

✅ FIXED: Add to netlify.toml

```toml

netlify.toml (committed to git — deployed automatically)

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

[functions] node_bundler = "esbuild"

[[env.production.context.functions]] environment = { DATABASE_URL = "postgres://user:pass@prod-host/db", API_KEY = "sk_prod_789012" } ```

OR via Netlify UI:

1. Go to Site Settings → Build & Deploy → Environment 2. Click Edit variables 3. Add key-value pairs: - DATABASE_URL = postgres://user:pass@prod-host/db - API_KEY = sk_prod_789012 4. Save and redeploy

✅ FIXED: Updated function code

```javascript // netlify/functions/query.js // Remove require('dotenv') — not needed in production

exports.handler = async (event) => { const db_url = process.env.DATABASE_URL; // ← now available if (!db_url) { return { statusCode: 500, body: JSON.stringify({ error: 'DATABASE_URL not configured' }) }; } const connection = await connect(db_url); return { statusCode: 200, body: 'Connected' }; }; ```

---

Why This Happens

1. .env files are NOT deployed — .gitignore excludes them (for security) 2. Netlify Functions run in a different context — they can't access your local machine's environment 3. Production needs explicit configuration — Netlify keeps secrets separate from code

Note on version behavior: As of Netlify CLI v18+ (2025), local builds using netlify dev will load .env files automatically, but this does NOT apply to deployed functions. We're uncertain if future versions will auto-sync .env files to the Netlify build context; always configure production vars explicitly.

---

Still broken? Check these too

1. Variables not redeployed after adding them - Environment variables require a new deploy to take effect - Go to Deploys → click the three dots on your latest deploy → Trigger deploy - Don't just rebuild locally; Netlify won't see the new vars - See: [Netlify deploy troubleshooting guide](/?guide=netlify-deploy-issues)

2. Using require('dotenv') in production - If your function calls require('dotenv').config(), it will silently fail in production - Remove it — Netlify Functions don't load .env files - Only use it in local development - See: [Environment setup best practices](/?guide=env-config-patterns)

3. Variable names with special characters or spaces - Netlify UI strips leading/trailing spaces - Use SNAKE_CASE (e.g., DATABASE_URL, not Database URL) - If copying from .env, remove quotes: KEY="value" → UI value: value - Special chars like $, {, } may need escaping depending on context

---

Verification Checklist

  • [ ] Variables added to Netlify Site Settings (or in netlify.toml)
  • [ ] New deploy triggered after adding variables
  • [ ] Function code does NOT call require('dotenv').config()
  • [ ] Console.log shows vars exist: console.log(process.env.DATABASE_URL)
  • [ ] Local .env is in .gitignore (never commit secrets)
  • [ ] Using process.env.VAR_NAME, not process.env['VAR_NAME'] (both work, first is clearer)
  • ---

    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/)
  • ---

    Found a different variation? Drop it in the comments — Does your error mention a specific function name or region? Are you using Edge Functions instead of regular Functions? Let us know so we can add it to this guide.

    🔥 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