Environment Variables For React App in AWS EC2

171 views Asked by At

I have a basic weather app built with React (Vite). I'm making an API call to the OpenWeather API. In my dev environment, I used a .env file.

I'm trying to host it now on AWS EC2 (Linux). I'm using Nginx as the web server and have the app running. But I can't make API calls due to not having access to the API key / environment variable.

How do I setup environment variables on this EC2 instance to get my app working?

I've tried exporting the environment variable in the shell directly (i.e. export VITE_OPENWEATHER_API_KEY=your_api_key_here). I rebuilt the production build and restarted the server. I'm not sure if there's any more to it but it didn't work.

I also tried to store it as a parameter in the AWS Systems Manager Parameter Store, made corresponding IAM policies and roles, and hooked it up to my EC2 instance. I have access to my parameter in my EC2 instance via the command: aws ssm get-parameter --name PARAMETER_NAME --with-decryption. I'm not sure how to load that into my app?

1

There are 1 answers

0
Cloudlady On

Vite exposes env variables on the special import.meta.env object.

Start by adding your API key as a permanent environment variable (VITE_OPENWEATHER_API_KEY). Then, you can try to add the following code line to the server.js file: import.meta.env.VITE_OPENWEATHER_API_KEY

Note that only variables prefixed with VITE_ are exposed to your Vite-processed code, so make sure you are naming the env var with that prefix.

You can find more info here: https://vitejs.dev/guide/env-and-mode