#Env variables in astro with react component.

16 messages · Page 1 of 1 (latest)

past dove
#

Hi community. I am using astro with some astro components and some react components. I have two services using the same env variable. In the service consumed by astro component it is working as expected in the component using react I get undefined. I add images with some code.

Could you help me to use variables in a react component. thanks!!

tender notch
#

I have a similar issue, did you solve this @past dove ?

#

Basically the problem seems to be that import.meta.env.* only works on .astro files, but not on custom.ts files

pulsar creek
#

Can either of you try prefixing your variables with VITE_

So @past dove can you try VITE_API_URL

#

Inside the .env

#

And then reference them with the same name

#

import.meta.env.VITE_API_URL

tender notch
#

@pulsar creek so you're saying then (if I understand correctly) that .astro files have something to support the .env vars right away without the VITE_ prefix but custom .ts / .js files don't, am I right?

pulsar creek
#

Not really, I wouldn't claim to understand it that much

I just did some research online and in the Vite docs (because that's what handled the environmental variables) and from that research found other people with similar issues in react

Adding the VITE seemed to help in some situations

tender notch
#

oh got it, let me try it real quick I can confirm in a few minutes, ty for the explaination!

#

it doesn't seem to be working on my end

#

I'll probably send it as parameter via the .astro file

tender notch
#

I've fixed on my end, you need to prefix front-end .env variables with PUBLIC_

#

so my file.ts would have something like this:
export const COLOR = import.meta.env.PUBLIC_COLOR;

pulsar creek
#

Ah doh cause it's running on the client

#

Good find lol