How to access environment variable defined in Netlify admin UI in front-end?

I have trouble with getting access to Netlify admin UI -defined env-vars in React. I followed these implementation steps.

Logging response.json() and in the next “then” statement json gives this console output:
image

Would be very grateful for any guidance on how to use a private API key in React, which is in an environment variable defined in the Netlify admin UI.

Thanks,
/David

Hi @ronnlidd

My answer is not going to address your question as much as clear up what I think you might be doing that would get you in some trouble down the road.

A “PRIVATE” API key shouldn’t be exposed to your front end. The implementation you are referring to is using the key in a function in a lambda server.

The call you are doing here would expose the key to the client and anyone would be able to access this data using your key!

image

The api call to https://api.themoviedb.org/3/discover/movie should be done inside the lambda function and return the data to fetchMovies. This way your API key would not be exposed to the client.

Answer to your question. You are not actually calling the lambda function on this call. You are fetching directly to a file that doesn’t exist and getting the page response as if you went to this url: https://davidronnlidmovies.netlify.app/netlify/functions/api.js which is a webpage from your SPA.

The endpoint for the lambda has a path like: https://davidronnlidmovies.netlify.app/.netlify/functions/api which is currently erroring. Good news, because you definitely do not want to pass your private api key inside this function to the web.

I hope all this made sense.

-Tony

2 Likes

Hey, @talves. Thank you!

Yes, that makes sense and I have now moved the entire API call into the lambda function and its file. But how do I get access to the data that was fetched from the API inside of my React project? I interpret the “exports.handler” as an export statement but maybe that is wrong? I tried to “import api_data from ‘…/…/.netlify/functions/api’” in the file where fetchMovies() is called and also with using the js fetch() function inside of that file, but none of these worked.

Thanks,
/David

Without seeing code, it would be hard to answer your question. Also, since I’m a consultant, I’ve little time to review code constantly for issues.

I’d console.log out the response and go from there if I were you.

Regards,
Tony