1

I'm stuck on what seems like a simple task. I want to run a weather app I built in Svelte and run it on Replit. The app uses an API with a key, so I added my key to Secrets in Replit and gave it the name MY_API_KEY.

In the file that calls the API, I used the following:

const MY_API_KEY = process.env.MY_API_KEY;

Unfortunately, that doesn't work. My app doesn't load. When I change the variable in my file to include the key itself, the app runs fine, so I must not be calling up the environmental variable right. Does anyone know how this works in Svelte? I'd appreciate any help.

  • 1
    Are you trying to call the API from the front-end? If so, there is no way you can implement this securely, anyone could just take the compiled JavaScript and extract the secret. (or is this not actually a secret?) – smitop Mar 24 '22 at 23:37
  • 1
    Yes, I am calling the API from the front end. It's a free API, so the worst thing that could happen if someone steals it is denied access after too many API calls. –  Mar 25 '22 at 00:11

1 Answers1

2

The base Svelte template on Replit uses Vite for building it's apps. This means you can do it the Vite way:

Call your environment variables something like VITE_ApiKey=123 And in your code use import.meta.env.VITE_ApiKey

Note that this only works for environment variables prefixed with VITE_

Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41