Accessing Environment Variables in Front End

First of all I’d like to apologise as I can see that this issue pops up a lot, and even though I’ve tried using the information available in other forum posts such as the following, I haven’t quite been able to crack it:

My website is https://www.linguallect.com; it is made with create-react-app. The issue occurs on the subdomain /buy/french (or other language name) when trying to retrieve my Stripe API key from my environment variables. I set up my environment variables in Netlify UI, and my code attempts to access it with the following:

const stripeKey = process.env.REACT_APP_STRIPE_PUBLIC_KEY;

But the error that I receive is this:
image

My understanding is that the environment variables can be read in the build, but the live version of the site is not the build itself. I saw this solution but I’m clueless as to where to add the code that is specified.

When I had my environment variable stored in .env, I had been accessing it fine without needing dotenv, is it required to access the variable over Netlify?

Any help in tackling this would be massively appreciated.

Thanks!

That’s correct.

Environment variables aren’t for keeping values secret from the client side code, they’re for keeping the values out of your source code.

You can still store a value like your stripe public key in an environment variable, but at the end of the day it needs to be accessed during the build and compiled into the actual result that is served to the client.

There’s no service that you call at client runtime to secretly access environment variables from the server and you can’t inherently have code that directly accesses process.env on the client side because it doesn’t exist.

Different systems have helpers for it, so as is frequently the case how you can achieve it depends on what you’re working with.