1

I would like to use an api key stored in an environment variable. I know I can just put it directly in the html (I don't think it is bad security wise since it is a public key). But I can't get access it an my react component.

useEffect(()=>{
      SetRecaptchaKey(import.meta.env.VITE_SITE_RECAPTCHA_KEY);
      console.log(recaptchaKey)
    });

outside my component function (above) I have this:

const key = import.meta.env;
console.log(key)

it logs the object in the console, and it has the variable i'm looking for.

Another thing, is that I have two VITE_... variables and another variable. Only one of VITE_.. is loaded (which is what I want) but I don't understand why.

Thanks in advance

Eye Patch
  • 881
  • 4
  • 11
  • 23

2 Answers2

0

In order to use an environment variable in client side Astro, you need to prefix the variable with "ASTRO_". For example, if you have an environment variable named "TEST_VAR", you would access it in client side Astro as "ASTRO_TEST_VAR".

  • 2
    It works. But how can I use it inside the component? It returns undefined. But It logs if it is outside. – Eye Patch Nov 19 '22 at 19:56
0

Not sure if the behavior or documentation was changed after the last answer, but you need to prefix it with PUBLIC_.

So if you have an environment variable named TEST_VAR, you need to rename it to PUBLIC_TEST_VAR and then it should be accessible in client side components as PUBLIC_TEST_VAR.

For example as import.meta.env.PUBLIC_TEST_VAR in a Astro React component.

Please note that this variable will be leaked in the client side code!

SenTisso
  • 579
  • 7
  • 18