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

Environment variables aren't passed to Netlify Functions at runtime. Move vars from .env to netlify.toml [build] or UI Settings.

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

TL;DR

Cause: Netlify Functions run in a separate context and don't automatically read .env files; they only access vars defined in netlify.toml or the Netlify UI. Fix: Define environment variables in netlify.toml under [build] section or add them via Netlify dashboard → Site settings → Build & deploy → Environment.

---

Real Console Error Messages

You'll likely see one of these:

``` Error: Cannot find module or its corresponding type declarations. (code: ENOENT) at /var/task/functions/api.js:5 require('process').env.DATABASE_URL // undefined ```

``` TypeError: Cannot read property 'split' of undefined at connectDatabase (/var/task/functions/db.js:12) const [host, port] = process.env.DB_HOST.split(':'); ^ ```

``` {"errorMessage":"process.env.STRIPE_KEY is undefined","errorType":"ReferenceError"} ```

``` Failed to load resource: the server responded with a status of 500 (Internal Server Error) Function error: Reference to undefined variable: API_TOKEN ```

``` netlify/functions/handler.js - SyntaxError: Unexpected token u in JSON at position 0 // Often caused by JSON.parse(undefined) when env var is missing ```

---

Side-by-Side: Broken Code → Fixed Code

❌ Broken Approach

File: .env ``` DATABASE_URL=postgresql://user:pass@localhost/db API_KEY=secret123 STRIPE_KEY=sk_live_xyz ```

File: netlify/functions/api.js ```javascript const dbUrl = process.env.DATABASE_URL; // ❌ undefined at runtime const apiKey = process.env.API_KEY; // ❌ undefined at runtime

exports.handler = async (event) => { const db = await connect(dbUrl); // CRASHES HERE return { statusCode: 500 }; }; ```

✅ Fixed Approach

File: netlify.toml ```toml [build] command = "npm run build" functions = "netlify/functions" environment = { DATABASE_URL = "postgresql://user:pass@localhost/db", API_KEY = "secret123", STRIPE_KEY = "sk_live_xyz" } ```

OR use UI: Netlify Dashboard → Site settings → Build & deploy → Environment variables → Add variable

File: netlify/functions/api.js (same code, now works) ```javascript const dbUrl = process.env.DATABASE_URL; // ✅ loads from netlify.toml const apiKey = process.env.API_KEY; // ✅ loads from netlify.toml

exports.handler = async (event) => { const db = await connect(dbUrl); // ✅ WORKS return { statusCode: 200, body: JSON.stringify({ success: true }) }; }; ```

Important note: We're uncertain whether netlify.toml inline environment variables support multiline secrets in all versions (2024-2026). For sensitive data or complex values, use the Netlify UI instead.

---

Step-by-Step Deployment Fix

1. Stop relying on .env — Netlify Functions don't read it during execution. 2. Choose one method: - Option A (Recommended for secrets): Netlify Dashboard → Site settings → Build & deploy → Environment variables - Option B (For non-sensitive config): Add to netlify.toml 3. Test locally with Netlify CLI: ```bash npm install -g netlify-cli netlify dev ``` This simulates the production environment and will load vars from netlify.toml or .env (for local development only). 4. Verify in production: ```bash curl https://your-site.netlify.app/.netlify/functions/api ```

---

Still broken? Check these too

1. Build-time vs. Runtime confusion - Variables in [build] section are available during npm run build AND in Functions - Variables needed only at build time (like CI=true) don't auto-populate Functions; explicitly add them - [Netlify environment variables scope guide](/?guide=netlify-build-runtime-vars)

2. Netlify CLI not reading .env - If netlify dev isn't loading your .env, create .env.example and manually add vars to netlify.toml for local testing - Verify netlify/functions path matches your netlify.toml config

3. Access control & branch deploys - Environment variables set in UI apply to all branches by default - For branch-specific vars, use context.production or context.deploy-preview in netlify.toml - [Netlify context-based configuration](/?guide=netlify-context-builds)

---

Reference

Official Netlify docs: https://docs.netlify.com/functions/overview/?fn-language=js#environment-variables

Key takeaway: .env files are for local development only. Production Netlify Functions require environment variables defined in netlify.toml or the Netlify UI dashboard.

---

Found a different variation? Drop it in the comments—does your error look different, or did you solve it another way? We update this guide based on real-world 2am incidents. 🚀

🔥 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