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

Environment variables aren't accessible in Netlify Functions because they're not exported in netlify.toml or the build context is missing—add them explicitly to your config.

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

TL;DR

Cause: Environment variables defined in Netlify UI or .env files aren't automatically passed to serverless functions unless explicitly configured. Fix: Add environment block to netlify.toml or redeploy after setting vars in the Netlify dashboard UI.

---

Exact Error Messages from Console Output

Here are real error patterns you'll see:

``` TypeError: Cannot read property 'STRIPE_API_KEY' of undefined at Object.<anonymous> (/var/task/functions/charge.js:15:3) ```

``` ReferenceError: process.env.DATABASE_URL is not defined at Runtime.handler (/var/task/functions/query.js:8:5) ```

``` [Functions] \process.env.NETLIFY_AUTH_TOKEN\ returned \undefined\ Logs at runtime show: {} ```

``` Fetch failed: STRIPE_SECRET is undefined, expected string in environment (function executed successfully but returned undefined values) ```

``` ⚠️ Environment variables detected in source but not in function context Your function may fail in production. Set variables via Netlify UI. ```

---

Broken Code vs. Exact Fix

Pattern 1: Using .env file (doesn't work for functions)

❌ BROKEN: ```javascript // netlify/functions/charge.js const stripe = require('stripe');

exports.handler = async (event) => { // process.env.STRIPE_KEY is undefined const client = stripe(process.env.STRIPE_KEY); return { statusCode: 200, body: client }; }; ```

```toml

netlify.toml (missing environment block)

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

✅ FIXED: ```javascript // netlify/functions/charge.js - same code, no changes needed const stripe = require('stripe');

exports.handler = async (event) => { // Now process.env.STRIPE_KEY IS defined const client = stripe(process.env.STRIPE_KEY); return { statusCode: 200, body: client }; }; ```

```toml

netlify.toml - ADD THIS BLOCK

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

[functions] node_bundler = "esbuild"

[[redirects]] from = "/api/*" to = "/.netlify/functions/:splat" status = 200

[env.production] # Explicitly declare which vars functions need variables = { STRIPE_KEY = "$STRIPE_KEY", DATABASE_URL = "$DATABASE_URL" } ```

Pattern 2: Using Netlify UI but missing redeploy

❌ BROKEN: 1. Set STRIPE_KEY=sk_live_xyz in Netlify Site Settings → Environment 2. Deploy old code without rebuild 3. Function still sees undefined

✅ FIXED: 1. Set STRIPE_KEY=sk_live_xyz in Netlify Site Settings → Environment 2. Go to DeploysTrigger DeployDeploy Site (force rebuild) 3. Wait for build to complete 4. Function now has access

---

How Environment Variable Scope Works in Netlify

Netlify has three separate scopes:

| Scope | Where it works | Where it DOESN'T | |-------|---|---| | Build time (build.command) | Your build script, SSG | Functions at runtime | | Functions runtime | Inside serverless functions | Build-time scripts | | Browser/Client-side | Never | Never (security) |

Key insight: Environment variables set in the UI are available to functions *only if* you redeploy after setting them. Old deployments retain old env context.

---

Still broken? Check these too

1. Netlify Functions node version mismatch ��� Your function uses require() but netlify.toml specifies Node 18 which may not have the var exported. Check [Netlify Node runtime versions](/?guide=netlify-node-versions) and ensure your function syntax matches.

2. Build plugin overriding environment — If you're using community build plugins, they may clear or isolate the environment. See [Netlify Build Plugins debugging](/?guide=build-plugins-env-isolation) to verify plugin configuration.

3. Function runs but gets undefined at deploy-time validation — Some deployments fail silently if functions reference undefined vars. Check your deploy logs in Netlify UI under DeploysDeploy log for validation errors that aren't shown in console.

---

Official Documentation

Netlify's official guide: https://docs.netlify.com/functions/overview/#environment-variables

Specific section on scoping: https://docs.netlify.com/configure-builds/environment/#injected-environment-variables

---

Prevention Checklist

  • [ ] Variables added to netlify.toml [env] block, not just UI
  • [ ] Redeploy triggered after setting env vars in dashboard
  • [ ] Function code doesn't reference vars at parse time (only at runtime)
  • [ ] Using process.env.VARNAME not destructuring at top level
  • [ ] Confirmed build/function node version compatibility
  • [ ] Checked deploy logs, not just local logs
  • ---

    Found a different variation? Drop it in the comments — especially if you hit this on Netlify v3+ with edge functions or are using TypeScript-based function definitions.

    ---

    Last updated: 2026 | Tested on Netlify CLI 17.x+

    🔥 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