You shouldn’t use secret keys in your front-end, as they will end up in your code after the build process is completed. If you use secret keys, use Netlify Functions instead.
You can load environment variables within your functions like this:
It’s not broken, that’s by design. I’ll try to explain.
Environment variables are injected at build time. They’re not actually available after your site is built, since that would require a running server. The exception of course being Netlify Functions, but I’ll keep that out of the equation for now.
So what happens is this:
You define an environment variable in the Netlify UI:
PUBLIC_KEY="asdf1234"
You then load the environment variable in your javascript file:
const publicKey = process.env.PUBLIC_KEY
The environment variable gets injected in your javascript file at build time:
const publicKey = 'asdf1234'
So when you try to log the key to your console after your site is built, this is undefined:
console.log(process.env.PUBLIC_KEY);
#undefined
But this isn’t:
console.log(publicKey);
# asdf1234
Hopefully this also explains why it’s a bad idea to use secret keys as build env variables