[Support Guide] Using environment variables on Netlify correctly

A couple of things @Richard_Fink

  1. You need to await response.json()
  2. Rather than an anonymous async function inside a non-async try
async function getEnvUN() {

  const response = await fetch('/.netlify/functions/envUN');
  const result = await response.json();    // Need to await

  console.log(result)

};

However the idea is that you don’t return the process.env.PAYLIVESHOP_USERNAME value to the front-end script. That defeats the purpose of using an environment variable and function. Obviously for testing, that’s a different thing.

1 Like

Screen Shot 2021-11-07 at 12.28.48 AM

I hope that says it… dang, it worked!

Thank you is a bit small. First I can move on, that’s big. Secondly, I can see/figure out just why this worked and the other methods did not. I appreciate the time you have contributed here. I will give the same elsewhere to another.

For me its 12:31am here in San Francisco. If at some time you had a moment to explain each line, and why it did the job, I would put the serious time in to study it. If that’s too much, I understand.

Thank you, very much. And to @hrishikesh the same thanks to you for your returning time and willing help.
Best, Ric

1 Like

Great that you got it working. However, I must tell again that if this was just for demo purposes, then it’s okay, but please don’t return the environment variable to client side using functions.

1 Like

if I never use the function to return an environment to a JS variable but only within the use statement where the value is needed, how is that dangerous. The value is passed but never held/exposed in a variable. It is never in plain text.

Seems the same as one may do using process.env in Node. Its when it is assigned to a JS variable that it becomes exposed and dangerous. Would you agree?

Could you share an example?

From what I know, any value that’s passed in any part of JavaScript code is accessible in the JS debugger using breakpoints.

Hey @fishstix81 did you get to solve that issue?

I am facing the same problem, although I have tried to reference a different env var, instead of NODE_ENV, using MYBUILD_ENV, the new var is always undefined for Gatsby.

Ths.

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"}`}
    })