While using JS, there are two environments your code usually executes within - client(browser) OR server(node).
For the API key to remain a secret you need to ensure it never reaches the client in the first place. Any code reaching the client can be debugged easily for API keys etc.
So, how to achieve API key hiding?
Store the API keys on the backend and have the backend make the request for you.
e.g.
Instead of directly interacting with a 3rd party API from the client / front-end like so:
axios.get('https://api.some-weather api.com/weather?lat={lat}&lon={lon} &api_key={API_KEY}`)
you can just call your backend's API that can make the call to the 3rd-party API like so:
axios.get('https://api.your-project.com/ weather?lat={lat}&lon={lon}`)
your backend api can then call the 3rd-party API with the API key that's stored via an env file(exists only on the backend):
axios.get('https://api.some-weather api.com/weather?lat={lat}&lon={lon} &api_key={API_KEY}`)
this way you don't expose your API keys, they're not included in the build of your web app so they won't be seen in developer tools.
As soon as you try and use env vars directly in the frontend code, you are exposing them to the web. Usually via the bundler tool/ecosystem that will lift the env var out of the .env file and bake the value into the bundled frontend code.
Note:
Since you mentioned open source, I’d also add that it is good practice to have environment specific data and secrets to NOT go directly into source control.
Env variables (with .env files that are gitignored) mainly hides it from other developers in the source code, like the git repo and perhaps deployment logs.
API_KEYas a config option. Add a comment// Put your API key here (get it at http://....), so that developers who want to use your wrapper can use it.