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

Netlify functions can't access env vars because they're not explicitly exposed in netlify.toml or defined in function scope.

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

TL;DR

Cause: Environment variables defined in Netlify UI aren't automatically injected into serverless functions without explicit configuration in netlify.toml.

Fix: Add nodeVersion context and declare functions variables in netlify.toml under [functions], or use process.env after ensuring variables are listed in the Netlify dashboard.

---

Real Console Error Messages

Here are exact errors you'll see at 2am:

``` Error: undefined is not a function at Runtime.handler (/var/task/functions/api.js:15:23) TypeError: Cannot read property 'API_KEY' of undefined ```

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

``` FunctionError: We encountered an error during function execution. We can't display logs right now, but your function executed without error. ```

``` Error: Missing required environment variable: STRIPE_SECRET_KEY at Object.<anonymous> (/var/task/functions/checkout.js:5:1) ```

``` [undefined] Handler function returned undefined instead of Error or Response object ```

---

Broken vs. Fixed Code

Problem 1: Missing netlify.toml Declaration

❌ BROKEN CODE: ```javascript // netlify/functions/api.js exports.handler = async (event, context) => { const apiKey = process.env.API_KEY; // undefined! console.log(apiKey); // prints: undefined return { statusCode: 200, body: JSON.stringify({ key: apiKey }) }; }; ```

```toml

netlify.toml - INCOMPLETE

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

✅ FIXED CODE: ```javascript // netlify/functions/api.js - NO CHANGES NEEDED exports.handler = async (event, context) => { const apiKey = process.env.API_KEY; // now works! console.log(apiKey); // prints: your-actual-key return { statusCode: 200, body: JSON.stringify({ key: apiKey }) }; }; ```

```toml

netlify.toml - ADD THIS

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

[functions] node_bundler = "esbuild" ```

Then in Netlify UI Dashboard: 1. Go to Site settings → Environment 2. Add variable: API_KEY = your-value 3. Redeploy (or wait ~2 min for warm function pickup)

Problem 2: Incorrect Variable Scope in Local Dev

❌ BROKEN CODE: ```bash

.env (local dev)

API_KEY=local-dev-key DATABASE_URL=postgres://localhost ```

```javascript // netlify/functions/query.js require('dotenv').config(); // Missing in production! exports.handler = async () => { console.log(process.env.DATABASE_URL); }; ```

✅ FIXED CODE: ```bash

.env (local dev)

API_KEY=local-dev-key DATABASE_URL=postgres://localhost ```

```javascript // netlify/functions/query.js exports.handler = async () => { // In production: Netlify injects vars automatically // In dev: use netlify dev CLI (handles dotenv) const dbUrl = process.env.DATABASE_URL; console.log(dbUrl); // works in both contexts return { statusCode: 200, body: dbUrl }; }; ```

Local testing command: ```bash netlify dev # Uses .env automatically, no dotenv() call needed ```

---

Critical Details

Node Version Clarification: Netlify uses Node 18.x by default (as of 2026). If you're explicitly setting nodeVersion in netlify.toml, ensure it matches your package.json engines field. We cannot guarantee compatibility beyond Node 18.x without seeing your specific version configuration.

When variables load:

  • Dashboard variables: Deployed function needs ~30 seconds after setting
  • .env file: Only in netlify dev local testing, ignored in production
  • netlify.toml defaults: Applied immediately on redeploy
  • ---

    Still broken? Check these too

    1. [Build-time vs Runtime variables](/?guide=env-build-runtime) — Some vars need $ prefix in netlify.toml to expose at runtime. Debug with console.log(process.env) in your handler.

    2. Function cold starts and lazy loading — First invocation after deploy may not see freshly-added env vars. Trigger the function twice or redeploy to refresh.

    3. [Netlify CLI authentication issues](/?guide=netlify-auth-local) — Running netlify dev without proper netlify link won't load remote environment variables. Run netlify link --id your-site-id first.

    ---

    Official Resources

  • [Netlify Environment Variables Documentation](https://docs.netlify.com/configure-builds/environment-variables/)
  • [Netlify Functions Runtime Guide](https://docs.netlify.com/functions/overview/)
  • ---

    Found a different variation? Drop it in the comments

    This guide covers the 95% case, but Netlify's edge function behavior, monorepo configurations, or custom build steps might produce different symptoms. Your error message could unlock the solution for someone else at 2am.

    🔥 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