Environment variables returning undefined

Hi, I’ve deployed my site - https://nervous-einstein-a721bb.netlify.app

for development I have an API key stored in env.local which works fine.

for deployment, I have set an env variable for the API through Netlify’s build and deploy settings. When I try to access it in the get request, it’s returned as undefined.

when I console log process.env in development, I, the key shows up, but when It’s logged in the deployed site, the variable I made in the build and deploy settings are not there at all in process.env, so I guess that’s why it’s giving me undefined.

So any idea why I’m not able to access the environment variable? thanks!

hi there, before we dig in, did you read through this guide already?

Yes I read that and I didn’t see what the issue was from it. cheers

any change you are including your .env file in a gitignore so it isn’t available after you push?

I have a few .env files in git ignore. Here is my git ignore file.

dependencies

/node_modules
/.pnp
.pnp.js

testing

/coverage

production

/build

misc

.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

Local Netlify folder

.netlify


In development the api is taken from env.local. I thought the enviroment variable through Netlify would be usable regardless of whatever is in gitignor, since it is coming from Netlify? (i’m new to this stuff :s)

our services never get to see the .env.local as it is listed out here and never pushed, i think.

i would suggest trying to set the environment variables you have in your local file via our UI:

Netlify App[YOUR SITE NAME]/settings/deploys#environment

that way, you don’t have to include anything private in your repository, but can still access them when you deploy.

Yes, that’s exactly what I’ve done and that’s the problem I’m having. I have set the variable for my api through Netlify App[YOUR SITE NAME]/settings/deploys#environment but it returns undefined when It’s accessed in the app.

So - the article Perry first linked you to is very specific: process.env.WHATEVER is not going to be defined at browse time. You’ll have to interpolate that value, during build, with what you want, unless you have a very specific use case like a variable of the special sort that gatsby/react/etc provide that are mentioned at the end of the article.

My question to you would be “how are you USING that variable, during build, to put its value into your files?” process.env.X has that value during build - but not during run - and that would be intended and explained in detail in that article :slight_smile:

1 Like