How can I access an api environmental variable in a static html site that makes an api call?

I have a github linked static html site with no build process.
I have some js that calls 3rd party api and uses a key.
I add the key to the dashboard env settings.

I have read the documentation and tried a few examples of setting a function, eg code-examples/function_examples/use-env at master · netlify/code-examples · GitHub
These either failed to execute path
const response = await fetch(’/.netlify/functions/return-env’)
or simply returned undefined.

Is it possible to access env variable key in a static html scenario?

You don’t really need Functions to access API key. In your JS if you write your code as process.env.NAME, it will automatically convert it to the API key while building.

If you want to use Functions for “securing the environment variable”, let me tell you that it’s not possible. Anyone can visit your Function URL and see the variable easily. So, the recommended way would be to call the 3rd-party API though the serverless function and return the data through that.

1 Like

Thanks @hrishikesh
It’s the third option that appeals - making the api call and returning the result.
There is no build process here just static html published via github.
So as far as I understand have

  1. my 'do-something.js" that calls a function ‘myfunction’
  2. in "netlify/functions’ i shoudl have a js file called myfunction
  3. data/vars returned in no 2 should then be available on the static client html/js

Is that right?

Yes, that seems about correct. Let us know if you face any issues in your process, we’ll be happy to help.

1 Like

Thank you - im sure ill be back here shortly