[Support Guide] Using environment variables on Netlify correctly

Hey there, @mustainer :wave:

It looks like you have two threads open about this question! Let’s continue your conversation in the other thread (linked here: Problems with environment variables - #7) This will help streamline your support conversations.

@hillary ,

sorry, I came up with this answer and the users seems to have a solution, I thought it was easier to ask him directly and then link the solution to my original thread.

But sorry for the inconvinience.

I followed all rules stated but when i pass process.env.REACT_APP_API_KEY int frontend function it sees undefined

my netlify vars in site/b&deploy Environment variables

REACT_APP_API_KEY ‘abcd123’

function abs () => {
apikey: process.env.REACT_APP_API_KEY
}

please advice

Hi, @marsidorowicz. The environment variable will be available for any node processes running inside the build environment at Netlify. However, when the build completes that environment is deleted.

Are you trying to access the environment variable inside client side javascript? If so, the client side javascript has no access to the build environment and the environment variable won’t be defined client side.

The environment variable should be defined for Functions, though. If that is where the error is occurring that shouldn’t be happening.

Would you please clarify where the error happens? Meaning, is it in the build itself, the client side javascript, or in a Function?

Thank you, so the problem comes only when i try to get access to env var in tsx file, in frontend side ofc and that is the problem, need to change function tough!

I have spent a good 3+ days on issues I believe are arising from the .env vars. I can use locally but *I think - are not available in production, this or there’s another issue going on that I can’t find. On local, using the netlify cli & running netlify dev cmd, I can spin it up and hit my netlify function that then posts to the api. I do get a good response and resultant message in inbox. I have double checked the vars in the Netlify UI, theyre good. In production or preview though, all I can get is a 500 and what seems like is not even executing my function - which I think stem from no reading of my env vars. Im using Nextjs. Thanks for your help.

Hi @emptydub, it would be helpful to see some code. If you can’t show it, maybe a simple reproduction of the issue.

I finally got it. Ok so if you are using axios for your function request this return structure worked for me… this post: [Netlify Functions + axios Get not working in production - #2 by hrishikesh] - the odd thing is locally & using await on my request would return a response and included data, but production deploy was returning undefined/bad request no matter what I would try.

The documentation shows the return schema for the lambdas but is somewhat confusing in implementation - I had thought to return the actual data from the request and then eval it on the client as ‘response.statusCode’, NO this is incorrect, the netlify-function EXPECTS you to return a value called ‘statusCode’ no matter what the actual request response data is - so take note of that, dont try to assign a response-value, just assign it a value. In the end I scrapped sending the returned .status value from the request and just assigned a 200 if good and 422 if bad.

I also took a look at the function’s log and noticed that my NetlifyUI Environment vars I had quotes around the values - so it was sending → " ‘variable’ " (*again this worked locally, but not in prod): lesson, don’t put quotes around your vars in the UI.

After removing those and the other thing with my return values, it indeed does work. I hope this might save someone else frustration and copious amounts of time.

–>Don’t do this:

...
let responseStatusCode = 444;
...
await axios(config)
    .then((response) => {
        console.log("response:: ", response.status)
        responseStatusCode = response.status || 200
    })
    .catch((error) => {
        console.log("func-error:: ", error.response.status)
        if(error)
            responseStatusCode = error.status || 500
    })
    return { statusCode: responseStatusCode }


-->Do something like this instead (see the referenced post above for a prettier version): 

return axios(config)
    .then((response) => { 
        return { statusCode: 200, body: response.data ? JSON.stringify(response.data) : "no-response-data-given" }
    })
    .catch((error) => {
        console.log(error);
        return { statusCode: 422, body: `Error: ${error ? error : "no error data given"}`}
    })

Hi all,

I have set my netlify.toml file with [context.deploy-preview.environment] NODE_ENV = "development", but when I create a pull request, my NODE_ENV variable does not change , even if the context indicated during build is ❯ Context deploy-preview

I am using it in a function for a Gatsby site :

function dosmthng() {

  if (process.env.NODE_ENV === "production") {
   // do Something
  } else {    // do Something else }
}

And the result is always ‘// do something’ , even when I am in deploy-preview context…

What am I missing ?

Hi, @Matos28 :wave:t6: welcome to the forums. Try these things:

  1. Did you make sure that you have saved the changes to your netlify.toml file and committed them to your repository before creating the pull request?
  2. Check that the environment variable NODE_ENV is set correctly; go to the “Build & deploy” section, and click on the "Environment" tab to see a list of environment variables. Make sure that NODE_ENV is listed and set to the correct value for the deploy-preview context.
  3. Finally give this guide a read and see if it helps answer your question: [Support Guide] Compiled Build and Deploy Resources -- start here!

Hello everyone!

I’m wondering is it possible to reassign default Netlify env var to my own env var that is used by my app?
So for instance, Netlify provides $URL env var - url of a deployed site. My app uses $AAA env var.
Is it possible somewhere in the admin dashboard to assign a custom env var this way?

env var AAA = $URL
smth like this:

As stated in this documentation URL is a read-only variable. If you require a different value than provided by Netlify, you’ll need to set another variable @matriar .

@jasiqli thanks,
yeah, I see it is read-only. I don’t want to reassign it, I’d like to use it as a value for another env var.

AFAIK that is not possible. At least not via the UI.

Using this example

possibly you could write that variable to a location then read it.

Or using this one

do preprocessing replace a placeholder value with that of $URL before building.

for anyone who’ll fall here
If you need Netlify env var to be fallthrough as different name:
updates to the build command npm run buildYOUR_VAR=$URL npm run build could make a trick.

It’s a bit ugly and poor scalable but for a MVP it is enough =)

1 Like