0

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?

3
  • How are you executing your app on the server currently? Commented Dec 20, 2023 at 0:47
  • @erik258 i run "sudo service nginx start" Commented Dec 20, 2023 at 0:56
  • That starts nginx but nginx doesn't run your app directly, just proxies requests to your app. Vite is the thing that needs the environment variables Commented Dec 20, 2023 at 18:28

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.