[Support Guide] Using environment variables on Netlify correctly

Hi, @fishstix81. Gatsby itself is overwriting that environment variable, not Netlify.

With Gatsby, NODE_ENV is a reserved environment variable and Gatsby will override whatever you set it to. This is found in their documentation here:

https://www.gatsbyjs.com/docs/how-to/local-development/environment-variables/#reserved-environment-variables

Quoting that page:

You can not override certain environment variables as some are used internally for optimizations during build, such as:

  • NODE_ENV
  • PUBLIC_DIR

If you make your build command this:

env ; npm run build

The env command above dumps the current environment variables to the logs and then runs the normal build command (npm run build).

You will see both that NODE_ENV is set to “staging” before npm run build is run and set to “production” while that npm run build command is running. In other words, this is your site build code (specifically, Gatsby itself) causing this.

Hmmmm, one more area where Gatsby kind of gets in the way. Thanks for pointing this out. I wasn’t aware that they hijacked some variables in this fashion. It looks like I may be able to hack this to do what I want, but at least the mystery is solved. Thanks for all the help!

Hi I recently visit netlify docs to get more info about Netlify Read Only Variables. As I started to try the Build Metadata Environment with React JS, which is CONTEXT environment by using process.env.CONTEXT. It seems that it returns undefined instead of production , deploy-preview or branch-deploy. Any ideas how to cope with this issue? Thanks in advance!

Hi @stanleyowen,

You’d probably have to do something like:

1 Like

HI @hrishikesh, it works for me :smiley:. I love how Netlify Community copes with issues and the speed of the responses :heart:. Thanks!

1 Like

I have read this posting completely and I have not found the answer.

My problem is when I try accessing my Env Vars in my app’s code, I get “process is not defined” error. Note, my Environment Key/Val IS in Netlify’s dashboard. My site is a plain Bootstrap Studio build, so I’m far past any design change using Node, React, or NextJS. And its my understanding from Zara’s post (link below) I shouldn’t have to. If you check the post by Tara Z. Manicsic, she makes no comment of the NECESSITY to use Node, React, NextJS, or Webpack. And Webpack 5 doesn’t even support dotenv any longer:

Please check my 3 uploads 1) my Env Key:Val in Netlify, 2) the code line in my app, 3) the runtime error.

Thanks for your help here.

1. KeyVal in Netlify


3. Run error

How do you even get a runtime error with client-side env variables? The build tool that you use is supposed to replace the process.env.name text with the actual value from the UI.

Browsers don’t know process - it’s a Node.js-only thing.

If you can share your repo, we can provide additional insights as to what you might have to do.

Thanks hrishikesh. I knew that process.env was a Node object but if you give 3 mins to the article by Tara Z. Manicsic that I referenced above, she appeared to infer that Netlify had internally implemented support for process.env in that her tutorial of environment var usage at Netlify was clearly without any mention of the requirement of using Node, React, NextJS, or Webpack.

I guess from that omission I made a leap of faith,… or, a leap of hope!

I’ll have to do some significant rewiring of things. Thanks.

Happy Birthday, hrishikesh !
If you get to the SF Bay Area, I owe you a BDay Pint!

This is not a requirement at all. But since I don’t have your site details to check, I’d like your clarification on whether you are building your website on Netlify, or are you manually deploying using drag-n-drop? if it’s the latter, it won’t work because in drag-n-drop deploy, Netlify doesn’t do any kind of processing except post processing. Thus those variables won’t be replaced.

This is a demo site, not an active business site, so I’m taking the easy route of drag-n-drop for updating. Of course, I would NOT want the variables to be replaced in my code. Is that what you meant? Actual replacement of var values in code, viewable as plain text?

I don’t ever want specific env vars to be stored in plain text. I would use a dymanic technique such as process.env within the functional statement, never assigning them to a var, let or const statement.

My objective is for my BSS app to be able to authenticate to an external server. Looks like it can’t be done as a static BSS app . It simply is not possible to hide/protect login credentials, permitting the app to securely log into an external server. I may have to complete my BSS app, functionally, and then rewire it as the web component of a new node server app, so I can perform my desired authentication from the backend, to then perform the logon to the actual external server I’m trying to log in to.

That’s not a problem, I just have got to stop trying to push this square object through a round hole!

Yes, that would be the case, you can never be sure that your auth keys in client-side data is safe no matter how well you hide it.

You can take a look at Netlify Functions which would access variables from the UI and thus, the variables would be safe.

Hrishikesh,

This looks like my final hurrah before possibly radical change.

Your idea of Netlify Functions was an interesting one. When I searched I found some general info but nothing that related directly to use of Environment Variables from the UI. May I ask you to reply one last time with a direct link to that ENV information? I would really appreciate that.

Thank you for sticking with me here.

-Ric

Richard Fink

Yeah sure, it’s not very complicated. Rather, it would fit your needs. The environment variables defined in UI are available during the runtime. So you could write your functions as process.env.FOO and the value of FOO would be automatically supplied to the functions when they ask for it.

So your code could be:

exports.handler = async () => {
  return {
    body: JSON.stringify(process.env.FOO),
    statusCode: 200
  }
}

This would return the variable to the client. It’s just an example of using variables with functions, and I’m not suggesting that you actually send the variable back to client. Rather, you’d want to connect to the external API using functions and use the variable like explained above and return the data from the API to your frontend.

1 Like

Where do I place this code?
In the MY_BASE_DIRECTORY/netlify/functions folder?
Or right in an application module of mine where I will need to use it’s functionality? Such as:

My Application Module:

exports.handler = async () => {
return {
body: JSON.stringify(process.env.FOO),
statusCode: 200
}
}

console.log("Env Var FOO: " + process.env.FOO);

UPDATE:

If I put your code in a module of my app, I get an “exports not defined” error.
If I wrap your code as a function in the netifly default functions directory as stated above, I get a “process not defined” error.

Do I need an import statement someplace?

Hi @Richard_Fink

This is the easiest place to put functions as Netlify will automatically build them. You then invoke the function by calling https://<your_site>/.netlify/functions/<FUNCTION_NAME>.

If you wanted to console.log (in a browser console) the value of the FOO variable as returned from the function you would need to fetch it first using the function endpoint as mentioned above and log the response. You can use console.log inside a function and it will print to the function log.

You might like to check out these resources for more information

2 Likes

@coelmay This is a great explanation. I have to bookmark for later questions regarding functions.

@Richard_Fink if this is a private repository, you could debug it back to the console.log() for display in the Netlify app. Otherwise you could just use a dummy value to make sure it’s coming through. Remember, only environment variables are only carried over to functions when they are entered into the admin console, which in most cases is more secure, not the netlify.toml.

1 Like

@coelmay this was amazingly helpful. I have actually spent the day on it, going down a thousand paths learning more and first applying the the lessons in the first video set “Up and Running”, I think Ch 3. I found my interpretation of code which I personalized did not work, so in the end I used the EXACT code in the lesson, which I point to here.

In the end, there are no errors, no crashes, just no result, no value. Let me proceed by including some screen prints and a horrible home video of 16 seconds.

I want to first document the situation, the Netlify dashboard and then my source code-

  1. screen print of the Netlify Env Var, in their dashboard. The value is only partial:
    1 Environment Var (partial) in Netlify Dashboard

  2. My two Netlify Functions as shown to be registered in the Netlify Dashboard:
    2 Netlify Functions documented in Dashboard

  3. The relevant Netlify Function source used in this test:
    3. Netlify Function Source

  4. The Netlify-CLI view of the functions, as correctly Deployed:
    4. Netlify-CLI Functions DEPLOYED

  5. My App module with the Fetch to the Netlify Function:

  6. Oh, excuse me, but my iPhone video of a run to a Breakpoint and stepping through, demonstrating that the Fetch is never run. ( its not letting me upload a .MOV file, so I’ll provide here the simple sequence of execution in photos-

6b Realtime Test

  1. The video I used for learning. I believe its Ch3, Create Your First Serverless Function:
    Create Your First Serverless Function - Up and Running with Serverless Functions - Jamstack Explorers

  2. His video also contains a link to the final code which he uses to complete the job. It is the code I eventually copied directly for use:
    explorers-up-and-running-with-serverless-functions/index.html at 03-end · netlify/explorers-up-and-running-with-serverless-functions · GitHub

His code works! Mine seems to not crash but just be ignored.

So the issue is I followed Ben’s coding exactly and it produced no errors or problems, but on execution, the Fetch is never processed! Dang it.

Can you see where I have missed the boat? Thank you!

-Ric

When you use await syntax, the correct way to convert to JSON is like:

const response = await fetch('/.netlify/functions/envUN')
const data = response.json()
console.log('fetch response: ' + data)

If you wish to use .then() syntax, it would be like:

fetch('/.netlify/functions/envUN').then(response => {
  return response.json()
}).then(data => {
  console.log('fetch response: ' + data)
})

This code came right out of Ben’s video. But I’m not wedded to it. In the end I’m looking for working code, and to understand it. Thanks.

I’ll give your suggestions a try.

UPDATE:

Same action, gets to the async then never to the fetch() or the console.log. I put a breakpoint on the console.log so I’d catch it, what ever timing it might take. No go.

1 screen

2 screen

3 screen

4 screen